<?php
session_start();
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'database.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';

$db = Database::getInstance();

$slug = trim($_GET['r'] ?? '');
$tableParam = trim($_GET['table'] ?? '');

if (empty($slug)) {
    http_response_code(404);
    echo '<!DOCTYPE html><html><head><title>Not Found</title></head><body style="display:flex;align-items:center;justify-content:center;min-height:100vh;font-family:sans-serif;text-align:center;"><div><h1>Restaurant Not Found</h1><p>Please scan a valid QR code.</p></div></body></html>';
    exit;
}

$restaurant = $db->query(
    "SELECT * FROM restaurants WHERE slug = ? AND status = 'active' LIMIT 1",
    [$slug]
)->fetch();

if (!$restaurant) {
    http_response_code(404);
    echo '<!DOCTYPE html><html><head><title>Not Found</title></head><body style="display:flex;align-items:center;justify-content:center;min-height:100vh;font-family:sans-serif;text-align:center;"><div><h1>Restaurant Not Found</h1><p>This restaurant may be inactive or the link is invalid.</p></div></body></html>';
    exit;
}

$restaurantId = (int) $restaurant['id'];

$settings = $db->query("SELECT * FROM restaurant_settings WHERE restaurant_id = ? LIMIT 1", [$restaurantId])->fetch();
if (!$settings) {
    $settings = [];
}

$operatingMode = (int) ($settings['operating_mode'] ?? $restaurant['operating_mode'] ?? 1);
$isOrderingMode = ($operatingMode === 2);

$primaryColor = $settings['primary_color'] ?? '#e74c3c';
$secondaryColor = $settings['secondary_color'] ?? '#2c3e50';
$currency = $restaurant['currency'] ?? 'USD';
$currencySymbol = '$';
$symbols = ['LKR' => 'Rs.', 'USD' => '$', 'EUR' => "\xE2\x82\xAC", 'GBP' => "\xC2\xA3", 'INR' => "\xE2\x82\xB9"];
$currencySymbol = $symbols[$currency] ?? $currency . ' ';

$tableId = null;
$tableNumber = null;
if (!empty($tableParam)) {
    $table = $db->query(
        "SELECT * FROM tables WHERE restaurant_id = ? AND (table_number = ? OR table_name = ?) AND is_active = 1 LIMIT 1",
        [$restaurantId, $tableParam, $tableParam]
    )->fetch();
    if ($table) {
        $tableId = (int) $table['id'];
        $tableNumber = $table['table_number'];
    }
}

$sessionId = 'sess_' . bin2hex(random_bytes(16));
if (isset($_SESSION['menu_session_id'])) {
    $sessionId = $_SESSION['menu_session_id'];
} else {
    $_SESSION['menu_session_id'] = $sessionId;
}
$sessionId = $_SESSION['menu_session_id'];
$deviceType = getDeviceType();
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

if ($tableId) {
    $qrCodeId = null;
    $existingQr = $db->query(
        "SELECT id FROM qr_scan_logs WHERE restaurant_id = ? AND table_id = ? AND session_id = ? ORDER BY scanned_at DESC LIMIT 1",
        [$restaurantId, $tableId, $sessionId]
    )->fetch();
    if (!$existingQr) {
        $db->insert('qr_scan_logs', [
            'restaurant_id' => $restaurantId,
            'table_id'      => $tableId,
            'qr_code_id'    => $qrCodeId,
            'session_id'    => $sessionId,
            'device_type'   => $deviceType,
            'user_agent'    => substr($userAgent, 0, 500),
            'scanned_at'    => date('Y-m-d H:i:s'),
        ]);
    }
}

$db->insert('menu_view_logs', [
    'restaurant_id' => $restaurantId,
    'category_id'   => null,
    'menu_item_id'  => null,
    'session_id'    => $sessionId,
    'event_type'    => 'menu_view',
    'device_type'   => $deviceType,
    'user_agent'    => substr($userAgent, 0, 500),
    'created_at'    => date('Y-m-d H:i:s'),
]);

$categories = $db->query(
    "SELECT * FROM categories WHERE restaurant_id = ? AND status = 1 ORDER BY sort_order ASC, name ASC",
    [$restaurantId]
)->fetchAll();

$allItems = $db->query(
    "SELECT * FROM menu_items WHERE restaurant_id = ? AND is_available = 1 ORDER BY is_featured DESC, sort_order ASC, name ASC",
    [$restaurantId]
)->fetchAll();

$itemIds = array_column($allItems, 'id');
$variationsMap = [];
$addonsMap = [];
$addonGroupsMap = [];
$itemAddonGroupsMap = [];

