<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <title><?= e($title ?? 'Menu') ?> — <?= e($shopSettings['restaurant_name'] ?? APP_NAME) ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <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="<?= asset('css/shop.css') ?>" rel="stylesheet">
    <link href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" rel="stylesheet">
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
</head>
<body>

<!-- ── Header ──────────────────────────────────────────────────────── -->
<header class="shop-header">
    <div class="shop-header-bar">

        <?php
        $_isLoggedIn = \Core\Session::get('customer_id');
        if ($_isLoggedIn):
            $_cid = \Core\Session::get('customer_id');
            $_del = (int)\Core\Database::getInstance()->fetchValue(
                "SELECT COUNT(*) FROM orders WHERE customer_id=? AND status='delivered'", [$_cid]);
            $_t   = customer_tier($_del);
        endif;
        ?>

        <!-- Left: Logo + Name -->
        <a href="<?= url('shop/menu') ?>" class="sh-brand">
            <?php if (!empty($shopSettings['restaurant_logo'])): ?>
            <img src="<?= e(upload_url($shopSettings['restaurant_logo'])) ?>"
                 alt="<?= e($shopSettings['restaurant_name'] ?? '') ?>"
                 class="sh-brand-logo">
            <?php endif; ?>
            <div class="sh-brand-text">
                <div class="sh-brand-name"><?= e($shopSettings['restaurant_name'] ?? APP_NAME) ?></div>
                <div class="sh-brand-sub">Order Online</div>
            </div>
        </a>

        <!-- Right: Profile + Cart/Orders -->
        <div style="display:flex;align-items:center;gap:6px;flex-shrink:0;">

            <!-- Cart icon -->
            <div class="sh-icon" style="position:relative;">
                <a href="<?= url('shop/cart') ?>" aria-label="Cart">
                    <i class="bi bi-bag"></i>
                </a>
                <span id="hdrCartDot" style="display:none;position:absolute;top:1px;right:1px;
                      min-width:16px;height:16px;background:var(--accent);color:#fff;
                      font-size:.58rem;font-weight:800;border-radius:20px;
                      align-items:center;justify-content:center;
                      padding:0 3px;box-shadow:0 1px 4px rgba(249,115,22,.5);
                      pointer-events:none;"></span>
            </div>

            <!-- Profile icon -->
            <?php if ($_isLoggedIn):
                $_custName   = \Core\Session::get('customer_name') ?? 'U';
                $_initial    = strtoupper(mb_substr($_custName, 0, 1));
                $__colors    = ['#f97316','#3b82f6','#16a34a','#8b5cf6','#e11d48','#0891b2'];
                $_avatarBg   = $__colors[abs(crc32($_custName)) % count($__colors)];
            ?>
            <div style="position:relative;flex-shrink:0;">
                <a href="<?= url('shop/account') ?>" aria-label="My Account"
                   style="display:flex;align-items:center;justify-content:center;
                          width:38px;height:38px;border-radius:50%;
                          background:<?= $_avatarBg ?>;color:#fff;
                          font-size:.88rem;font-weight:800;text-decoration:none;
                          box-shadow:0 2px 6px rgba(0,0,0,.15);">
                    <?= $_initial ?>
                </a>
                <span style="position:absolute;bottom:-1px;right:-1px;font-size:.6rem;line-height:1;
                             background:#fff;border-radius:50%;width:15px;height:15px;
                             display:flex;align-items:center;justify-content:center;
                             box-shadow:0 1px 3px rgba(0,0,0,.18);pointer-events:none;">
                    <?= $_t['icon'] ?>
                </span>
            </div>
            <?php else: ?>
            <div class="sh-icon">
                <a href="<?= url('shop/login') ?>" aria-label="Sign In">
                    <i class="bi bi-person"></i>
                </a>
            </div>
            <?php endif; ?>

        </div>

    </div>

    <!-- Search bar -->
    <div class="shop-search-bar">
        <div class="shop-search-inner">
            <i class="bi bi-search" id="searchIcon"></i>
            <input type="search" id="liveSearch"
                   placeholder="Search dishes, drinks…"
                   value="<?= e($_GET['q'] ?? '') ?>"
                   autocomplete="off" autocorrect="off" spellcheck="false"
                   inputmode="search" enterkeyhint="search">
            <button class="search-clear" id="searchClear" onclick="clearSearch()" style="display:none">
                <i class="bi bi-x-lg"></i>
            </button>
        </div>
    </div>
