<?php
/**
 * Shared back-office layout — redesigned to match the user-supplied
 * "Hotel Dashboard" mockup (sidebar nav, light theme), replacing the
 * earlier top-navbar layout. Every screen still just extends this with
 * <?= $this->extend('layouts/main') ?> / fills 'content' (+ optional
 * 'styles'/'scripts') — nothing about that contract changed, only the
 * chrome around it, so no other view needed to change.
 *
 * Nav items for modules that don't exist yet (Housekeeping, Maintenance,
 * Inventory, Reports & Analytics — Phase 4) are shown disabled with a
 * "Soon" badge rather than omitted or linking to a 404, per explicit
 * user choice when this redesign was scoped.
 */
$tenant = service('tenantContext')->hasTenant() ? service('tenantContext')->getTenant() : null;
// safe_hex_color(), not esc(..., 'css') — see app/Helpers/theme_helper.php:
// the escaped version silently broke every --brand-colored background on
// every screen in the app (var(--brand) resolved to nothing, so anything
// using it fell back to transparent/default).
$primaryColor = safe_hex_color($tenant->primary_color ?? null, '#4f46e5');

$role          = session('userRole');
$isFrontDesk   = in_array($role, ['manager', 'front_desk'], true);
$isFnb         = in_array($role, ['manager', 'fnb'], true);
$isManager     = $role === 'manager';
// The two Phase 4 roles get their own minimal nav blocks below rather
// than joining $isFrontDesk (which pulls in bookings/check-in-out/guest
// CRM editing — exactly what the least-privilege default excludes for
// them). manager/front_desk already reach Housekeeping/Maintenance/Rooms
// via the $isFrontDesk block above unchanged; these two booleans are
// only true for staff who have NO other way to reach this nav.
$isHousekeepingOnly = $role === 'housekeeping';
$isAccountsOnly     = $role === 'accounts';

// Role Management (see RoleManagementController) — per-role nav
// visibility on top of the $isFrontDesk/$isFnb/$isManager boundaries
// above, which remain the actual (route-enforced) access control. One
// query for every module this role has an explicit override for;
// absent = visible, matching pre-existing behavior for anyone who's
// never touched Role Management.
$roleOverrides = $role ? (new \App\Models\RolePermissionModel())->forRole($role) : [];
$canAccess     = static fn (string $moduleKey) => $roleOverrides[$moduleKey] ?? true;

$path = trim(uri_string(), '/');
$is   = static fn (string $prefix) => $path === $prefix || str_starts_with($path, $prefix . '/');

// Initials for the avatar circle — fallback for staff who haven't
// uploaded a photo yet (see UserController::uploadPhoto()).
$userInitials = 'U';
if ($name = session('userName')) {
    $words = preg_split('/\s+/', trim($name));
    $userInitials = strtoupper(($words[0][0] ?? '') . ($words[count($words) - 1][0] ?? ''));
}

