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

<?php
$segMeta  = $lookups->guestSegments[$guest->segment] ?? null;
$initials = strtoupper(mb_substr($guest->full_name, 0, 1));
?>

<div class="d-flex justify-content-between align-items-start mb-3">
    <div class="d-flex align-items-center gap-3">
        <div class="user-avatar" style="width:56px;height:56px;font-size:1.25rem;"><?= esc($initials) ?></div>
        <div>
            <h1 class="h3 mb-1"><?= esc($guest->full_name) ?></h1>
            <div class="d-flex align-items-center gap-2">
                <?php if ($segMeta): ?><span class="badge bg-<?= esc($segMeta['badge']) ?>"><?= esc($segMeta['label']) ?></span><?php endif; ?>
                <?php if ($loyaltyAccount): ?><span class="badge bg-<?= ['gold' => 'warning text-dark', 'silver' => 'secondary', 'bronze' => 'danger-subtle text-dark'][$loyaltyAccount->tier] ?? 'secondary' ?>"><i class="bi bi-award me-1"></i><?= esc(ucfirst($loyaltyAccount->tier)) ?> · <?= number_format($loyaltyAccount->points_balance) ?> pts</span><?php endif; ?>
                <?php if ($diningMembership && $diningMembership->status === 'active'): ?><span class="badge bg-<?= $lookups->diningMembershipTiers[$diningMembership->tier]['badge'] ?? 'secondary' ?>"><i class="bi bi-cup-hot me-1"></i><?= esc($lookups->diningMembershipTiers[$diningMembership->tier]['label'] ?? ucfirst($diningMembership->tier)) ?> Dining</span><?php endif; ?>
                <?php if ($guest->is_blacklisted): ?><span class="badge bg-danger">Blacklisted</span><?php endif; ?>
                <?php if ($noShowCount > 0): ?><span class="badge bg-warning text-dark">Room no-shows: <?= (int) $noShowCount ?></span><?php endif; ?>
                <?php if ($guest->restaurant_no_show_count > 0): ?><span class="badge bg-warning text-dark">Restaurant no-shows: <?= (int) $guest->restaurant_no_show_count ?></span><?php endif; ?>
            </div>
        </div>
    </div>
    <div class="d-flex gap-2">
        <a href="<?= site_url('complaints/new?guest_id=' . $guest->id) ?>" class="btn btn-outline-danger"><i class="bi bi-exclamation-octagon me-1"></i>Log Complaint</a>
        <a href="<?= site_url('guests/' . $guest->id . '/edit') ?>" class="btn btn-outline-secondary"><i class="bi bi-pencil me-1"></i>Edit</a>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Total Stays</div>
            <div class="fs-3 fw-bold"><?= $stats['totalStays'] ?></div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Total Nights</div>
            <div class="fs-3 fw-bold"><?= $stats['totalNights'] ?></div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Lifetime Value</div>
            <div class="fs-3 fw-bold"><?= format_money($stats['lifetimeValue']) ?></div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Last Stay</div>
            <div class="fs-3 fw-bold"><?= $stats['lastStay'] ? esc(date('d M Y', strtotime($stats['lastStay']))) : '—' ?></div>
        </div></div>
    </div>
</div>