</header>

<!-- Flash alerts -->
<?php $flash = flash_alert(); if ($flash): ?>
<div class="shop-flash"><?= $flash ?></div>
<?php endif; ?>

<!-- Page content -->
<div class="shop-wrap">
    <?= $content ?>
</div>

<!-- ── Bottom Cart Bar ──────────────────────────────────────────────── -->
<div class="cart-bar" id="cartBar" onclick="location.href='<?= url('shop/cart') ?>'">
    <div class="cart-bar-badge" id="cartBarBadge">0 items</div>
    <div class="cart-bar-mid">View Cart</div>
    <div class="cart-bar-cta">
        <span id="cartBarTotal">Rs. 0.00</span>
        <i class="bi bi-chevron-right"></i>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const SHOP_URL  = '<?= url('shop') ?>';
const UPLOAD_URL = '<?= UPLOAD_URL ?>';
const _CSRF     = '<?= csrf_token() ?>';

function updateCartUI(count, total) {
    const bar = document.getElementById('cartBar');
    if (count > 0) {
        document.getElementById('cartBarBadge').textContent = count + (count === 1 ? ' item' : ' items');
        document.getElementById('cartBarTotal').textContent  = 'Rs. ' + parseFloat(total).toFixed(2);
        bar.classList.add('visible');
    } else {
        bar.classList.remove('visible');
    }
    // Header cart dot
    const dot = document.getElementById('hdrCartDot');
    if (dot) {
        if (count > 0) {
            dot.textContent    = count > 9 ? '9+' : count;
            dot.style.display  = 'flex';
        } else {
            dot.style.display  = 'none';
        }
    }
}
updateCartUI(<?= (int)($cartCount ?? 0) ?>, <?= (float)($cartTotal ?? 0) ?>);

async function addToCart(itemId, choices = {}, qty = 1) {
    const fd = new FormData();
    fd.append('item_id', itemId);
    fd.append('qty', qty);
    fd.append('_csrf', _CSRF);
    Object.entries(choices).forEach(([k, v]) => fd.append('choices[' + k + ']', v));
    const res  = await fetch('<?= url('shop/cart/add') ?>', { method: 'POST', body: fd });
    const data = await res.json();
    if (data.success) {
        updateCartUI(data.cart_count, data.cart_total);
        showToast('Added to cart!', 'success');
    } else {
        showToast(data.message ?? 'Something went wrong', 'danger');
    }
    return data;
}

function showToast(msg, type = 'success') {
    document.querySelectorAll('.shop-toast').forEach(e => e.remove());
    const el = document.createElement('div');
    el.className = `shop-toast ${type}`;
    el.innerHTML = `<i class="bi bi-${type === 'success' ? 'check-circle-fill' : 'x-circle-fill'}"></i> ${msg}`;
    document.body.appendChild(el);
    requestAnimationFrame(() => el.classList.add('show'));
    setTimeout(() => { el.classList.remove('show'); setTimeout(() => el.remove(), 300); }, 2000);
}

