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

<?php
$sourceMeta = [
    'walk_in'   => ['label' => 'Walk-in', 'icon' => 'bi-person-walking'],
    'phone'     => ['label' => 'Phone', 'icon' => 'bi-telephone'],
    'online'    => ['label' => 'Online', 'icon' => 'bi-globe'],
    'corporate' => ['label' => 'Corporate', 'icon' => 'bi-briefcase'],
];
$tabs = [
    'all'       => 'All Reservations',
    'confirmed' => 'Confirmed',
    'in_house'  => 'In House',
    'due_in'    => 'Due In',
    'due_out'   => 'Due Out',
    'cancelled' => 'Cancelled',
    'no_show'   => 'No Show',
];
?>

<div class="d-flex justify-content-between align-items-start mb-3">
    <div></div>
    <a href="<?= site_url('bookings/new') ?>" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>New Reservation</a>
</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 Reservations</div>
            <div class="fs-3 fw-bold"><?= $stats['total'] ?></div>
            <div class="small <?= $stats['createdTodayPct'] >= 0 ? 'text-success' : 'text-danger' ?>">
                <i class="bi bi-arrow-<?= $stats['createdTodayPct'] >= 0 ? 'up' : 'down' ?>"></i> <?= abs($stats['createdTodayPct']) ?>% new today
            </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">Confirmed</div>
            <div class="fs-3 fw-bold"><?= $stats['confirmed'] ?></div>
            <div class="text-muted small"><?= round($stats['confirmed'] / $stats['totalAll'] * 100) ?>% of 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">Check In Today</div>
            <div class="fs-3 fw-bold"><?= $stats['checkInToday'] ?></div>
            <div class="small <?= $stats['checkInToday'] >= $stats['checkInYesterday'] ? 'text-success' : 'text-danger' ?>">
                <i class="bi bi-arrow-<?= $stats['checkInToday'] >= $stats['checkInYesterday'] ? 'up' : 'down' ?>"></i>
                <?= abs($stats['checkInToday'] - $stats['checkInYesterday']) ?> vs yesterday
            </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">In House</div>
            <div class="fs-3 fw-bold"><?= $stats['inHouse'] ?></div>
            <div class="text-muted small"><?= round($stats['inHouse'] / $stats['totalAll'] * 100, 1) ?>% of 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">Cancelled</div>
            <div class="fs-3 fw-bold"><?= $stats['cancelled'] ?></div>
            <div class="text-muted small"><?= round($stats['cancelled'] / $stats['totalAll'] * 100) ?>% of total</div>
        </div></div>
    </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('bookings') . '?' . 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('bookings') ?>" method="get" class="row g-2 align-items-center">
            <input type="hidden" name="tab" value="<?= esc($filters['tab']) ?>">
            <div class="col-md-3">
                <input type="search" name="q" class="form-control form-control-sm" placeholder="Search guest, phone, email, #..." value="<?= esc($filters['q'] ?? '') ?>">
            </div>
            <div class="col-md-2">
                <input type="date" name="date_from" class="form-control form-control-sm" value="<?= esc($filters['date_from'] ?? '') ?>" title="Check-in from">
            </div>
            <div class="col-md-2">
                <input type="date" name="date_to" class="form-control form-control-sm" value="<?= esc($filters['date_to'] ?? '') ?>" title="Check-in to">
            </div>
            <div class="col-md-2">
                <select name="room_type_id" class="form-select form-select-sm">
                    <option value="">All Room Types</option>
                    <?php foreach ($roomTypes as $rt): ?>
                        <option value="<?= $rt->id ?>" <?= ((string) ($filters['room_type_id'] ?? '')) === (string) $rt->id ? 'selected' : '' ?>><?= esc($rt->name) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <select name="source" class="form-select form-select-sm">
                    <option value="">All Sources</option>
                    <?php foreach ($sourceMeta as $key => $meta): ?>
                        <option value="<?= $key ?>" <?= ($filters['source'] ?? '') === $key ? 'selected' : '' ?>><?= esc($meta['label']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-1">
                <button type="submit" class="btn btn-sm btn-outline-primary w-100"><i class="bi bi-funnel"></i></button>
            </div>
        </form>
    </div>

    <div class="table-responsive">
        <table class="table mb-0 align-middle">
            <thead>
            <tr>
                <th>Confirmation #</th>
                <th>Guest</th>
                <th>Check In</th>
                <th>Check Out</th>
                <th>Room / Rate</th>
                <th>Status</th>
                <th>Total</th>
                <th>Source</th>
                <th></th>
            </tr>
            </thead>
            <tbody>
            <?php if (empty($bookings)): ?>
                <tr><td colspan="9" class="text-center text-muted py-5">No reservations match these filters.</td></tr>
            <?php endif; ?>
            <?php foreach ($bookings as $b):
                $badge  = $lookups->bookingStatuses[$b->status]['badge'] ?? 'secondary';
                $label  = $lookups->bookingStatuses[$b->status]['label'] ?? ucfirst($b->status);
                $src    = $sourceMeta[$b->source] ?? ['label' => ucfirst($b->source), 'icon' => 'bi-question-circle'];
                $confNo = sprintf('BK-%04d', $b->id);
            ?>
                <tr class="booking-row" style="cursor: pointer;" data-detail='<?= esc(json_encode([
                    'confNo'   => $confNo,
                    'status'   => $label,
                    'badge'    => $badge,
                    'name'     => $b->guest_name,
                    'email'    => $b->guest_email,
                    'phone'    => $b->guest_phone,
                    'checkIn'  => $b->check_in_date,
                    'checkOut' => $b->check_out_date,
                    'nights'   => $b->nights,
                    'room'     => $b->room_number . ' — ' . $b->room_type_name,
                    'rate'     => format_money($b->rate_applied) . ' / night',
                    'source'   => $src['label'],
                    'total'    => format_money($b->total),
                    'payment'  => $b->payment_status,
                    'bookingUrl' => site_url('bookings/' . $b->id),
                    'cancelUrl'  => site_url('bookings/' . $b->id . '/cancel'),
                    'noShowUrl'  => site_url('bookings/' . $b->id . '/no-show'),
                    'canCancel'  => in_array($b->status, ['confirmed', 'pending_deposit'], true),
                ], JSON_UNESCAPED_SLASHES), 'attr') ?>'>
                    <td class="fw-semibold"><?= esc($confNo) ?></td>
                    <td>
                        <div class="fw-semibold small"><?= esc($b->guest_name) ?></div>
                        <div class="text-muted" style="font-size: 0.75rem;"><?= esc($b->guest_email ?: $b->guest_phone) ?></div>
                    </td>
                    <td class="small"><?= esc(date('d M Y', strtotime($b->check_in_date))) ?></td>
                    <td class="small"><?= esc(date('d M Y', strtotime($b->check_out_date))) ?></td>
                    <td>
                        <div class="small"><?= esc($b->room_type_name) ?> · <?= esc($b->room_number) ?></div>
                        <div class="text-muted" style="font-size: 0.75rem;"><?= format_money($b->rate_applied) ?>/night</div>
                    </td>
                    <td><span class="badge bg-<?= $badge ?>"><?= esc($label) ?></span></td>
                    <td class="fw-semibold"><?= format_money($b->total) ?></td>
                    <td class="small"><i class="bi <?= $src['icon'] ?> me-1 text-muted"></i><?= esc($src['label']) ?></td>
                    <td class="text-end">
                        <a href="<?= site_url('bookings/' . $b->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($bookings) ?> of <?= $pager->getTotal() ?> results</span>
        <?= $pager->links() ?>
    </div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="bookingDetail">
    <div class="offcanvas-header border-bottom">
        <h5 class="offcanvas-title" id="detailConfNo">—</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
    </div>
    <div class="offcanvas-body">
        <span class="badge mb-3" id="detailStatus">—</span>

        <h6 class="text-muted text-uppercase small fw-bold mb-2">Guest Information</h6>
        <div class="mb-3">
            <div class="fw-semibold" id="detailName">—</div>
            <div class="text-muted small" id="detailEmail"></div>
            <div class="text-muted small" id="detailPhone"></div>
        </div>

        <h6 class="text-muted text-uppercase small fw-bold mb-2">Reservation Details</h6>
        <div class="row row-cols-2 g-2 mb-3 small">
            <div class="col"><span class="text-muted">Check In</span><br><span id="detailCheckIn">—</span></div>
            <div class="col"><span class="text-muted">Check Out</span><br><span id="detailCheckOut">—</span></div>
            <div class="col"><span class="text-muted">Nights</span><br><span id="detailNights">—</span></div>
            <div class="col"><span class="text-muted">Room / Rate</span><br><span id="detailRoom">—</span></div>
            <div class="col"><span class="text-muted">Source</span><br><span id="detailSource">—</span></div>
            <div class="col"><span class="text-muted">Confirmation #</span><br><span id="detailConfNo2">—</span></div>
            <div class="col"><span class="text-muted">Total</span><br><span id="detailTotal">—</span></div>
            <div class="col"><span class="text-muted">Payment Status</span><br><span id="detailPayment">—</span></div>
        </div>

        <div class="d-grid gap-2 mt-4">
            <a href="#" id="detailViewBtn" class="btn btn-primary"><i class="bi bi-eye me-1"></i>View Reservation</a>
            <form id="detailCancelForm" action="#" method="post">
                <?= csrf_field() ?>
                <button type="submit" class="btn btn-outline-danger w-100" onclick="return confirm('Cancel this booking?');"><i class="bi bi-x-circle me-1"></i>Cancel Booking</button>
            </form>
            <form id="detailNoShowForm" action="#" method="post">
                <?= csrf_field() ?>
                <button type="submit" class="btn btn-outline-dark w-100" onclick="return confirm('Mark this booking as a no-show?');"><i class="bi bi-person-x me-1"></i>Mark No-Show</button>
            </form>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
