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

<?php
$tabs = [
    'all'       => 'All Guests',
    'vip'       => 'VIP Guests',
    'repeat'    => 'Repeat Guests',
    'blacklist' => 'Blacklist',
];
?>

<div class="d-flex justify-content-between align-items-start mb-3">
    <div></div>
    <div>
    <button type="button" class="btn btn-outline-primary me-2" data-bs-toggle="modal" data-bs-target="#smartSearchModal"><i class="bi bi-stars me-1"></i>Smart Search</button>
    <a href="<?= site_url('guests/new') ?>" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Add Guest</a>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-6 col-xl">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Total Guests</div>
            <div class="fs-3 fw-bold"><?= $stats['total'] ?></div>
        </div></div>
    </div>
    <div class="col-6 col-xl">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Repeat Guests</div>
            <div class="fs-3 fw-bold"><?= $stats['repeat'] ?></div>
            <div class="text-muted small"><?= $stats['total'] > 0 ? round($stats['repeat'] / $stats['total'] * 100, 1) : 0 ?>%</div>
        </div></div>
    </div>
    <div class="col-6 col-xl">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">New Guests</div>
            <div class="fs-3 fw-bold"><?= $stats['new'] ?></div>
            <div class="text-muted small"><?= $stats['total'] > 0 ? round($stats['new'] / $stats['total'] * 100, 1) : 0 ?>%</div>
        </div></div>
    </div>
    <div class="col-6 col-xl">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">VIP Guests</div>
            <div class="fs-3 fw-bold"><?= $stats['vip'] ?></div>
            <div class="text-muted small"><?= $stats['total'] > 0 ? round($stats['vip'] / $stats['total'] * 100, 1) : 0 ?>%</div>
        </div></div>
    </div>
    <div class="col-6 col-xl">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Countries</div>
            <div class="fs-3 fw-bold"><?= $stats['countries'] ?></div>
        </div></div>
    </div>
    <div class="col-6 col-xl">
        <a href="<?= site_url('complaints?tab=open') ?>" class="text-decoration-none">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Open Complaints</div>
            <div class="fs-3 fw-bold <?= $stats['openComplaints'] > 0 ? 'text-danger' : '' ?>"><?= $stats['openComplaints'] ?></div>
        </div></div>
        </a>
    </div>
</div>