<div class="row">
    <div class="col-md-4 mb-3">
        <div class="card shadow-sm">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-person-vcard" style="color: var(--brand);"></i> Contact Info
            </div>
            <div class="card-body">
                <dl class="row mb-0 small">
                    <dt class="col-5">Phone</dt><dd class="col-7"><?= esc($guest->phone) ?></dd>
                    <dt class="col-5">Email</dt><dd class="col-7"><?= esc($guest->email ?: '—') ?></dd>
                    <dt class="col-5">ID Type</dt><dd class="col-7"><?= esc($lookups->guestIdTypes[$guest->id_type]['label'] ?? '—') ?></dd>
                    <dt class="col-5">ID Number</dt><dd class="col-7"><?= esc($guest->id_number ?: '—') ?></dd>
                    <dt class="col-5">Nationality</dt><dd class="col-7"><?= esc($guest->nationality ?: '—') ?></dd>
                    <dt class="col-5">DOB</dt><dd class="col-7"><?= esc($guest->date_of_birth ?: '—') ?></dd>
                    <dt class="col-5">Anniversary</dt><dd class="col-7"><?= esc($guest->anniversary_date ?: '—') ?></dd>
                    <dt class="col-5">Address</dt><dd class="col-7"><?= esc($guest->address ?: '—') ?></dd>
                </dl>
            </div>
        </div>

        <div class="card shadow-sm mt-3">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-journal-text" style="color: var(--brand);"></i> Notes
            </div>
            <div class="card-body">
                <p class="mb-0 small"><?= nl2br(esc($guest->notes ?: 'No notes on file.')) ?></p>
            </div>
        </div>

        <div class="card shadow-sm mt-3">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-stars" style="color: var(--brand);"></i> Stay Preferences
            </div>
            <div class="card-body">
                <?php if ($preferences === null): ?>
                    <p class="mb-0 small text-muted">No preferences on file.</p>
                <?php else: ?>
                    <dl class="row mb-0 small">
                        <dt class="col-5">Room Type</dt><dd class="col-7"><?= esc($preferredRoomType->name ?? '—') ?></dd>
                        <dt class="col-5">Bed Type</dt><dd class="col-7"><?= esc($preferences->bed_type ?: '—') ?></dd>
                        <dt class="col-5">Dietary</dt><dd class="col-7"><?= esc($preferences->dietary_restrictions ?: '—') ?></dd>
                        <dt class="col-5">Allergies</dt><dd class="col-7"><?= esc($preferences->allergies ?: '—') ?></dd>
                        <dt class="col-5">Seating</dt><dd class="col-7"><?= esc($preferences->seating_preference ?: '—') ?></dd>
                        <dt class="col-5">Smoking</dt><dd class="col-7"><?= esc($lookups->smokingPreferences[$preferences->smoking_preference]['label'] ?? '—') ?></dd>
                        <?php if ($preferences->other_notes): ?>
                        <dt class="col-5">Other</dt><dd class="col-7"><?= esc($preferences->other_notes) ?></dd>
                        <?php endif; ?>
                    </dl>
                    <?php if ($preferences->ai_inferred_summary): ?>
                    <hr>
                    <div class="d-flex align-items-start gap-2">
                        <i class="bi bi-robot text-muted mt-1"></i>
                        <div>
                            <div class="small"><?= esc($preferences->ai_inferred_summary) ?></div>
                            <div class="text-muted" style="font-size: 0.7rem;">AI-inferred from real order/stay history — staff-facing only, never shown to the guest. Updated <?= esc(date('d M Y', strtotime($preferences->ai_inferred_at))) ?>.</div>
                        </div>
                    </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($loyaltyAccount): ?>
        <div class="card shadow-sm mt-3">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-award" style="color: var(--brand);"></i> Loyalty
            </div>
            <div class="card-body">
                <p class="mb-2">
                    <strong class="fs-5"><?= number_format($loyaltyAccount->points_balance) ?></strong> <span class="text-muted small">points</span>
                    <span class="badge bg-<?= ['gold' => 'warning text-dark', 'silver' => 'secondary', 'bronze' => 'danger-subtle text-dark'][$loyaltyAccount->tier] ?? 'secondary' ?> ms-1"><?= esc(ucfirst($loyaltyAccount->tier)) ?></span>
                </p>
                <?php if (empty($loyaltyTransactions)): ?>
                    <p class="text-muted small mb-0">No points activity yet.</p>
                <?php else: ?>
                    <ul class="list-group list-group-flush small">
                        <?php foreach (array_slice($loyaltyTransactions, 0, 8) as $tx): ?>
                            <li class="list-group-item d-flex justify-content-between px-0">
                                <span>
                                    <?= esc(ucfirst($tx->type)) ?>
                                    <span class="text-muted d-block" style="font-size: 0.75rem;"><?= esc(date('d M Y', strtotime($tx->created_at))) ?></span>
                                </span>
                                <strong class="<?= $tx->points >= 0 ? 'text-success' : 'text-danger' ?>"><?= $tx->points >= 0 ? '+' : '' ?><?= $tx->points ?></strong>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="card shadow-sm mt-3">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-cup-hot" style="color: var(--brand);"></i> Executive Dining
            </div>
            <div class="card-body">
                <?php if ($diningMembership && $diningMembership->status === 'active'): ?>
                    <p class="mb-2">
                        <span class="badge bg-<?= $lookups->diningMembershipTiers[$diningMembership->tier]['badge'] ?? 'secondary' ?>"><?= esc($lookups->diningMembershipTiers[$diningMembership->tier]['label'] ?? ucfirst($diningMembership->tier)) ?></span>
                        <span class="text-muted small d-block mt-1">Renews <?= esc(date('d M Y', strtotime($diningMembership->renewal_date))) ?></span>
                    </p>
                    <?php if ($diningBenefitsText): ?>
                        <p class="small mb-2"><?= nl2br(esc($diningBenefitsText)) ?></p>
                    <?php endif; ?>

                    <?php if (! empty($benefitUsage)): ?>
                        <p class="text-muted small mb-1 mt-2">Recent usage</p>
                        <ul class="list-group list-group-flush small mb-2">
                            <?php foreach (array_slice($benefitUsage, 0, 5) as $usage): ?>
                                <li class="list-group-item d-flex justify-content-between px-0">
                                    <span><?= esc($usage->benefit_description) ?></span>
                                    <span class="text-muted" style="font-size: 0.75rem;"><?= esc(date('d M', strtotime($usage->used_at))) ?></span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>

                    <form action="<?= site_url('guests/' . $guest->id . '/log-benefit-usage') ?>" method="post" class="row g-2 mb-2">
                        <?= csrf_field() ?>
                        <div class="col-8"><input type="text" class="form-control form-control-sm" name="benefit_description" placeholder="e.g. Free dessert" required></div>
                        <div class="col-4"><button type="submit" class="btn btn-sm btn-outline-primary w-100">Log</button></div>
                    </form>
                    <div class="d-flex gap-2">
                        <form action="<?= site_url('guests/' . $guest->id . '/renew-dining') ?>" method="post"><?= csrf_field() ?><button type="submit" class="btn btn-sm btn-outline-secondary">Renew</button></form>
                        <form action="<?= site_url('guests/' . $guest->id . '/cancel-dining') ?>" method="post"><?= csrf_field() ?><button type="submit" class="btn btn-sm btn-outline-danger">Cancel</button></form>
                    </div>
                <?php else: ?>
                    <p class="text-muted small">Not a member.</p>
                    <form action="<?= site_url('guests/' . $guest->id . '/join-dining') ?>" method="post" class="row g-2">
                        <?= csrf_field() ?>
                        <div class="col-8">
                            <select class="form-select form-select-sm" name="tier" required>
                                <option value="">Choose tier...</option>
                                <?php foreach ($lookups->diningMembershipTiers as $key => $meta): ?>
                                    <option value="<?= esc($key) ?>"><?= esc($meta['label']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-4"><button type="submit" class="btn btn-sm btn-primary w-100">Enroll</button></div>
                    </form>
                <?php endif; ?>
            </div>
        </div>

        <?php if (! empty($events)): ?>
        <div class="card shadow-sm mt-3">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-calendar-event" style="color: var(--brand);"></i> Event History
            </div>
            <ul class="list-group list-group-flush small">
                <?php foreach ($events as $event): ?>
                    <li class="list-group-item d-flex justify-content-between">
                        <a href="<?= site_url('events/' . $event->id) ?>" class="text-decoration-none"><?= esc($event->event_name) ?></a>
                        <span class="text-muted"><?= esc($event->event_date) ?></span>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>
    </div>

    <div class="col-md-8">
        <div class="card shadow-sm">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-clock-history" style="color: var(--brand);"></i> Stay History
            </div>
            <div class="table-scroll">
                <table class="table table-sm align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Dates</th>
                            <th>Room</th>
                            <th>Status</th>
                            <th>Folio Total</th>
                            <th>Balance</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($bookings)): ?>
                            <tr><td colspan="5" class="text-center text-muted py-4">No stays yet.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($bookings as $booking): ?>
                            <tr>
                                <td><a href="<?= site_url('bookings/' . $booking->id) ?>" class="text-decoration-none"><?= esc($booking->check_in_date) ?> &rarr; <?= esc($booking->check_out_date) ?></a></td>
                                <td><?= esc($booking->room_number) ?> (<?= esc($booking->room_type_name) ?>)</td>
                                <td>
                                    <span class="badge bg-<?= esc($lookups->bookingStatuses[$booking->status]['badge'] ?? 'secondary') ?>">
                                        <?= esc($lookups->bookingStatuses[$booking->status]['label'] ?? $booking->status) ?>
                                    </span>
                                </td>
                                <td><?= format_money($booking->folio_total) ?></td>
                                <td>
                                    <?php if ($booking->folio_id): ?>
                                        <a href="<?= site_url('folios/' . $booking->folio_id) ?>"><?= format_money($booking->folio_balance) ?></a>
                                    <?php else: ?>
                                        —
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card shadow-sm mt-3">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-chat-square-text" style="color: var(--brand);"></i> Communication Timeline
            </div>
            <div class="card-body">
                <form action="<?= site_url('guests/' . $guest->id . '/log-communication') ?>" method="post" class="row g-2 mb-3 border-bottom pb-3">
                    <?= csrf_field() ?>
                    <div class="col-auto">
                        <select class="form-select form-select-sm" name="channel">
                            <option value="call">Call</option>
                            <option value="note">Note</option>
                        </select>
                    </div>
                    <div class="col">
                        <input type="text" class="form-control form-control-sm" name="notes" placeholder="What happened / what was said..." required>
                    </div>
                    <div class="col-auto">
                        <button type="submit" class="btn btn-sm btn-outline-primary">Log</button>
                    </div>
                </form>

                <?php if (empty($timeline)): ?>
                    <p class="text-muted small mb-0">No calls, emails, WhatsApp/SMS, or notes logged yet.</p>
                <?php else: ?>
                    <?php
                    $timelineIcons = [
                        'whatsapp' => 'bi-whatsapp',
                        'sms'      => 'bi-chat-dots',
                        'email'    => 'bi-envelope',
                        'call'     => 'bi-telephone',
                        'note'     => 'bi-sticky',
                    ];
                    $timelineStatusBadge = [
                        'sent'   => 'success',
                        'failed' => 'danger',
                        'logged' => 'secondary',
                    ];
                    ?>
                    <ul class="list-unstyled mb-0">
                        <?php foreach ($timeline as $entry): ?>
                            <li class="d-flex gap-2 mb-3">
                                <i class="bi <?= esc($timelineIcons[$entry['type']] ?? 'bi-chat') ?> mt-1" style="color: var(--brand);"></i>
                                <div class="flex-grow-1">
                                    <div class="d-flex justify-content-between">
                                        <span class="small fw-semibold text-capitalize"><?= esc($entry['type']) ?></span>
                                        <span class="text-muted small"><?= esc(date('d M Y, g:ia', strtotime($entry['createdAt']))) ?></span>
                                    </div>
                                    <div class="small"><?= esc($entry['summary']) ?></div>
                                    <?php if ($entry['detail']): ?><div class="text-muted small"><?= esc($entry['detail']) ?></div><?php endif; ?>
                                    <span class="badge bg-<?= esc($timelineStatusBadge[$entry['status']] ?? 'secondary') ?> mt-1"><?= esc(ucfirst($entry['status'])) ?></span>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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