const paymentBadges = { paid: 'success', partial: 'warning', unpaid: 'secondary' };
const offcanvasEl = document.getElementById('bookingDetail');
const offcanvas = new bootstrap.Offcanvas(offcanvasEl);

document.querySelectorAll('.booking-row').forEach(function (row) {
    row.addEventListener('click', function () {
        const d = JSON.parse(row.dataset.detail);
        document.getElementById('detailConfNo').textContent = d.confNo;
        document.getElementById('detailConfNo2').textContent = d.confNo;
        const statusEl = document.getElementById('detailStatus');
        statusEl.textContent = d.status;
        statusEl.className = 'badge mb-3 bg-' + d.badge;
        document.getElementById('detailName').textContent = d.name;
        document.getElementById('detailEmail').textContent = d.email || '';
        document.getElementById('detailPhone').textContent = d.phone || '';
        document.getElementById('detailCheckIn').textContent = d.checkIn;
        document.getElementById('detailCheckOut').textContent = d.checkOut;
        document.getElementById('detailNights').textContent = d.nights;
        document.getElementById('detailRoom').textContent = d.room + ' — ' + d.rate;
        document.getElementById('detailSource').textContent = d.source;
        document.getElementById('detailTotal').textContent = d.total;

        const payEl = document.getElementById('detailPayment');
        if (d.payment) {
            payEl.innerHTML = '<span class="badge bg-' + (paymentBadges[d.payment] || 'secondary') + '">' + d.payment.charAt(0).toUpperCase() + d.payment.slice(1) + '</span>';
        } else {
            payEl.innerHTML = '<span class="text-muted">Not yet billed</span>';
        }

        document.getElementById('detailViewBtn').href = d.bookingUrl;
        const cancelForm = document.getElementById('detailCancelForm');
        cancelForm.action = d.cancelUrl;
        cancelForm.style.display = d.canCancel ? 'block' : 'none';

        const noShowForm = document.getElementById('detailNoShowForm');
        noShowForm.action = d.noShowUrl;
        noShowForm.style.display = d.canCancel ? 'block' : 'none';

        offcanvas.show();
    });
});
</script>
<?= $this->endSection() ?>