if (!empty($itemIds)) {
    $placeholders = implode(',', array_fill(0, count($itemIds), '?'));
    $variations = $db->query(
        "SELECT * FROM item_variations WHERE restaurant_id = ? AND menu_item_id IN ({$placeholders}) AND status = 1 ORDER BY sort_order ASC",
        array_merge([$restaurantId], $itemIds)
    )->fetchAll();
    foreach ($variations as $v) {
        $variationsMap[$v['menu_item_id']][] = $v;
    }

    $itemAddonGroups = $db->query(
        "SELECT * FROM item_addon_groups WHERE menu_item_id IN ({$placeholders})",
        $itemIds
    )->fetchAll();
    foreach ($itemAddonGroups as $iag) {
        $itemAddonGroupsMap[$iag['menu_item_id']][] = $iag['addon_group_id'];
    }

    $allAddonGroupIds = array_unique(array_column($itemAddonGroups, 'addon_group_id'));
    if (!empty($allAddonGroupIds)) {
        $agPlaceholders = implode(',', array_fill(0, count($allAddonGroupIds), '?'));
        $addonGroups = $db->query(
            "SELECT * FROM addon_groups WHERE restaurant_id = ? AND id IN ({$agPlaceholders}) AND status = 1 ORDER BY sort_order ASC",
            array_merge([$restaurantId], $allAddonGroupIds)
        )->fetchAll();
        foreach ($addonGroups as $ag) {
            $addonGroupsMap[$ag['id']] = $ag;
        }

        $addons = $db->query(
            "SELECT * FROM addons WHERE restaurant_id = ? AND addon_group_id IN ({$agPlaceholders}) AND status = 1 ORDER BY sort_order ASC",
            array_merge([$restaurantId], $allAddonGroupIds)
        )->fetchAll();
        foreach ($addons as $a) {
            $addonsMap[$a['addon_group_id']][] = $a;
        }
    }
}

$activeOffers = $db->query(
    "SELECT * FROM offers WHERE restaurant_id = ? AND is_active = 1 AND (start_date IS NULL OR start_date <= CURDATE()) AND (end_date IS NULL OR end_date >= CURDATE()) ORDER BY created_at DESC",
    [$restaurantId]
)->fetchAll();

$activeAdverts = $db->query(
    "SELECT * FROM advertisements WHERE restaurant_id = ? AND is_active = 1 AND (start_date IS NULL OR start_date <= CURDATE()) AND (end_date IS NULL OR end_date >= CURDATE()) ORDER BY position ASC, created_at DESC",
    [$restaurantId]
)->fetchAll();

$topBanners = [];
$bottomBanners = [];
$popupAd = null;
foreach ($activeAdverts as $ad) {
    if ($ad['position'] === 'top_banner') {
        $topBanners[] = $ad;
    } elseif ($ad['position'] === 'bottom_banner') {
        $bottomBanners[] = $ad;
    } elseif ($ad['position'] === 'popup') {
        if (!$popupAd) $popupAd = $ad;
    }
}

$operatingHours = getOperatingHours($settings);

$csrf = new CSRF();
$csrfToken = $csrf->generate();

$menuItemsJson = [];
foreach ($allItems as &$item) {
    $itemData = [
        'id'          => $item['id'],
        'name'        => $item['name'],
        'description' => $item['short_description'] ?? '',
        'full_desc'   => $item['full_description'] ?? '',
        'price'       => (float) ($item['offer_price'] ?: $item['regular_price']),
        'regular_price' => (float) $item['regular_price'],
        'offer_price' => (!empty($item['offer_price']) && (float) $item['offer_price'] > 0) ? (float) $item['offer_price'] : null,
        'image'       => !empty($item['main_image']) ? $item['main_image'] : '',
        'is_new'      => (bool) $item['is_new'],
        'is_bestseller' => (bool) $item['is_bestseller'],
        'is_spicy'    => (bool) $item['is_spicy'],
        'is_vegetarian' => (bool) $item['is_vegetarian'],
        'is_vegan'    => (bool) $item['is_vegan'],
        'is_halal'    => (bool) $item['is_halal'],
        'is_gluten_free' => (bool) $item['is_gluten_free'],
        'is_chefs_choice' => (bool) $item['is_chefs_choice'],
        'category_id' => $item['category_id'],
        'variations'  => $variationsMap[$item['id']] ?? [],
        'addons'      => [],
    ];
    $agIds = $itemAddonGroupsMap[$item['id']] ?? [];
    foreach ($agIds as $agId) {
        if (isset($addonGroupsMap[$agId])) {
            $itemData['addons'][] = [
                'group' => $addonGroupsMap[$agId],
                'items' => $addonsMap[$agId] ?? [],
            ];
        }
    }
    $menuItemsJson[] = $itemData;
    $item['_viewData'] = $itemData;
}
unset($item);