<div class="card">
    <div class="card-header p-0">
        <ul class="nav nav-tabs border-0 px-2 pt-2">
            <?php foreach ($tabs as $key => $label): ?>
                <li class="nav-item">
                    <a class="nav-link <?= ($filters['tab'] ?: 'all') === $key ? 'active' : '' ?>"
                       href="<?= site_url('guests') . '?' . http_build_query(array_merge($filters, ['tab' => $key])) ?>">
                        <?= esc($label) ?>
                    </a>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>

    <div class="card-body border-bottom">
        <form action="<?= site_url('guests') ?>" method="get" class="row g-2 align-items-center">
            <input type="hidden" name="tab" value="<?= esc($filters['tab']) ?>">
            <div class="col-md-4">
                <input type="search" name="q" class="form-control form-control-sm" placeholder="Search guest name, phone, or ID number" value="<?= esc($filters['q'] ?? '') ?>">
            </div>
            <div class="col-md-3">
                <select name="segment" class="form-select form-select-sm">
                    <option value="">All Segments</option>
                    <?php foreach ($lookups->guestSegments as $key => $meta): ?>
                        <option value="<?= $key ?>" <?= ($filters['segment'] ?? '') === $key ? 'selected' : '' ?>><?= esc($meta['label']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <select name="nationality" class="form-select form-select-sm">
                    <option value="">All Countries</option>
                    <?php foreach ($nationalities as $n): ?>
                        <option value="<?= esc($n) ?>" <?= ($filters['nationality'] ?? '') === $n ? 'selected' : '' ?>><?= esc($n) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-sm btn-outline-primary w-100"><i class="bi bi-funnel me-1"></i>Filter</button>
            </div>
        </form>
    </div>

    <div class="table-responsive">
        <table class="table mb-0 align-middle">
            <thead>
            <tr>
                <th>Guest</th>
                <th>Contact</th>
                <th>Country</th>
                <th>Segment</th>
                <th>Last Stay</th>
                <th>Total Stays</th>
                <th>Lifetime Value</th>
                <th></th>
            </tr>
            </thead>
            <tbody>
            <?php if (empty($guests)): ?>
                <tr><td colspan="8" class="text-center text-muted py-5">No guests match these filters.</td></tr>
            <?php endif; ?>
            <?php foreach ($guests as $g):
                $segMeta  = $lookups->guestSegments[$g->segment] ?? null;
                $initials = strtoupper(mb_substr($g->full_name, 0, 1));
            ?>
                <tr class="guest-row" style="cursor: pointer;" data-detail='<?= esc(json_encode([
                    'name'       => $g->full_name,
                    'segment'    => $segMeta['label'] ?? null,
                    'segmentBadge' => $segMeta['badge'] ?? null,
                    'blacklisted' => (bool) $g->is_blacklisted,
                    'email'      => $g->email,
                    'phone'      => $g->phone,
                    'country'    => $g->nationality,
                    'notes'      => $g->notes,
                    'totalStays' => $g->total_stays,
                    'lifetimeValue' => format_money($g->lifetime_value),
                    'lastStay'   => $g->last_stay ? date('d M Y', strtotime($g->last_stay)) : '—',
                    'profileUrl' => site_url('guests/' . $g->id),
                    'editUrl'    => site_url('guests/' . $g->id . '/edit'),
                ], JSON_UNESCAPED_SLASHES), 'attr') ?>'>
                    <td>
                        <div class="d-flex align-items-center gap-2">
                            <div class="user-avatar" style="width:32px;height:32px;font-size:0.72rem;"><?= esc($initials) ?></div>
                            <div>
                                <div class="fw-semibold small"><?= esc($g->full_name) ?></div>
                                <?php if ($g->is_blacklisted): ?><span class="badge bg-danger" style="font-size: 0.62rem;">Blacklisted</span><?php endif; ?>
                            </div>
                        </div>
                    </td>
                    <td class="small">
                        <div><?= esc($g->email ?: '—') ?></div>
                        <div class="text-muted"><?= esc($g->phone) ?></div>
                    </td>
                    <td class="small text-muted"><?= esc($g->nationality ?: '—') ?></td>
                    <td>
                        <?php if ($segMeta): ?><span class="badge bg-<?= $segMeta['badge'] ?>"><?= esc($segMeta['label']) ?></span><?php else: ?><span class="text-muted small">—</span><?php endif; ?>
                        <?php if ($g->loyalty_tier): ?><span class="badge bg-<?= ['gold' => 'warning text-dark', 'silver' => 'secondary', 'bronze' => 'danger-subtle text-dark'][$g->loyalty_tier] ?? 'secondary' ?>"><?= esc(ucfirst($g->loyalty_tier)) ?></span><?php endif; ?>
                        <?php if ($g->dining_tier): ?><span class="badge bg-<?= $lookups->diningMembershipTiers[$g->dining_tier]['badge'] ?? 'secondary' ?>"><i class="bi bi-cup-hot"></i></span><?php endif; ?>
                    </td>
                    <td class="small text-muted"><?= $g->last_stay ? esc(date('d M Y', strtotime($g->last_stay))) : '—' ?></td>
                    <td class="small"><?= $g->total_stays ?></td>
                    <td class="small fw-semibold"><?= format_money($g->lifetime_value) ?></td>
                    <td class="text-end">
                        <a href="<?= site_url('guests/' . $g->id) ?>" class="btn btn-sm btn-outline-secondary" onclick="event.stopPropagation();"><i class="bi bi-eye"></i></a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="card-footer bg-white d-flex justify-content-between align-items-center">
        <span class="text-muted small">Showing <?= count($guests) ?> of <?= $pager->getTotal() ?> results</span>
        <?= $pager->links() ?>
    </div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="guestDetail">
    <div class="offcanvas-header border-bottom">
        <h5 class="offcanvas-title" id="gdName">—</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
    </div>
    <div class="offcanvas-body">
        <div class="mb-3" id="gdBadges"></div>

        <h6 class="text-muted text-uppercase small fw-bold mb-2">Contact</h6>
        <div class="mb-3 small">
            <div id="gdEmail" class="mb-1"></div>
            <div id="gdPhone" class="mb-1"></div>
            <div id="gdCountry" class="text-muted"></div>
        </div>

        <h6 class="text-muted text-uppercase small fw-bold mb-2">Stay Summary</h6>
        <div class="row row-cols-3 g-2 mb-3 small text-center">
            <div class="col"><div class="text-muted">Stays</div><div class="fw-bold" id="gdStays">—</div></div>
            <div class="col"><div class="text-muted">Lifetime Value</div><div class="fw-bold" id="gdValue">—</div></div>
            <div class="col"><div class="text-muted">Last Stay</div><div class="fw-bold" id="gdLastStay">—</div></div>
        </div>

        <h6 class="text-muted text-uppercase small fw-bold mb-2">Notes</h6>
        <p class="small text-muted" id="gdNotes">—</p>

        <div class="d-grid gap-2 mt-4">
            <a href="#" id="gdProfileBtn" class="btn btn-primary"><i class="bi bi-person-lines-fill me-1"></i>View Full Profile</a>
            <a href="#" id="gdEditBtn" class="btn btn-outline-secondary"><i class="bi bi-pencil me-1"></i>Edit Guest</a>
        </div>
    </div>
</div>

<!-- Smart Search: Claude interprets the query into real tool calls (search_records) against guests.notes/guest_preferences/complaints — the guest cards below are built from what those tools actually returned, never from Claude's own prose. See GuestController::smartSearch(). -->
<div class="modal fade" id="smartSearchModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-stars me-2"></i>Smart Search</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="text-muted small">Ask a natural-language question — e.g. "find the guest who complained about AC last month" or "who has a peanut allergy". Searches real guest notes, preferences, and complaints only.</p>
                <div class="input-group mb-3">
                    <input type="text" class="form-control" id="smartSearchInput" placeholder="Ask a question...">
                    <button type="button" class="btn btn-primary" id="smartSearchBtn"><i class="bi bi-search me-1"></i>Search</button>
                </div>
                <div id="smartSearchResults"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