// ── Live search ──────────────────────────────────────────────────────────────
(function () {
    const input = document.getElementById('liveSearch');
    const clearBtn = document.getElementById('searchClear');
    if (!input) return;

    let debounce;

    // Cards to search: grid cards + list cards across all sections
    function allCards() {
        return [...document.querySelectorAll('.grid-card, .item-card')];
    }

    function filterItems(q) {
        const term = q.trim().toLowerCase();
        clearBtn.style.display = term ? '' : 'none';

        if (!term) {
            // Show everything
            allCards().forEach(c => c.closest('.menu-section, .item-grid, .item-group') && showCard(c, true));
            allCards().forEach(c => showCard(c, true));
            document.querySelectorAll('.search-no-results').forEach(e => e.remove());
            document.querySelectorAll('.menu-section').forEach(s => s.style.display = '');
            document.querySelectorAll('.see-more-link')?.forEach(e => e.parentElement.style.display = '');
            document.getElementById('viewGrid') && (document.getElementById('viewGrid').style.display = '');
            document.getElementById('viewList') && updateCountBadge();
            return;
        }

        let total = 0;

        // Handle grid view
        const gridCards = [...document.querySelectorAll('.item-grid .grid-card')];
        gridCards.forEach(card => {
            const text = card.textContent.toLowerCase();
            const match = text.includes(term);
            showCard(card, match);
            if (match) total++;
        });

        // Handle list view
        const listCards = [...document.querySelectorAll('.item-group .item-card')];
        listCards.forEach(card => {
            const text = card.textContent.toLowerCase();
            showCard(card, text.includes(term));
        });

        // Hide/show category section headers when all items in them are hidden
        document.querySelectorAll('.menu-section').forEach(sec => {
            const visible = [...sec.querySelectorAll('.grid-card, .item-card')].some(c => c.style.display !== 'none');
            sec.style.display = visible ? '' : 'none';
        });

        // Hide "see more" links during search
        document.querySelectorAll('.see-more-link')?.forEach(e => e.parentElement.style.display = 'none');

        // No results message
        document.querySelectorAll('.search-no-results').forEach(e => e.remove());
        if (total === 0) {
            const msg = document.createElement('div');
            msg.className = 'search-no-results empty-state';
            msg.innerHTML = `<div class="empty-state-icon">🔍</div><h4>No results for "${q}"</h4><p>Try a different keyword.</p>`;
            (document.getElementById('viewGrid') || document.getElementById('menuSections'))?.after(msg);
        }

        updateCountBadge(total);
    }

    function showCard(card, show) {
        card.style.display = show ? '' : 'none';
    }

    function updateCountBadge(n) {
        const badge = document.querySelector('.view-count');
        if (!badge) return;
        if (n === undefined) {
            n = [...document.querySelectorAll('.grid-card, .item-card')].filter(c => c.style.display !== 'none').length;
        }
        badge.textContent = n + (n === 1 ? ' item' : ' items');
    }

    function clearSearch() {
        input.value = '';
        input.focus();
        filterItems('');
    }
    window.clearSearch = clearSearch;

    function runFilter(val) {
        clearBtn.style.display = val.trim() ? '' : 'none';
        // Delegate to page-level hook if available (menu page), else generic filter
        if (typeof window._menuFilterHook === 'function') {
            window._menuFilterHook(val);
        } else {
            filterItems(val);
        }
    }

    input.addEventListener('input', () => {
        clearTimeout(debounce);
        debounce = setTimeout(() => runFilter(input.value), 180);
    });

    // Prevent form submit / page reload on Enter
    input.addEventListener('keydown', e => { if (e.key === 'Enter') e.preventDefault(); });

    // Run on load if there's a pre-filled query
    if (input.value) runFilter(input.value);
})();
</script>

<?php if (!empty($extraJs)): ?>
<?= $extraJs ?>
<?php endif; ?>

<script>
// ── Fix 1: bfcache — force reload if page is served from back/forward cache
// so cart count and login state always reflect actual session
window.addEventListener('pageshow', function (e) {
    if (e.persisted) { window.location.reload(); }
});

// ── Fix 2: clear guest-prompt dismiss flag when user is not logged in
// so the prompt always re-appears after logout
<?php if (!\Core\Session::get('customer_id')): ?>
sessionStorage.removeItem('guestPromptDismissed');
<?php endif; ?>
</script>
</body>
</html>