$categoryMap = [];
foreach ($categories as $cat) {
    $categoryMap[$cat['id']] = $cat;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0">
    <meta name="csrf-token" content="<?php echo sanitize($csrfToken); ?>">
    <meta name="currency" content="<?php echo sanitize($currency); ?>">
    <meta name="currency-symbol" content="<?php echo sanitize($currencySymbol); ?>">
    <meta name="theme-color" content="<?php echo sanitize($primaryColor); ?>">
    <meta name="robots" content="noindex, nofollow">
    <base href="<?php echo getBaseUrl(); ?>/">
    <title><?php echo sanitize($restaurant['name']); ?> - Menu</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://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="assets/css/menu.css" rel="stylesheet">
    <style>
        :root {
            --rest-primary: <?php echo sanitize($primaryColor); ?>;
            --rest-primary-rgb: <?php echo implode(',', array_map('intval', sscanf($primaryColor, '#%02x%02x%02x'))); ?>;
            --rest-secondary: <?php echo sanitize($secondaryColor); ?>;
        }
    </style>
</head>
<body>

<?php if (!empty($topBanners)): ?>
<div class="ad-slider" style="margin: 0; border-radius: 0;">
    <div class="ad-slider-track">
        <?php foreach ($topBanners as $idx => $banner): ?>
        <div class="ad-slide">
            <?php if (!empty($banner['image'])): ?>
            <img src="<?php echo sanitize($banner['image']); ?>" alt="<?php echo sanitize($banner['title']); ?>" style="height:140px;">
            <?php endif; ?>
            <div class="ad-content">
                <div>
                    <h4><?php echo sanitize($banner['title']); ?></h4>
                    <?php if (!empty($banner['description'])): ?>
                    <p><?php echo sanitize($banner['description']); ?></p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php if (count($topBanners) > 1): ?>
    <div class="ad-dots">
        <?php foreach ($topBanners as $idx => $banner): ?>
        <button class="ad-dot <?php echo $idx === 0 ? 'active' : ''; ?>" data-slide="<?php echo $idx; ?>"></button>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<header class="menu-header" id="menuHeader">
    <div class="restaurant-info">
        <?php if (!empty($restaurant['logo'])): ?>
        <img class="restaurant-logo" src="<?php echo sanitize($restaurant['logo']); ?>" alt="<?php echo sanitize($restaurant['name']); ?>">
        <?php else: ?>
        <div class="restaurant-logo" style="background:var(--rest-primary);display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700;font-size:14px;">
            <?php echo strtoupper(substr($restaurant['name'], 0, 2)); ?>
        </div>
        <?php endif; ?>
        <div>
            <div class="restaurant-name"><?php echo sanitize($restaurant['name']); ?></div>
            <?php if ($tableNumber): ?>
            <div class="restaurant-tagline">Table <?php echo sanitize($tableNumber); ?></div>
            <?php endif; ?>
        </div>
    </div>
    <div class="header-btn-row" style="display:flex;align-items:center;gap:4px;">
        <?php if ($operatingHours['is_open']): ?>
        <span style="background:#eafaf1;color:#27ae60;padding:3px 10px;border-radius:12px;font-size:0.7rem;font-weight:600;">Open</span>
        <?php else: ?>
        <span style="background:#fef2e2;color:#e67e22;padding:3px 10px;border-radius:12px;font-size:0.7rem;font-weight:600;">Closed</span>
        <?php endif; ?>
        <?php if (!empty($restaurant['phone'])): ?>
        <a href="tel:<?php echo sanitize($restaurant['phone']); ?>" class="header-btn" title="Call"><i class="fas fa-phone"></i></a>
        <?php endif; ?>
        <?php if (!empty($settings['wifi_name'])): ?>
        <button class="header-btn" onclick="document.getElementById('wifiModal').classList.add('show')" title="Wi-Fi"><i class="fas fa-wifi"></i></button>
        <?php endif; ?>
    </div>
</header>

<?php if (!empty($restaurant['cover_image'])): ?>
<section class="hero-section">
    <img class="hero-image" src="<?php echo sanitize($restaurant['cover_image']); ?>" alt="<?php echo sanitize($restaurant['name']); ?>">
    <div class="hero-overlay"></div>
    <div class="hero-content">
        <h1><?php echo sanitize($restaurant['name']); ?></h1>
        <?php if (!empty($restaurant['description'])): ?>
        <p><?php echo sanitize($restaurant['description']); ?></p>
        <?php endif; ?>
        <div class="hero-meta">
            <?php if (!empty($restaurant['address'])): ?>
            <span class="meta-item"><i class="fas fa-map-marker-alt"></i> <?php echo sanitize($restaurant['city'] ?? $restaurant['address']); ?></span>
            <?php endif; ?>
            <?php if (!empty($settings['delivery_enabled'])): ?>
            <span class="meta-item"><i class="fas fa-motorcycle"></i> Delivery</span>
            <?php endif; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<div style="background:var(--rest-surface);padding:10px 16px;display:flex;gap:8px;border-bottom:1px solid var(--rest-border);">
    <?php if (!empty($restaurant['phone'])): ?>
    <a href="tel:<?php echo sanitize($restaurant['phone']); ?>" style="flex:1;display:flex;align-items:center;justify-content:center;gap:6px;padding:8px;background:var(--rest-bg);border-radius:8px;font-size:0.78rem;font-weight:500;color:var(--rest-text);">
        <i class="fas fa-phone" style="color:var(--rest-primary);"></i> Call
    </a>
    <?php endif; ?>
    <?php if (!empty($restaurant['whatsapp'])): ?>
    <a href="https://wa.me/<?php echo sanitize(preg_replace('/[^0-9]/', '', $restaurant['whatsapp'])); ?>" target="_blank" style="flex:1;display:flex;align-items:center;justify-content:center;gap:6px;padding:8px;background:var(--rest-bg);border-radius:8px;font-size:0.78rem;font-weight:500;color:#25d366;">
        <i class="fab fa-whatsapp"></i> WhatsApp
    </a>
    <?php endif; ?>
    <?php if (!empty($restaurant['address'])): ?>
    <a href="https://www.google.com/maps/search/?api=1&query=<?php echo urlencode($restaurant['address']); ?>" target="_blank" style="flex:1;display:flex;align-items:center;justify-content:center;gap:6px;padding:8px;background:var(--rest-bg);border-radius:8px;font-size:0.78rem;font-weight:500;color:var(--rest-text);">
        <i class="fas fa-directions" style="color:var(--rest-primary);"></i> Direction
    </a>
    <?php endif; ?>
</div>

<?php if (!empty($settings['wifi_name'])): ?>
<div id="wifiModal" class="offer-popup-overlay" onclick="if(event.target===this)this.classList.remove('show')">
    <div class="offer-popup" style="max-width:320px;">
        <div class="offer-popup-content" style="padding:30px;">
            <i class="fas fa-wifi" style="font-size:2.5rem;color:var(--rest-primary);margin-bottom:12px;"></i>
            <h3 style="margin-bottom:12px;">Wi-Fi Access</h3>
            <p><strong>Network:</strong> <?php echo sanitize($settings['wifi_name']); ?></p>
            <?php if (!empty($settings['wifi_password'])): ?>
            <p><strong>Password:</strong> <span style="font-family:monospace;letter-spacing:1px;"><?php echo sanitize($settings['wifi_password']); ?></span></p>
            <?php endif; ?>
            <button onclick="this.closest('.offer-popup-overlay').classList.remove('show')" style="margin-top:16px;padding:8px 24px;background:var(--rest-primary);color:#fff;border:none;border-radius:8px;font-weight:600;cursor:pointer;">Close</button>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if (!empty($popupAd)): ?>
<div class="offer-popup-overlay" id="offer-popup">
    <div class="offer-popup">
        <button class="close-popup">&times;</button>
        <?php if (!empty($popupAd['image'])): ?>
        <img class="offer-popup-image" src="<?php echo sanitize($popupAd['image']); ?>" alt="<?php echo sanitize($popupAd['title']); ?>">
        <?php endif; ?>
        <div class="offer-popup-content">
            <h3><?php echo sanitize($popupAd['title']); ?></h3>
            <?php if (!empty($popupAd['description'])): ?>
            <p><?php echo sanitize($popupAd['description']); ?></p>
            <?php endif; ?>
            <?php if (!empty($popupAd['button_text']) && !empty($popupAd['button_link'])): ?>
            <a href="<?php echo sanitize($popupAd['button_link']); ?>" class="checkout-btn" style="text-decoration:none;"><?php echo sanitize($popupAd['button_text']); ?></a>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if (!empty($activeOffers)): ?>
<section style="padding:16px 0 0;">
    <div style="padding:0 16px;margin-bottom:10px;display:flex;align-items:center;justify-content:space-between;">
        <h2 style="font-size:1rem;font-weight:700;"><i class="fas fa-fire" style="color:var(--rest-primary);margin-right:6px;"></i> Special Offers</h2>
    </div>
    <div style="display:flex;gap:12px;overflow-x:auto;padding:0 16px 8px;-webkit-overflow-scrolling:touch;scrollbar-width:none;">
        <style>.offer-scroll::-webkit-scrollbar{display:none;}</style>
        <?php foreach ($activeOffers as $offer): ?>
        <div style="min-width:260px;background:linear-gradient(135deg,var(--rest-primary),#c0392b);border-radius:var(--rest-radius);padding:16px;color:#fff;flex-shrink:0;">
            <div style="font-size:0.7rem;opacity:0.8;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px;">Limited Time</div>
            <div style="font-size:1rem;font-weight:700;margin-bottom:6px;"><?php echo sanitize($offer['title']); ?></div>
            <?php if (!empty($offer['description'])): ?>
            <div style="font-size:0.78rem;opacity:0.9;margin-bottom:8px;"><?php echo sanitize($offer['description']); ?></div>
            <?php endif; ?>
            <?php if (!empty($offer['coupon_code'])): ?>
            <div style="display:inline-block;background:rgba(255,255,255,0.2);padding:3px 10px;border-radius:6px;font-family:monospace;font-size:0.75rem;letter-spacing:1px;"><?php echo sanitize($offer['coupon_code']); ?></div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
</section>
<?php endif; ?>

<nav class="category-nav" id="categoryNav">
    <button class="category-pill active" data-category="all">All</button>
    <?php foreach ($categories as $cat): ?>
    <button class="category-pill" data-category="<?php echo $cat['id']; ?>"><?php echo sanitize($cat['name']); ?></button>
    <?php endforeach; ?>
</nav>

<div class="search-section">
    <div class="search-bar">
        <i class="fas fa-search"></i>
        <input type="text" placeholder="Search menu..." id="searchInput">
        <button class="clear-search" id="clearSearch"><i class="fas fa-times"></i></button>
    </div>
    <div class="search-results-info" id="searchResultsInfo"></div>
</div>

<div class="menu-content" id="menuContent">
    <?php
    $categoryItems = [];
    foreach ($allItems as $item) {
        $categoryItems[$item['category_id']][] = $item;
    }

    $displayedCategories = [];
    foreach ($categories as $cat) {
        if (empty($categoryItems[$cat['id']])) continue;
        $displayedCategories[] = $cat;
    }
    ?>

    <?php foreach ($displayedCategories as $cat): ?>
    <section class="menu-category-section" id="category-<?php echo $cat['id']; ?>" data-category-id="<?php echo $cat['id']; ?>">
        <div class="category-header">
            <h2><?php echo sanitize($cat['name']); ?></h2>
            <span class="item-count"><?php echo count($categoryItems[$cat['id']]); ?> items</span>
        </div>
        <?php if (!empty($cat['description'])): ?>
        <p class="category-description"><?php echo sanitize($cat['description']); ?></p>
        <?php endif; ?>

        <div class="food-items-grid">
            <?php foreach ($categoryItems[$cat['id']] as $item):
                $itemData = $item['_viewData'];
                $hasVariations = !empty($variationsMap[$item['id']]);
                $hasAddons = !empty($itemAddonGroupsMap[$item['id']]);
                $db->query("UPDATE menu_items SET view_count = view_count + 1 WHERE id = ?", [$item['id']]);
            ?>
            <div class="food-item-card"
                 data-item-id="<?php echo $item['id']; ?>"
                 data-item-name="<?php echo sanitize($item['name']); ?>"
                 data-item-price="<?php echo $itemData['price']; ?>"
                 data-item-desc="<?php echo sanitize($item['short_description'] ?? ''); ?>"
                 data-item-image="<?php echo sanitize($itemData['image']); ?>"
                 data-variations="<?php echo sanitize(json_encode($itemData['variations'])); ?>"
                 data-addons="<?php echo sanitize(json_encode($itemData['addons'])); ?>"
                 onclick="MenuApp.openItemModal('<?php echo $item['id']; ?>')">

                <div class="item-image-wrapper">
                    <?php if (!empty($item['main_image'])): ?>
                    <img class="item-image" src="<?php echo sanitize($item['main_image']); ?>" alt="<?php echo sanitize($item['name']); ?>" loading="lazy">
                    <?php else: ?>
                    <div class="item-image-placeholder"><i class="fas fa-utensils"></i></div>
                    <?php endif; ?>
                    <div class="item-badges">
                        <?php if ($item['is_new']): ?><span class="badge-tag badge-new"><i class="fas fa-star"></i> New</span><?php endif; ?>
                        <?php if ($item['is_bestseller']): ?><span class="badge-tag badge-bestseller"><i class="fas fa-fire"></i> Best</span><?php endif; ?>
                        <?php if ($item['is_spicy']): ?><span class="badge-tag badge-spicy"><i class="fas fa-pepper-hot"></i></span><?php endif; ?>
                        <?php if ($item['is_vegetarian']): ?><span class="badge-tag badge-veg">Veg</span><?php endif; ?>
                    </div>
                </div>

                <div class="item-info">
                    <div class="item-name"><?php echo sanitize($item['name']); ?></div>
                    <?php if (!empty($item['short_description'])): ?>
                    <div class="item-description"><?php echo sanitize($item['short_description']); ?></div>
                    <?php endif; ?>
                    <div class="item-bottom">
                        <div class="item-price">
                            <?php if ($itemData['offer_price'] !== null): ?>
                            <span class="price-current"><?php echo sanitize($currencySymbol . number_format($itemData['price'], 2)); ?></span>
                            <span class="price-original"><?php echo sanitize($currencySymbol . number_format($itemData['regular_price'], 2)); ?></span>
                            <?php else: ?>
                            <span class="price-current"><?php echo sanitize($currencySymbol . number_format($itemData['price'], 2)); ?></span>
                            <?php endif; ?>
                        </div>
                        <?php if ($isOrderingMode): ?>
                        <button class="add-btn" onclick="event.stopPropagation(); MenuApp.addToCart('<?php echo $item['id']; ?>')" title="Add to Cart">
                            <i class="fas fa-plus"></i>
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endforeach; ?>

    <?php if (empty($displayedCategories)): ?>
    <div style="text-align:center;padding:60px 20px;color:var(--rest-text-muted);">
        <i class="fas fa-utensils" style="font-size:3rem;margin-bottom:12px;opacity:0.3;"></i>
        <p style="font-size:0.95rem;">No menu items available at the moment.</p>
    </div>
    <?php endif; ?>
</div>

<?php if ($isOrderingMode): ?>
<div class="floating-cart-btn" id="floatingCart">
    <i class="fas fa-shopping-cart"></i>
    <span class="cart-count" id="floatingCartCount">0</span>
    <span style="opacity:0.8;">|</span>
    <span class="cart-total" id="floatingCartTotal"><?php echo $currencySymbol; ?>0.00</span>
</div>

<div class="cart-overlay" id="cartOverlay"></div>
<div class="cart-sidebar" id="cartSidebar">
    <div class="cart-header">
        <h3><i class="fas fa-shopping-cart" style="margin-right:8px;"></i>Your Cart</h3>
        <button class="close-cart" id="closeCart"><i class="fas fa-times"></i></button>
    </div>
    <div class="cart-items" id="cart-items">
        <div class="cart-empty">
            <i class="fas fa-shopping-cart"></i>
            <p>Your cart is empty</p>
        </div>
    </div>
    <div class="cart-footer" id="cart-footer" style="display:none;">
        <div class="promo-input-group">
            <input type="text" placeholder="Promo code" id="promoInput">
            <button onclick="MenuApp.applyPromoCode()">Apply</button>
        </div>
        <div class="cart-summary-row" data-summary="subtotal">
            <span>Subtotal</span>
            <span class="summary-value"><?php echo $currencySymbol; ?>0.00</span>
        </div>
        <div class="cart-summary-row" data-summary="discount" style="display:none;">
            <span>Discount</span>
            <span class="summary-value discount">-<?php echo $currencySymbol; ?>0.00</span>
        </div>
        <div class="cart-summary-row" data-summary="tax">
            <span>Tax (<?php echo sanitize($settings['tax_percent'] ?? 0); ?>%)</span>
            <span class="summary-value"><?php echo $currencySymbol; ?>0.00</span>
        </div>
        <?php if (!empty($settings['service_charge_percent'])): ?>
        <div class="cart-summary-row" data-summary="service">
            <span>Service Charge (<?php echo sanitize($settings['service_charge_percent']); ?>%)</span>
            <span class="summary-value"><?php echo $currencySymbol; ?>0.00</span>
        </div>
        <?php endif; ?>
        <div class="cart-summary-row" data-summary="delivery" style="display:none;">
            <span>Delivery</span>
            <span class="summary-value"><?php echo $currencySymbol; ?>0.00</span>
        </div>
        <div class="cart-summary-row total">
            <span>Total</span>
            <span class="summary-value" id="cart-total"><?php echo $currencySymbol; ?>0.00</span>
        </div>
        <button class="checkout-btn" onclick="MenuApp.openCheckout()">
            <i class="fas fa-check"></i> Checkout
        </button>
    </div>
</div>

<div class="item-modal-overlay" id="item-modal">
    <div class="item-modal" style="position:relative;">
        <button class="modal-close"><i class="fas fa-times"></i></button>
        <div class="modal-image-placeholder"><i class="fas fa-utensils"></i></div>
        <div class="modal-body">
            <div class="modal-item-name"></div>
            <div class="modal-item-desc"></div>
            <div class="modal-item-price"></div>

            <div class="modal-section modal-variations-section">
                <div class="modal-section-title">Choose Variation <span class="required-tag">Required</span></div>
                <div class="variation-options"></div>
            </div>

            <div class="modal-section modal-addons-section">
                <div class="modal-section-title">Add-ons <span class="required-tag" style="display:none;">Optional</span></div>
                <div class="addon-options"></div>
            </div>

            <div class="modal-notes">
                <textarea placeholder="Special instructions (optional)..."></textarea>
            </div>

            <div class="modal-quantity-section" style="margin-top:12px;">
                <span style="font-weight:600;">Quantity</span>
                <div class="modal-qty-control">
                    <button class="modal-qty-btn" onclick="MenuApp.modalQtyChange(-1)"><i class="fas fa-minus"></i></button>
                    <span class="modal-qty-value">1</span>
                    <button class="modal-qty-btn" onclick="MenuApp.modalQtyChange(1)"><i class="fas fa-plus"></i></button>
                </div>
            </div>

            <button class="modal-add-to-cart" onclick="MenuApp.addItemFromModal()">
                <i class="fas fa-cart-plus"></i> Add to Cart
            </button>
        </div>
    </div>
</div>

<div class="checkout-overlay" id="checkout-overlay">
    <div class="checkout-panel">
        <div class="checkout-header">
            <h3><i class="fas fa-clipboard-check" style="margin-right:8px;"></i>Checkout</h3>
            <button class="close-cart" onclick="MenuApp.closeCheckout()"><i class="fas fa-times"></i></button>
        </div>
        <div class="checkout-body">
            <form id="checkout-form">
                <input type="hidden" name="csrf_token" value="<?php echo sanitize($csrfToken); ?>">
                <input type="hidden" name="restaurant_id" value="<?php echo $restaurantId; ?>">
                <input type="hidden" name="table_id" value="<?php echo $tableId ?? ''; ?>">

                <div class="checkout-section">
                    <div class="checkout-section-title">Order Type</div>
                    <div class="order-type-options">
                        <?php if (!empty($settings['dine_in_enabled'])): ?>
                        <button type="button" class="order-type-btn active" data-type="dine_in">
                            <i class="fas fa-chair"></i>
                            <span>Dine In</span>
                        </button>
                        <?php endif; ?>
                        <?php if (!empty($settings['takeaway_enabled'])): ?>
                        <button type="button" class="order-type-btn" data-type="takeaway">
                            <i class="fas fa-shopping-bag"></i>
                            <span>Takeaway</span>
                        </button>
                        <?php endif; ?>
                        <?php if (!empty($settings['delivery_enabled'])): ?>
                        <button type="button" class="order-type-btn" data-type="delivery">
                            <i class="fas fa-motorcycle"></i>
                            <span>Delivery</span>
                        </button>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="checkout-section">
                    <div class="checkout-section-title">Your Details</div>
                    <div class="form-group">
                        <label>Name *</label>
                        <input type="text" name="customer_name" placeholder="Your name" required>
                    </div>
                    <div class="form-group">
                        <label>Phone *</label>
                        <input type="tel" name="customer_phone" placeholder="Phone number" required>
                    </div>
                    <div id="deliveryFields" style="display:none;">
                        <div class="form-group">
                            <label>Delivery Address *</label>
                            <input type="text" name="customer_address" placeholder="Delivery address">
                        </div>
                        <div class="form-group">
                            <label>City</label>
                            <input type="text" name="customer_city" placeholder="City">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Order Notes</label>
                        <textarea name="order_notes" rows="2" placeholder="Any special requests..."></textarea>
                    </div>
                </div>
            </form>
        </div>
        <div class="checkout-footer">
            <button class="place-order-btn" onclick="MenuApp.placeOrder()">
                <i class="fas fa-check"></i> Place Order
            </button>
        </div>
    </div>
</div>

<div class="order-confirmation" id="order-confirmation">
    <div class="confirmation-content">
        <div class="confirmation-check"><i class="fas fa-check"></i></div>
        <h2>Order Placed Successfully!</h2>
        <p>Your order has been received and is being prepared.</p>
        <div class="confirmation-order-id"></div>
        <div class="order-status-bar">
            <div class="status-step active"><div class="step-circle"><i class="fas fa-clock"></i></div><span class="step-label">Pending</span></div>
            <div class="status-step"><div class="step-circle"><i class="fas fa-check"></i></div><span class="step-label">Confirmed</span></div>
            <div class="status-step"><div class="step-circle"><i class="fas fa-fire"></i></div><span class="step-label">Preparing</span></div>
            <div class="status-step"><div class="step-circle"><i class="fas fa-bell"></i></div><span class="step-label">Ready</span></div>
            <div class="status-step"><div class="step-circle"><i class="fas fa-utensils"></i></div><span class="step-label">Served</span></div>
        </div>
        <div class="confirmation-actions">
            <?php if (!empty($restaurant['whatsapp'])): ?>
            <a href="https://wa.me/<?php echo sanitize(preg_replace('/[^0-9]/', '', $restaurant['whatsapp'])); ?>" target="_blank" class="confirmation-btn btn-whatsapp">
                <i class="fab fa-whatsapp"></i> Contact on WhatsApp
            </a>
            <?php endif; ?>
            <button class="confirmation-btn btn-new-order" onclick="MenuApp.newOrder()">
                <i class="fas fa-plus"></i> New Order
            </button>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if (!empty($bottomBanners)): ?>
<?php $bottomAd = $bottomBanners[0]; ?>
<div class="offer-banner-bottom show" id="bottomBanner">
    <div class="offer-text">
        <?php if (!empty($bottomAd['title'])): ?>
        <strong><?php echo sanitize($bottomAd['title']); ?></strong>
        <?php if (!empty($bottomAd['description'])): ?>
        <span style="opacity:0.8;margin-left:6px;"><?php echo sanitize($bottomAd['description']); ?></span>
        <?php endif; ?>
        <?php endif; ?>
    </div>
    <?php if (!empty($bottomAd['button_text'])): ?>
    <button class="offer-cta" onclick="document.getElementById('bottomBanner').classList.remove('show')"><?php echo sanitize($bottomAd['button_text']); ?></button>
    <?php else: ?>
    <button class="offer-cta" onclick="document.getElementById('bottomBanner').classList.remove('show')"><i class="fas fa-times"></i></button>
    <?php endif; ?>
</div>
<?php endif; ?>

<footer style="background:var(--rest-secondary);color:rgba(255,255,255,0.7);padding:24px 16px;text-align:center;margin-top:40px;">
    <div style="margin-bottom:8px;">
        <?php if (!empty($restaurant['logo'])): ?>
        <img src="<?php echo sanitize($restaurant['logo']); ?>" alt="" style="width:40px;height:40px;border-radius:50%;margin:0 auto 8px;object-fit:cover;">
        <?php endif; ?>
        <div style="font-weight:700;font-size:0.95rem;color:#fff;"><?php echo sanitize($restaurant['name']); ?></div>
    </div>
    <?php if (!empty($settings['footer_message'])): ?>
    <p style="font-size:0.78rem;margin-bottom:8px;"><?php echo sanitize($settings['footer_message']); ?></p>
    <?php endif; ?>
    <div style="font-size:0.7rem;opacity:0.5;">Powered by Tap2Order</div>
</footer>

<script src="assets/js/menu.js"></script>
<script>
(function() {
    var cfg = {
        currency: <?php echo json_encode($currency); ?>,
        currencySymbol: <?php echo json_encode($currencySymbol); ?>,
        restaurantId: <?php echo $restaurantId; ?>,
        tableNumber: <?php echo json_encode($tableNumber); ?>,
        orderType: 'dine_in',
        promoCode: null,
        promoDiscount: 0,
        minOrderAmount: <?php echo (float) ($settings['min_order'] ?? 0); ?>,
        taxRate: <?php echo (float) ($settings['tax_percent'] ?? 0); ?>,
        serviceChargeRate: <?php echo (float) ($settings['service_charge_percent'] ?? 0); ?>,
        deliveryFee: <?php echo (float) ($settings['delivery_charge'] ?? 0); ?>,
        isOrderingMode: <?php echo $isOrderingMode ? 'true' : 'false'; ?>,
        baseUrl: <?php echo json_encode(getBaseUrl()); ?>,
        csrfToken: <?php echo json_encode($csrfToken); ?>,
        dineInEnabled: <?php echo !empty($settings['dine_in_enabled']) ? 'true' : 'false'; ?>,
        takeawayEnabled: <?php echo !empty($settings['takeaway_enabled']) ? 'true' : 'false'; ?>,
        deliveryEnabled: <?php echo !empty($settings['delivery_enabled']) ? 'true' : 'false'; ?>
    };
    var el = document.createElement('div');
    el.setAttribute('data-config', '');
    el.dataset.config = JSON.stringify(cfg);
    el.style.display = 'none';
    document.body.appendChild(el);

    var menuItemsEl = document.createElement('div');
    menuItemsEl.setAttribute('data-menu-items', '');
    menuItemsEl.dataset.menuItems = JSON.stringify(<?php echo json_encode(array_values($menuItemsJson)); ?>);
    menuItemsEl.style.display = 'none';
    document.body.appendChild(menuItemsEl);

    document.querySelectorAll('.ad-dot').forEach(function(dot) {
        dot.addEventListener('click', function() {
            var idx = parseInt(this.dataset.slide);
            var track = this.closest('.ad-slider').querySelector('.ad-slider-track');
            if (track) track.style.transform = 'translateX(-' + (idx * 100) + '%)';
            this.closest('.ad-dots').querySelectorAll('.ad-dot').forEach(function(d, i) {
                d.classList.toggle('active', i === idx);
            });
        });
    });

    if (document.querySelectorAll('.ad-slider-track').length > 0) {
        setInterval(function() {
            document.querySelectorAll('.ad-slider').forEach(function(slider) {
                var track = slider.querySelector('.ad-slider-track');
                var dots = slider.querySelectorAll('.ad-dot');
                var slides = slider.querySelectorAll('.ad-slide');
                if (!track || slides.length <= 1) return;
                var current = 0;
                dots.forEach(function(d, i) { if (d.classList.contains('active')) current = i; });
                var next = (current + 1) % slides.length;
                track.style.transform = 'translateX(-' + (next * 100) + '%)';
                dots.forEach(function(d, i) { d.classList.toggle('active', i === next); });
            });
        }, 5000);
    }

    var orderTypeBtns = document.querySelectorAll('.order-type-btn');
    orderTypeBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            orderTypeBtns.forEach(function(b) { b.classList.remove('active'); });
            this.classList.add('active');
            cfg.orderType = this.dataset.type;
            var deliveryFields = document.getElementById('deliveryFields');
            if (deliveryFields) {
                deliveryFields.style.display = cfg.orderType === 'delivery' ? 'block' : 'none';
            }
        });
    });

    var deliveryFields = document.getElementById('deliveryFields');
    if (deliveryFields) {
        deliveryFields.style.display = 'none';
    }

    var categoryNav = document.getElementById('categoryNav');
    if (categoryNav) {
        categoryNav.querySelectorAll('.category-pill').forEach(function(pill) {
            pill.addEventListener('click', function() {
                var catId = this.dataset.category;
                categoryNav.querySelectorAll('.category-pill').forEach(function(p) { p.classList.remove('active'); });
                this.classList.add('active');
                var sections = document.querySelectorAll('.menu-category-section');
                sections.forEach(function(sec) {
                    if (catId === 'all') {
                        sec.style.display = '';
                    } else {
                        sec.style.display = sec.dataset.categoryId === catId ? '' : 'none';
                    }
                });
            });
        });
    }

    var searchInput = document.getElementById('searchInput');
    var clearSearch = document.getElementById('clearSearch');
    var searchInfo = document.getElementById('searchResultsInfo');
    if (searchInput) {
        var debounce;
        searchInput.addEventListener('input', function() {
            clearTimeout(debounce);
            var self = this;
            debounce = setTimeout(function() {
                var q = self.value.toLowerCase().trim();
                if (clearSearch) clearSearch.style.display = q.length > 0 ? 'block' : 'none';
                var cards = document.querySelectorAll('.food-item-card');
                var count = 0;
                cards.forEach(function(card) {
                    var name = (card.dataset.itemName || '').toLowerCase();
                    var desc = (card.dataset.itemDesc || '').toLowerCase();
                    var match = !q || name.indexOf(q) !== -1 || desc.indexOf(q) !== -1;
                    card.style.display = match ? '' : 'none';
                    if (match) count++;
                });
                document.querySelectorAll('.menu-category-section').forEach(function(sec) {
                    var vis = sec.querySelectorAll('.food-item-card:not([style*="display: none"])');
                    sec.style.display = vis.length > 0 ? '' : 'none';
                });
                if (searchInfo) {
                    if (q) {
                        searchInfo.textContent = 'Found ' + count + ' item' + (count !== 1 ? 's' : '');
                        searchInfo.style.display = 'block';
                    } else {
                        searchInfo.style.display = 'none';
                    }
                }
            }, 250);
        });
        if (clearSearch) {
            clearSearch.addEventListener('click', function() {
                searchInput.value = '';
                searchInput.dispatchEvent(new Event('input'));
                searchInput.focus();
            });
        }
    }
})();
</script>
</body>
</html>