const guestOffcanvas = new bootstrap.Offcanvas(document.getElementById('guestDetail'));

document.querySelectorAll('.guest-row').forEach(function (row) {
    row.addEventListener('click', function () {
        const d = JSON.parse(row.dataset.detail);
        document.getElementById('gdName').textContent = d.name;

        let badges = '';
        if (d.segment) { badges += '<span class="badge bg-' + d.segmentBadge + ' me-1">' + d.segment + '</span>'; }
        if (d.blacklisted) { badges += '<span class="badge bg-danger">Blacklisted</span>'; }
        document.getElementById('gdBadges').innerHTML = badges || '<span class="text-muted small">No tags</span>';

        document.getElementById('gdEmail').innerHTML = d.email ? '<i class="bi bi-envelope me-1"></i>' + d.email : '';
        document.getElementById('gdPhone').innerHTML = '<i class="bi bi-telephone me-1"></i>' + d.phone;
        document.getElementById('gdCountry').textContent = d.country || '';

        document.getElementById('gdStays').textContent = d.totalStays;
        document.getElementById('gdValue').textContent = d.lifetimeValue;
        document.getElementById('gdLastStay').textContent = d.lastStay;

        document.getElementById('gdNotes').textContent = d.notes || 'No notes on file.';

        document.getElementById('gdProfileBtn').href = d.profileUrl;
        document.getElementById('gdEditBtn').href = d.editUrl;

        guestOffcanvas.show();
    });
});

function runSmartSearch() {
    const query = document.getElementById('smartSearchInput').value.trim();
    const resultsEl = document.getElementById('smartSearchResults');
    const btn = document.getElementById('smartSearchBtn');

    if (! query) {
        resultsEl.textContent = '';
        const warn = document.createElement('div');
        warn.className = 'text-danger small';
        warn.textContent = 'Enter a question first.';
        resultsEl.appendChild(warn);
        return;
    }

    btn.disabled = true;
    resultsEl.textContent = '';
    const loading = document.createElement('div');
    loading.className = 'text-muted small';
    loading.textContent = 'Searching real guest records...';
    resultsEl.appendChild(loading);

    window.maxyieldsPost('<?= site_url('guests/smart-search') ?>', { query: query })
        .then(function (data) {
            resultsEl.textContent = '';

            if (! data.success) {
                const err = document.createElement('div');
                err.className = 'text-danger small';
                err.textContent = data.error;
                resultsEl.appendChild(err);
                return;
            }

            const explanation = document.createElement('div');
            explanation.className = 'alert alert-primary py-2 small';
            explanation.textContent = data.explanation; // Claude's own text — never innerHTML.
            resultsEl.appendChild(explanation);

            if (data.matches.length === 0) {
                const none = document.createElement('div');
                none.className = 'text-muted small';
                none.textContent = 'No matching real records found.';
                resultsEl.appendChild(none);
                return;
            }

            const sourceLabels = { guest_notes: 'Guest Note', guest_preferences: 'Preference', complaints: 'Complaint' };

            data.matches.forEach(function (m) {
                const card = document.createElement('div');
                card.className = 'card mb-2';
                const body = document.createElement('div');
                body.className = 'card-body py-2 px-3';

                const link = document.createElement('a');
                link.href = '<?= site_url('guests') ?>/' + m.guest_id;
                link.className = 'fw-semibold text-decoration-none small';
                link.textContent = m.guest_name;
                body.appendChild(link);

                const badge = document.createElement('span');
                badge.className = 'badge bg-light text-dark border ms-2';
                badge.textContent = sourceLabels[m.source] || m.source;
                body.appendChild(badge);

                if (m.date) {
                    const dateSpan = document.createElement('span');
                    dateSpan.className = 'text-muted small ms-2';
                    dateSpan.textContent = m.date;
                    body.appendChild(dateSpan);
                }

                const snippet = document.createElement('div');
                snippet.className = 'text-muted small mt-1';
                snippet.textContent = m.snippet;
                body.appendChild(snippet);

                card.appendChild(body);
                resultsEl.appendChild(card);
            });
        })
        .catch(function () {
            resultsEl.textContent = '';
            const err = document.createElement('div');
            err.className = 'text-danger small';
            err.textContent = 'Could not reach the server — please try again.';
            resultsEl.appendChild(err);
        })
        .finally(function () {
            btn.disabled = false;
        });
}

document.getElementById('smartSearchBtn').addEventListener('click', runSmartSearch);
document.getElementById('smartSearchInput').addEventListener('keydown', function (e) {
    if (e.key === 'Enter') { e.preventDefault(); runSmartSearch(); }
});
</script>
<?= $this->endSection() ?>
