<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<?= view('bookings/_wizard_steps', ['step' => 3]) ?>

<div class="row">
    <div class="col-lg-8 mb-3">
        <div class="card">
            <div class="card-header p-0">
                <ul class="nav nav-tabs border-0 px-2 pt-2" id="guestTabs">
                    <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tab-existing">Existing Guest</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-new">New Guest</a></li>
                </ul>
            </div>
            <div class="card-body">
                <div class="tab-content">
                    <div class="tab-pane fade show active" id="tab-existing">
                        <div class="input-group icon-input-group mb-3">
                            <span class="input-group-text"><i class="bi bi-search"></i></span>
                            <input type="text" class="form-control" id="guestSearch" placeholder="Search guest by name, phone, or ID…" autocomplete="off">
                        </div>
                        <div id="guestResults" class="list-group"></div>
                        <p class="text-muted small mt-2" id="guestResultsHint">Type at least 2 characters to search.</p>
                    </div>

                    <div class="tab-pane fade" id="tab-new">
                        <form id="newGuestForm">
                            <div class="mb-3">
                                <label class="form-label small fw-semibold">Full Name</label>
                                <input type="text" class="form-control" id="new_full_name" placeholder="Guest's full name">
                            </div>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">Phone</label>
                                    <input type="text" class="form-control" id="new_phone" placeholder="024XXXXXXX">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold">Email <span class="text-muted fw-normal">(optional)</span></label>
                                    <input type="email" class="form-control" id="new_email">
                                </div>
                            </div>
                            <p class="text-muted small mt-2 mb-0">ID/passport and nationality are captured at check-in.</p>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card shadow-sm">
            <div class="card-header">Guest Information</div>
            <div class="card-body" id="guestInfoPanel">
                <p class="text-muted small mb-0">Search for and select an existing guest, or switch to New Guest.</p>
            </div>
        </div>
    </div>
</div>

<form action="<?= site_url('bookings/wizard/guest') ?>" method="post" id="guestStepForm">
    <?= csrf_field() ?>
    <input type="hidden" name="guest_id" id="guest_id_field" value="<?= (int) ($wizard['guest_id'] ?? 0) ?>">
    <input type="hidden" name="full_name" id="full_name_field">
    <input type="hidden" name="phone" id="phone_field">
    <input type="hidden" name="email" id="email_field">

    <div class="d-flex gap-2 mt-3">
        <a href="<?= site_url('bookings/search?check_in=' . urlencode($wizard['check_in']) . '&check_out=' . urlencode($wizard['check_out'])) ?>" class="btn btn-outline-secondary">Back</a>
        <button type="submit" class="btn btn-primary">Continue to Reservation Details</button>
    </div>
</form>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
let selectedGuest = null;

function renderGuestInfo(g) {
    document.getElementById('guestInfoPanel').innerHTML =
        '<div class="d-flex align-items-center gap-2 mb-3">' +
            '<div class="user-avatar" style="width:44px;height:44px;">' + g.full_name.charAt(0).toUpperCase() + '</div>' +
            '<div><div class="fw-semibold">' + g.full_name + '</div><div class="text-muted small">GUEST-' + String(g.id).padStart(5, '0') + '</div></div>' +
        '</div>' +
        '<dl class="row mb-0 small">' +
            '<dt class="col-5">Phone</dt><dd class="col-7">' + (g.phone || '—') + '</dd>' +
            '<dt class="col-5">Email</dt><dd class="col-7">' + (g.email || '—') + '</dd>' +
            '<dt class="col-5">Nationality</dt><dd class="col-7">' + (g.nationality || '—') + '</dd>' +
            '<dt class="col-5">ID/Passport</dt><dd class="col-7">' + (g.id_number || '—') + '</dd>' +
            '<dt class="col-5">Address</dt><dd class="col-7">' + (g.address || '—') + '</dd>' +
        '</dl>';
}

const guestSearch = document.getElementById('guestSearch');
let searchDebounce;
guestSearch.addEventListener('input', function () {
    clearTimeout(searchDebounce);
    const q = this.value.trim();
    const resultsEl = document.getElementById('guestResults');
    const hintEl = document.getElementById('guestResultsHint');

    if (q.length < 2) {
        resultsEl.innerHTML = '';
        hintEl.textContent = 'Type at least 2 characters to search.';
        hintEl.classList.remove('d-none');
        return;
    }

    searchDebounce = setTimeout(function () {
        fetch('<?= site_url('guests/search-ajax') ?>?q=' + encodeURIComponent(q))
            .then((r) => r.json())
            .then((data) => {
                if (data.results.length === 0) {
                    resultsEl.innerHTML = '';
                    hintEl.textContent = 'No guests match "' + q + '".';
                    hintEl.classList.remove('d-none');
                    return;
                }
                hintEl.classList.add('d-none');
                resultsEl.innerHTML = '';
                data.results.forEach(function (g) {
                    const item = document.createElement('button');
                    item.type = 'button';
                    item.className = 'list-group-item list-group-item-action d-flex justify-content-between align-items-center';
                    item.innerHTML = '<span><strong>' + g.full_name + '</strong> <span class="text-muted small">' + (g.phone || '') + '</span></span><span class="btn btn-sm btn-outline-primary">Select Guest</span>';
                    item.addEventListener('click', function () {
                        selectedGuest = g;
                        renderGuestInfo(g);
                        document.getElementById('guest_id_field').value = g.id;
                        document.querySelectorAll('#guestResults .list-group-item').forEach((el) => el.classList.remove('active'));
                        item.classList.add('active');
                    });
                    resultsEl.appendChild(item);
                });
            });
    }, 300);
});

// Switching to New Guest clears any existing-guest selection, and vice versa.
document.querySelector('a[href="#tab-new"]').addEventListener('shown.bs.tab', function () {
    document.getElementById('guest_id_field').value = '0';
});
document.querySelector('a[href="#tab-existing"]').addEventListener('shown.bs.tab', function () {
    if (selectedGuest) {
        document.getElementById('guest_id_field').value = selectedGuest.id;
    }
});

document.getElementById('guestStepForm').addEventListener('submit', function (e) {
    const onNewTab = document.getElementById('tab-new').classList.contains('active');

    if (onNewTab) {
        document.getElementById('guest_id_field').value = '0';
        document.getElementById('full_name_field').value = document.getElementById('new_full_name').value;
        document.getElementById('phone_field').value = document.getElementById('new_phone').value;
        document.getElementById('email_field').value = document.getElementById('new_email').value;

        if (!document.getElementById('new_full_name').value.trim() || !document.getElementById('new_phone').value.trim()) {
            e.preventDefault();
            alert('Enter the new guest\'s name and phone.');
        }
    } else if (!document.getElementById('guest_id_field').value || document.getElementById('guest_id_field').value === '0') {
        e.preventDefault();
        alert('Search for and select a guest, or switch to New Guest.');
    }
});
</script>
<?= $this->endSection() ?>