// Fetched fresh rather than cached in session, so a just-uploaded photo
// shows up immediately without forcing a re-login — same reasoning
// SettingsController re-fetches the tenant row fresh instead of trusting
// the request-cached tenantContext object.
$currentUserPhoto = null;
if (session('userId')) {
    $currentUserRow   = (new \App\Models\UserModel())->find(session('userId'));
    $currentUserPhoto = $currentUserRow->photo_path ?? null;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= esc($pageTitle ?? 'Dashboard') ?> · <?= esc($tenant->hotel_name ?? 'MaxYields PMS') ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root { --brand: <?= $primaryColor ?>; }
        * { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
        body { background-color: #f6f7fb; }

        .app-shell { min-height: 100vh; }
        /* Light sidebar — reverted back from the dark navy (#16182b)
           theme per explicit user request; back to matching the topbar/
           page content instead of contrasting with it. */
        .sidebar {
            width: 264px; flex-shrink: 0; background: #fff; border-right: 1px solid #eef0f3;
            min-height: 100vh; display: flex; flex-direction: column;
        }
        .sidebar .brand-block { padding: 1.15rem 1.15rem 0.9rem; display: flex; align-items: center; gap: 0.65rem; }
        .sidebar .brand-mark { width: 40px; height: 40px; border-radius: 11px; background: var(--brand); display: flex; align-items: center; justify-content: center; color: #fff; font-size: 1.15rem; flex-shrink: 0; }
        .sidebar .brand-name { font-weight: 800; font-size: 1.05rem; letter-spacing: -0.01em; color: #16182b; line-height: 1.2; }
        .sidebar .brand-sub { font-size: 0.72rem; color: #9ca3af; }
        .hotel-card { margin: 0.4rem 1rem 0.75rem; padding: 0.65rem 0.8rem; background: #f8f8fb; border-radius: 10px; display: flex; align-items: center; justify-content: space-between; }
        .hotel-card .hotel-name { font-size: 0.82rem; font-weight: 700; color: #16182b; }
        .hotel-card .hotel-id { font-size: 0.7rem; color: #9ca3af; }

        .nav-scroll { flex-grow: 1; overflow-y: auto; padding: 0.25rem 0.85rem 1rem; }
        .nav-section-label { font-size: 0.68rem; font-weight: 700; letter-spacing: 0.06em; color: #b0b3bd; text-transform: uppercase; padding: 0.9rem 0.6rem 0.35rem; }
        .side-link { color: #4b4f5c; border-radius: 8px; padding: 0.5rem 0.65rem; font-size: 0.865rem; font-weight: 500; display: flex; align-items: center; gap: 0.65rem; margin-bottom: 0.1rem; text-decoration: none; }
        .side-link i.bi { font-size: 1rem; width: 1.1rem; text-align: center; flex-shrink: 0; }
        .side-link:hover { background: #f4f4f8; color: #16182b; }
        .side-link.active { background: color-mix(in srgb, var(--brand) 10%, white); color: var(--brand); font-weight: 700; }
        .side-link .chevron { margin-left: auto; font-size: 0.75rem; transition: transform 0.15s ease; }
        .side-link[aria-expanded="true"] .chevron { transform: rotate(90deg); }
        .side-link.disabled { color: #c3c5cc; cursor: default; }
        .side-link.disabled:hover { background: none; color: #c3c5cc; }
        .soon-badge { margin-left: auto; font-size: 0.62rem; font-weight: 700; background: #f1f2f5; color: #9ca3af; border-radius: 999px; padding: 0.12rem 0.5rem; }
        .side-submenu { padding-left: 2rem; }
        .side-submenu .side-link { font-size: 0.82rem; padding-top: 0.4rem; padding-bottom: 0.4rem; }

        .help-card { margin: 0.75rem; padding: 0.95rem; border-radius: 12px; background: color-mix(in srgb, var(--brand) 7%, white); }
        .help-card .icon { width: 34px; height: 34px; border-radius: 9px; background: color-mix(in srgb, var(--brand) 15%, white); color: var(--brand); display: flex; align-items: center; justify-content: center; margin-bottom: 0.5rem; }
        .help-card h6 { font-size: 0.82rem; font-weight: 700; margin-bottom: 0.15rem; }
        .help-card p { font-size: 0.75rem; color: #6b7280; margin-bottom: 0.65rem; }

        .app-main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
        .topbar { background: #fff; border-bottom: 1px solid #eef0f3; padding: 0.85rem 1.5rem; display: flex; align-items: center; gap: 1rem; }
        .topbar .page-title { font-weight: 800; font-size: 1.15rem; letter-spacing: -0.01em; margin: 0; }
        .topbar .page-sub { font-size: 0.78rem; color: #9ca3af; }
        .topbar .page-sub a { color: #9ca3af; }
        .topbar .page-icon-box { width: 40px; height: 40px; border-radius: 10px; background: color-mix(in srgb, var(--brand) 12%, white); color: var(--brand); display: flex; align-items: center; justify-content: center; font-size: 1.1rem; flex-shrink: 0; }
        .topbar-search { flex-grow: 1; max-width: 420px; }
        .topbar-search .form-control { border-radius: 9px; background: #f6f7fb; border-color: transparent; font-size: 0.85rem; }
        .topbar-search .kbd-hint { font-size: 0.68rem; color: #b0b3bd; border: 1px solid #e5e7eb; border-radius: 5px; padding: 0.05rem 0.35rem; }
        .icon-btn { width: 38px; height: 38px; border-radius: 9px; border: 1px solid #eef0f3; background: #fff; display: flex; align-items: center; justify-content: center; color: #4b4f5c; position: relative; }
        .icon-btn:hover { background: #f6f7fb; }
        .user-chip { display: flex; align-items: center; gap: 0.6rem; padding: 0.3rem 0.5rem; border-radius: 9px; }
        .user-chip:hover { background: #f6f7fb; }
        .user-avatar { width: 36px; height: 36px; border-radius: 50%; background: var(--brand); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 0.82rem; flex-shrink: 0; }
        .user-chip .name { font-size: 0.84rem; font-weight: 700; color: #16182b; line-height: 1.15; }
        .user-chip .role { font-size: 0.72rem; color: #9ca3af; }

        .card { border: none; border-radius: 12px; box-shadow: 0 1px 2px rgba(16,24,40,0.04), 0 1px 3px rgba(16,24,40,0.06); }
        .card-header { background-color: #fff; border-bottom: 1px solid #eef0f3; font-weight: 600; }
        .btn { border-radius: 8px; font-weight: 500; }
        /* Bootstrap 5.3's .btn-primary rule only sets --bs-btn-* custom
           properties, not the actual background-color/border-color
           longhands — see auth/login.php's .btn-brand for the bug this
           avoids (confirmed via screenshot: text renders, background
           silently doesn't, when the longhands are set directly instead). */
        .btn-primary {
            --bs-btn-bg: var(--brand);
            --bs-btn-border-color: var(--brand);
            --bs-btn-hover-bg: var(--brand);
            --bs-btn-hover-border-color: var(--brand);
            --bs-btn-active-bg: var(--brand);
            --bs-btn-active-border-color: var(--brand);
        }
        .btn-primary:hover, .btn-primary:focus { filter: brightness(0.92); }
        .btn-outline-primary {
            --bs-btn-color: var(--brand);
            --bs-btn-border-color: var(--brand);
            --bs-btn-hover-bg: var(--brand);
            --bs-btn-hover-border-color: var(--brand);
            --bs-btn-active-bg: var(--brand);
            --bs-btn-active-border-color: var(--brand);
        }
        .form-control:focus, .form-select:focus { border-color: var(--brand); box-shadow: 0 0 0 0.2rem color-mix(in srgb, var(--brand) 18%, transparent); }
        .table thead th { font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.05em; color: #6b7280; background: #f9fafb; font-weight: 700; border-bottom-width: 1px; }
        .badge { font-weight: 600; }
        h1, h2, h3, .h1, .h2, .h3 { letter-spacing: -0.01em; }
        .status-clean { background-color: #d1e7dd; }
        .status-dirty { background-color: #fff3cd; }
        .status-occupied { background-color: #cfe2ff; }
        .status-out_of_service { background-color: #f8d7da; }
        .table-scroll { overflow-x: auto; }

        /* Multi-step flow indicator (e.g. New Booking: Search → Select
           Room → Guest & Confirm) — shared so every step of a wizard uses
           the same markup/classes instead of each view re-styling it. */
        .wizard-steps { display: flex; align-items: center; gap: 0.6rem; margin-bottom: 1.75rem; flex-wrap: wrap; }
        .wizard-steps .step-badge { width: 28px; height: 28px; border-radius: 50%; background: #f1f2f5; color: #9ca3af; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 0.82rem; flex-shrink: 0; }
        .wizard-steps .step-badge.active { background: var(--brand); color: #fff; }
        .wizard-steps .step-badge.done { background: #22c55e; color: #fff; }
        .wizard-steps .step-label { font-size: 0.85rem; color: #9ca3af; font-weight: 500; }
        .wizard-steps .step-label.active { color: #16182b; font-weight: 700; }
        .wizard-steps .step-line { width: 32px; height: 2px; background: #e5e7eb; flex-shrink: 0; }
        .icon-input-group .input-group-text { background: #f8f9fb; border-right: none; color: #9ca3af; }
        .icon-input-group .form-control, .icon-input-group .form-select { border-left: none; }
        .icon-input-group .form-control:focus, .icon-input-group .form-select:focus { box-shadow: none; border-color: #ced4da; }

        @media (max-width: 991.98px) {
            .sidebar.offcanvas-lg { --bs-offcanvas-width: 264px; }
        }
        <?= $this->renderSection('styles') ?>
    </style>
</head>
<body>
<?php if (session('isLoggedIn')): ?>
<div class="app-shell d-flex">
    <aside class="sidebar offcanvas-lg offcanvas-start" tabindex="-1" id="sidebarNav">
        <div class="d-flex d-lg-none justify-content-end p-2">
            <button type="button" class="btn-close" data-bs-dismiss="offcanvas" data-bs-target="#sidebarNav"></button>
        </div>
        <div class="brand-block">
            <div class="brand-mark"><i class="bi bi-buildings-fill"></i></div>
            <div>
                <div class="brand-name"><?= esc($tenant->hotel_name ?? 'MaxYields PMS') ?></div>
                <div class="brand-sub">Hotel Management System</div>
            </div>
        </div>

        <?php if ($tenant): ?>
        <div class="hotel-card">
            <div>
                <div class="hotel-name"><?= esc($tenant->hotel_name) ?></div>
                <div class="hotel-id">Hotel ID: <?= esc(sprintf('H%03d', $tenant->id)) ?></div>
            </div>
            <i class="bi bi-chevron-expand text-muted small"></i>
        </div>
        <?php endif; ?>

        <nav class="nav-scroll">
            <?php if ($canAccess('shifts')): ?>
            <a class="side-link <?= $is('shifts') ? 'active' : '' ?>" href="<?= site_url('shifts') ?>">
                <i class="bi bi-calendar3-week"></i> Shift Schedule
            </a>
            <?php endif; ?>

            <?php if ($isFrontDesk): ?>
            <div class="nav-section-label">Overview</div>
            <?php if ($canAccess('dashboard')): ?>
            <a class="side-link <?= $is('') && $path === '' ? 'active' : '' ?>" href="<?= site_url('/') ?>">
                <i class="bi bi-grid-1x2-fill"></i> Dashboard
            </a>
            <?php endif; ?>

            <div class="nav-section-label">Front Office</div>
            <?php if ($canAccess('reservations')): ?>
            <?php $reservationsActive = $is('bookings') || $is('group-bookings'); ?>
            <a class="side-link <?= $reservationsActive ? 'active' : '' ?>" data-bs-toggle="collapse" href="#navReservations" aria-expanded="<?= $reservationsActive ? 'true' : 'false' ?>">
                <i class="bi bi-calendar-check"></i> Reservations <i class="bi bi-chevron-right chevron"></i>
            </a>
            <div class="collapse side-submenu <?= $reservationsActive ? 'show' : '' ?>" id="navReservations">
                <a class="side-link <?= $path === 'bookings' ? 'active' : '' ?>" href="<?= site_url('bookings') ?>">All Reservations</a>
                <a class="side-link <?= $path === 'bookings/calendar' ? 'active' : '' ?>" href="<?= site_url('bookings/calendar') ?>">Calendar</a>
                <a class="side-link <?= $path === 'bookings/new' ? 'active' : '' ?>" href="<?= site_url('bookings/new') ?>">New Booking</a>
                <a class="side-link <?= $is('group-bookings') ? 'active' : '' ?>" href="<?= site_url('group-bookings') ?>">Group Bookings</a>
            </div>
            <?php endif; ?>

            <?php if ($canAccess('front_desk_ops')): ?>
            <?php $frontDeskActive = $is('checkin') || $is('checkout') || $is('folios') || $is('payments'); ?>
            <a class="side-link <?= $frontDeskActive ? 'active' : '' ?>" data-bs-toggle="collapse" href="#navFrontDesk" aria-expanded="<?= $frontDeskActive ? 'true' : 'false' ?>">
                <i class="bi bi-door-open"></i> Front Desk <i class="bi bi-chevron-right chevron"></i>
            </a>
            <div class="collapse side-submenu <?= $frontDeskActive ? 'show' : '' ?>" id="navFrontDesk">
                <a class="side-link <?= $is('checkin') ? 'active' : '' ?>" href="<?= site_url('checkin') ?>">Check-In</a>
                <a class="side-link <?= $is('checkout') ? 'active' : '' ?>" href="<?= site_url('checkout') ?>">Check-Out</a>
                <a class="side-link <?= $is('folios') ? 'active' : '' ?>" href="<?= site_url('folios') ?>">Folios</a>
                <a class="side-link <?= $is('payments') ? 'active' : '' ?>" href="<?= site_url('payments') ?>">Payments</a>
            </div>
            <?php endif; ?>

            <?php if ($canAccess('guests')): ?>
            <a class="side-link <?= ($is('guests') || $is('corporate-accounts')) ? 'active' : '' ?>" data-bs-toggle="collapse" href="#navGuests" aria-expanded="<?= ($is('guests') || $is('corporate-accounts')) ? 'true' : 'false' ?>">
                <i class="bi bi-people"></i> Guests <i class="bi bi-chevron-right chevron"></i>
            </a>
            <div class="collapse side-submenu <?= ($is('guests') || $is('corporate-accounts')) ? 'show' : '' ?>" id="navGuests">
                <a class="side-link <?= $is('guests') ? 'active' : '' ?>" href="<?= site_url('guests') ?>">All Guests</a>
                <a class="side-link <?= $is('corporate-accounts') ? 'active' : '' ?>" href="<?= site_url('corporate-accounts') ?>">Corporate Accounts</a>
            </div>
            <?php endif; ?>

            <?php if ($canAccess('rooms')): ?>
            <?php $roomsActive = $is('rooms') || $is('room-types'); ?>
            <a class="side-link <?= $roomsActive ? 'active' : '' ?>" data-bs-toggle="collapse" href="#navRooms" aria-expanded="<?= $roomsActive ? 'true' : 'false' ?>">
                <i class="bi bi-door-closed"></i> Rooms <i class="bi bi-chevron-right chevron"></i>
            </a>
            <div class="collapse side-submenu <?= $roomsActive ? 'show' : '' ?>" id="navRooms">
                <a class="side-link <?= $path === 'rooms/board' ? 'active' : '' ?>" href="<?= site_url('rooms/board') ?>">Room Management</a>
                <a class="side-link <?= $is('room-types') ? 'active' : '' ?>" href="<?= site_url('room-types') ?>">Room Types</a>
                <a class="side-link <?= ($is('rooms') && $path !== 'rooms/board') ? 'active' : '' ?>" href="<?= site_url('rooms') ?>">All Rooms</a>
            </div>
            <?php endif; ?>

            <?php if ($canAccess('housekeeping')): ?>
            <a class="side-link <?= $is('housekeeping') ? 'active' : '' ?>" href="<?= site_url('housekeeping') ?>">
                <i class="bi bi-bucket"></i> Housekeeping
            </a>
            <?php endif; ?>
            <?php if ($canAccess('maintenance')): ?>
            <a class="side-link <?= $is('maintenance') ? 'active' : '' ?>" href="<?= site_url('maintenance') ?>">
                <i class="bi bi-tools"></i> Maintenance
            </a>
            <?php endif; ?>
            <?php if ($canAccess('complaints')): ?>
            <a class="side-link <?= $is('complaints') ? 'active' : '' ?>" href="<?= site_url('complaints') ?>">
                <i class="bi bi-exclamation-octagon"></i> Service Recovery
            </a>
            <?php endif; ?>

            <?php if ($canAccess('ai_assistant') || $isManager): ?>
            <div class="nav-section-label">AI Tools</div>
            <?php if ($canAccess('ai_assistant')): ?>
            <a class="side-link <?= $is('ai/assistant') ? 'active' : '' ?>" href="<?= site_url('ai/assistant') ?>">
                <i class="bi bi-stars"></i> Booking Assistant
            </a>
            <?php endif; ?>
            <?php if ($isManager): ?>
            <?php if ($canAccess('ai_alerts')): ?>
            <a class="side-link <?= $is('ai/alerts') ? 'active' : '' ?>" href="<?= site_url('ai/alerts') ?>">
                <i class="bi bi-exclamation-triangle"></i> AI Alerts
            </a>
            <?php endif; ?>
            <?php if ($canAccess('ai_modules')): ?>
            <a class="side-link <?= $is('ai-modules') ? 'active' : '' ?>" href="<?= site_url('ai-modules') ?>">
                <i class="bi bi-graph-up-arrow"></i> AI Modules
            </a>
            <?php endif; ?>
            <?php if ($canAccess('guest_message_drafts')): ?>
            <a class="side-link <?= $is('guest-message-drafts') ? 'active' : '' ?>" href="<?= site_url('guest-message-drafts') ?>">
                <i class="bi bi-envelope-paper"></i> Guest Message Drafts
            </a>
            <?php endif; ?>
            <?php if ($canAccess('concierge')): ?>
            <a class="side-link <?= $is('concierge') ? 'active' : '' ?>" href="<?= site_url('concierge') ?>">
                <i class="bi bi-whatsapp"></i> WhatsApp Concierge
            </a>
            <?php endif; ?>
            <?php endif; ?>
            <?php endif; ?>
            <?php endif; // isFrontDesk ?>

            <?php if ($isHousekeepingOnly): ?>
            <div class="nav-section-label">Housekeeping</div>
            <?php if ($canAccess('rooms')): ?>
            <a class="side-link <?= $path === 'rooms/board' ? 'active' : '' ?>" href="<?= site_url('rooms/board') ?>">
                <i class="bi bi-door-closed"></i> Room Status
            </a>
            <?php endif; ?>
            <?php if ($canAccess('housekeeping')): ?>
            <a class="side-link <?= $is('housekeeping') ? 'active' : '' ?>" href="<?= site_url('housekeeping') ?>">
                <i class="bi bi-bucket"></i> Housekeeping
            </a>
            <?php endif; ?>
            <?php if ($canAccess('maintenance')): ?>
            <a class="side-link <?= $is('maintenance') ? 'active' : '' ?>" href="<?= site_url('maintenance') ?>">
                <i class="bi bi-tools"></i> Maintenance
            </a>
            <?php endif; ?>
            <?php endif; ?>

            <?php if ($isAccountsOnly): ?>
            <div class="nav-section-label">Finance &amp; Revenue</div>
            <?php if ($canAccess('billing_finance')): ?>
            <a class="side-link <?= $is('billing-finance') ? 'active' : '' ?>" href="<?= site_url('billing-finance') ?>">
                <i class="bi bi-cash-coin"></i> Billing &amp; Finance
            </a>
            <?php endif; ?>
            <?php if ($canAccess('invoicing')): ?>
            <a class="side-link <?= $is('folios') ? 'active' : '' ?>" href="<?= site_url('folios') ?>">
                <i class="bi bi-receipt"></i> Folios &amp; Invoicing
            </a>
            <a class="side-link <?= $is('payments') ? 'active' : '' ?>" href="<?= site_url('payments') ?>">
                <i class="bi bi-credit-card"></i> Payments
            </a>
            <?php endif; ?>
            <?php if ($canAccess('corporate_accounts')): ?>
            <a class="side-link <?= $is('corporate-accounts') ? 'active' : '' ?>" href="<?= site_url('corporate-accounts') ?>">
                <i class="bi bi-building"></i> Corporate Accounts
            </a>
            <?php endif; ?>
            <?php if ($canAccess('rate_plans')): ?>
            <a class="side-link <?= $is('rate-plans') ? 'active' : '' ?>" href="<?= site_url('rate-plans') ?>">
                <i class="bi bi-tags"></i> Rate Plans
            </a>
            <?php endif; ?>
            <?php if ($canAccess('expenses')): ?>
            <a class="side-link <?= $is('expenses') ? 'active' : '' ?>" href="<?= site_url('expenses') ?>">
                <i class="bi bi-receipt-cutoff"></i> Expenses
            </a>
            <?php endif; ?>
            <?php if ($canAccess('reports')): ?>
            <a class="side-link <?= $is('reports') ? 'active' : '' ?>" href="<?= site_url('reports') ?>">
                <i class="bi bi-graph-up"></i> Reports &amp; Analytics
            </a>
            <?php endif; ?>
            <?php endif; ?>

            <?php if ($isFnb): ?>
            <div class="nav-section-label">Restaurant &amp; Events</div>
            <?php if ($canAccess('restaurant')): ?>
            <?php $restaurantActive = $is('restaurant') || $is('dining') || $is('pos'); ?>
            <a class="side-link <?= $restaurantActive ? 'active' : '' ?>" data-bs-toggle="collapse" href="#navFnb" aria-expanded="<?= $restaurantActive ? 'true' : 'false' ?>">
                <i class="bi bi-cup-hot"></i> Restaurant (F&amp;B) <i class="bi bi-chevron-right chevron"></i>
            </a>
            <div class="collapse side-submenu <?= $restaurantActive ? 'show' : '' ?>" id="navFnb">
                <a class="side-link <?= $path === 'restaurant' ? 'active' : '' ?>" href="<?= site_url('restaurant') ?>">Overview</a>
                <a class="side-link <?= $path === 'dining/reservations' ? 'active' : '' ?>" href="<?= site_url('dining/reservations') ?>">Table Reservations</a>
                <a class="side-link <?= $is('pos/orders') ? 'active' : '' ?>" href="<?= site_url('pos/orders') ?>">Orders</a>
                <a class="side-link <?= $is('pos/kitchen') ? 'active' : '' ?>" href="<?= site_url('pos/kitchen') ?>">Kitchen Display</a>
                <a class="side-link <?= $is('pos/menu') ? 'active' : '' ?>" href="<?= site_url('pos/menu') ?>">Menu Items</a>
                <a class="side-link <?= $path === 'dining/areas' ? 'active' : '' ?>" href="<?= site_url('dining/areas') ?>">Dining Areas</a>
                <a class="side-link <?= $path === 'dining/tables' ? 'active' : '' ?>" href="<?= site_url('dining/tables') ?>">Dining Tables</a>
            </div>
            <?php endif; ?>

            <?php if ($canAccess('events')): ?>
            <a class="side-link <?= ($is('events') || $is('event-clients')) ? 'active' : '' ?>" data-bs-toggle="collapse" href="#navEvents" aria-expanded="<?= ($is('events') || $is('event-clients')) ? 'true' : 'false' ?>">
                <i class="bi bi-calendar-event"></i> Events <i class="bi bi-chevron-right chevron"></i>
            </a>
            <div class="collapse side-submenu <?= ($is('events') || $is('event-clients')) ? 'show' : '' ?>" id="navEvents">
                <a class="side-link <?= $is('events') ? 'active' : '' ?>" href="<?= site_url('events') ?>">Events</a>
                <a class="side-link <?= $is('event-clients') ? 'active' : '' ?>" href="<?= site_url('event-clients') ?>">Event Clients</a>
            </div>
            <?php endif; ?>

            <?php if (! $isFrontDesk && $canAccess('complaints')): ?>
            <a class="side-link <?= $is('complaints') ? 'active' : '' ?>" href="<?= site_url('complaints') ?>">
                <i class="bi bi-exclamation-octagon"></i> Service Recovery
            </a>
            <?php endif; ?>
            <?php endif; // isFnb ?>

            <?php if ($isManager): ?>
            <div class="nav-section-label">Finance &amp; Revenue</div>
            <?php if ($canAccess('billing_finance')): ?>
            <a class="side-link <?= $is('billing-finance') ? 'active' : '' ?>" href="<?= site_url('billing-finance') ?>">
                <i class="bi bi-cash-coin"></i> Billing &amp; Finance
            </a>
            <?php endif; ?>
            <?php if ($canAccess('rate_plans')): ?>
            <a class="side-link <?= $is('rate-plans') ? 'active' : '' ?>" href="<?= site_url('rate-plans') ?>">
                <i class="bi bi-tags"></i> Rate Plans
            </a>
            <?php endif; ?>
            <?php if ($canAccess('services')): ?>
            <a class="side-link <?= $is('services') ? 'active' : '' ?>" href="<?= site_url('services') ?>">
                <i class="bi bi-bag-plus"></i> Services &amp; Extras
            </a>
            <?php endif; ?>
            <?php if ($canAccess('expenses')): ?>
            <a class="side-link <?= $is('expenses') ? 'active' : '' ?>" href="<?= site_url('expenses') ?>">
                <i class="bi bi-receipt-cutoff"></i> Expenses
            </a>
            <?php endif; ?>
            <?php if ($canAccess('payroll')): ?>
            <a class="side-link <?= $is('payroll') ? 'active' : '' ?>" href="<?= site_url('payroll') ?>">
                <i class="bi bi-cash-stack"></i> Payroll
            </a>
            <?php endif; ?>
            <?php if ($canAccess('reports')): ?>
            <a class="side-link <?= $is('reports') ? 'active' : '' ?>" href="<?= site_url('reports') ?>">
                <i class="bi bi-graph-up"></i> Reports &amp; Analytics
            </a>
            <?php endif; ?>

            <div class="nav-section-label">Administration</div>
            <?php if ($canAccess('staff')): ?>
            <a class="side-link <?= $is('users') ? 'active' : '' ?>" href="<?= site_url('users') ?>">
                <i class="bi bi-person-badge"></i> Staff
            </a>
            <a class="side-link <?= $path === 'reports/staff-performance' ? 'active' : '' ?>" href="<?= site_url('reports/staff-performance') ?>">
                <i class="bi bi-bar-chart-steps"></i> Staff Performance
            </a>
            <?php endif; ?>
            <a class="side-link <?= $is('role-management') ? 'active' : '' ?>" href="<?= site_url('role-management') ?>">
                <i class="bi bi-shield-lock"></i> Role Management
            </a>
            <?php if ($canAccess('inventory')): ?>
            <a class="side-link <?= $is('inventory') ? 'active' : '' ?>" href="<?= site_url('inventory') ?>">
                <i class="bi bi-box-seam"></i> Inventory
            </a>
            <?php endif; ?>
            <?php if ($canAccess('communication')): ?>
            <a class="side-link <?= $is('communication') ? 'active' : '' ?>" href="<?= site_url('communication') ?>">
                <i class="bi bi-chat-dots"></i> Communication
            </a>
            <?php endif; ?>
            <?php if ($canAccess('campaigns')): ?>
            <a class="side-link <?= $is('campaigns') ? 'active' : '' ?>" href="<?= site_url('campaigns') ?>">
                <i class="bi bi-megaphone"></i> Email Campaigns
            </a>
            <?php endif; ?>
            <?php if ($canAccess('activity_log')): ?>
            <a class="side-link <?= $is('activity-log') ? 'active' : '' ?>" href="<?= site_url('activity-log') ?>">
                <i class="bi bi-clock-history"></i> Activity Log
            </a>
            <?php endif; ?>
            <a class="side-link <?= $is('backup') ? 'active' : '' ?>" href="<?= site_url('backup') ?>">
                <i class="bi bi-cloud-arrow-down"></i> Data Backup
            </a>
            <?php if ($canAccess('settings')): ?>
            <a class="side-link <?= $is('settings') ? 'active' : '' ?>" href="<?= site_url('settings') ?>">
                <i class="bi bi-gear"></i> Settings
            </a>
            <?php endif; ?>
            <?php endif; // isManager ?>
        </nav>

        <div class="help-card">
            <div class="icon"><i class="bi bi-question-circle"></i></div>
            <h6>Need Help?</h6>
            <p>Contact our support team for assistance.</p>
            <a href="mailto:support@maxyields.com" class="btn btn-outline-primary btn-sm w-100"><i class="bi bi-headset me-1"></i>Contact Support</a>
        </div>
    </aside>

    <div class="app-main">
        <div class="topbar">
            <button type="button" class="icon-btn d-lg-none" data-bs-toggle="offcanvas" data-bs-target="#sidebarNav"><i class="bi bi-list fs-5"></i></button>

            <div class="d-none d-md-flex align-items-center gap-2">
                <?php if (! empty($pageIcon)): ?>
                    <div class="page-icon-box"><i class="bi <?= esc($pageIcon) ?>"></i></div>
                <?php endif; ?>
                <div>
                    <p class="page-title"><?= esc($pageTitle ?? 'Dashboard') ?></p>
                    <?php if (! empty($breadcrumb)): ?>
                        <div class="page-sub">
                            <?php $crumbs = array_keys($breadcrumb); $last = end($crumbs); ?>
                            <?php foreach ($breadcrumb as $label => $url): ?>
                                <?= $url ? '<a href="' . esc($url) . '" class="text-decoration-none">' . esc($label) . '</a>' : '<span class="fw-semibold text-body">' . esc($label) . '</span>' ?>
                                <?= $label !== $last ? ' <i class="bi bi-chevron-right" style="font-size: 0.6rem;"></i> ' : '' ?>
                            <?php endforeach; ?>
                        </div>
                    <?php elseif (! empty($pageSubtitle)): ?>
                        <div class="page-sub"><?= esc($pageSubtitle) ?></div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="topbar-search d-none d-md-block ms-auto">
                <div class="input-group">
                    <span class="input-group-text bg-transparent border-0" style="background:#f6f7fb;"><i class="bi bi-search text-muted"></i></span>
                    <input type="search" class="form-control border-0" placeholder="Search reservations, guests, rooms...">
                </div>
            </div>

            <div class="d-flex align-items-center gap-2 ms-auto ms-md-0">
                <?php $notifications = (new \App\Models\NotificationModel())->unread(); ?>
                <div class="dropdown">
                    <button class="icon-btn" type="button" data-bs-toggle="dropdown">
                        <i class="bi bi-bell"></i>
                        <?php if (! empty($notifications)): ?>
                            <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" style="font-size: 0.6rem;">
                                <?= count($notifications) ?>
                            </span>
                        <?php endif; ?>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end" style="min-width: 320px;">
                        <?php if (empty($notifications)): ?>
                            <li><span class="dropdown-item-text text-muted small">No new notifications.</span></li>
                        <?php else: ?>
                            <?php foreach ($notifications as $n): ?>
                                <li><a class="dropdown-item small" href="<?= $n->link ? site_url($n->link) : '#' ?>"><?= esc($n->message) ?></a></li>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        <li><hr class="dropdown-divider"></li>
                        <li class="d-flex justify-content-between align-items-center px-2">
                            <a href="<?= site_url('notifications') ?>" class="btn btn-sm btn-link p-0">View all</a>
                            <?php if (! empty($notifications)): ?>
                                <form action="<?= site_url('notifications/mark-read') ?>" method="post" class="m-0">
                                    <?= csrf_field() ?>
                                    <button type="submit" class="btn btn-sm btn-link p-0">Mark all read</button>
                                </form>
                            <?php endif; ?>
                        </li>
                    </ul>
                </div>

                <div class="dropdown">
                    <button class="btn user-chip" type="button" data-bs-toggle="dropdown">
                        <?php if ($currentUserPhoto): ?>
                            <img src="<?= site_url('uploads/' . $currentUserPhoto) ?>" alt="" class="user-avatar" style="object-fit: cover;">
                        <?php else: ?>
                            <div class="user-avatar"><?= esc($userInitials) ?></div>
                        <?php endif; ?>
                        <div class="d-none d-sm-block text-start">
                            <div class="name"><?= esc(session('userName')) ?></div>
                            <div class="role"><?= esc((new \Config\Lookups())->staffRoles[$role]['label'] ?? ucfirst((string) $role)) ?></div>
                        </div>
                        <i class="bi bi-chevron-down text-muted small ms-1"></i>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><span class="dropdown-item-text small text-muted"><?= esc(session('userEmail')) ?></span></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="<?= site_url('profile') ?>"><i class="bi bi-person me-2"></i>My Profile</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="<?= site_url('logout') ?>"><i class="bi bi-box-arrow-right me-2"></i>Log out</a></li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="container-fluid py-4 px-4">
            <?php if (session()->getFlashdata('success')): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?= esc(session()->getFlashdata('success')) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            <?php if (session()->getFlashdata('error')): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?= esc(session()->getFlashdata('error')) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            <?php if (isset($validation) && $validation instanceof \CodeIgniter\Validation\ValidationInterface && $validation->getErrors()): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <ul class="mb-0">
                        <?php foreach ($validation->getErrors() as $error): ?>
                            <li><?= esc($error) ?></li>
                        <?php endforeach; ?>
                    </ul>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?= $this->renderSection('content') ?>
        </div>
    </div>
</div>
<?php else: ?>
<div class="container-fluid py-4 px-4">
    <?= $this->renderSection('content') ?>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="<?= base_url('js/room-picker.js') ?>"></script>
<script>
// Shared by every same-page AJAX POST this app makes (the AI features'
// "Summarize this"/"Suggest with AI" buttons first). Security.php has
// regenerate=true — a fresh CSRF token after each request that consumes
// one — so a JSON endpoint that echoes csrf_hash() back in its response
// lets a page make more than one AJAX POST without a full reload.
window.maxyieldsCsrf = { name: '<?= csrf_token() ?>', hash: '<?= csrf_hash() ?>' };

window.maxyieldsPost = function (url, body) {
    const form = new FormData();
    for (const key in (body || {})) { form.append(key, body[key]); }
    form.append(window.maxyieldsCsrf.name, window.maxyieldsCsrf.hash);

    return fetch(url, { method: 'POST', body: form })
        .then((r) => r.json())
        .then((data) => {
            if (data.csrf_hash) {
                window.maxyieldsCsrf.hash = data.csrf_hash;

                // Security.php's regenerate=true rotates the token on
                // EVERY successful CSRF-protected POST, this AJAX one
                // included — so a regular <form> elsewhere on the page
                // (e.g. Settings' own tabs) is left holding a now-stale
                // hidden csrf_field() value the moment this fires.
                // Without this, submitting that form throws a 403
                // SecurityException even though nothing the user did was
                // wrong — caught for real on the Settings page once it
                // grew "Test Connection" buttons alongside its save
                // forms.
                document.querySelectorAll('input[name="' + window.maxyieldsCsrf.name + '"]').forEach(function (input) {
                    input.value = window.maxyieldsCsrf.hash;
                });
            }
            return data;
        });
};
</script>
<?= $this->renderSection('scripts') ?>
</body>
</html>
