<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/db_connect.php';

$isConnected = ($conn && !$conn->connect_error);
$connError = $connError ?? '';
$search = trim($_GET['q'] ?? '');
$selectedZone = trim($_GET['zone'] ?? '');
$lat = filter_input(INPUT_GET, 'lat', FILTER_VALIDATE_FLOAT);
$lng = filter_input(INPUT_GET, 'lng', FILTER_VALIDATE_FLOAT);
$hasLocation = ($lat !== false && $lat !== null && $lng !== false && $lng !== null);
$csrfToken = generateCsrfToken();
$currentUserId = (int) ($_SESSION['user_id'] ?? 0);
$currentUserName = (string) ($_SESSION['user_name'] ?? '');
$googleLoginConfigured = GOOGLE_CLIENT_ID !== '' && GOOGLE_CLIENT_SECRET !== '';

function e($value): string {
    return htmlspecialchars((string) $value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}

function money($amount): string {
    return 'Rs. ' . number_format((float) $amount, 0);
}

function tableExists($conn, string $table): bool {
    if (!$conn || $conn->connect_error) {
        return false;
    }
    $safeTable = $conn->real_escape_string($table);
    $result = $conn->query("SHOW TABLES LIKE '{$safeTable}'");
    return $result && $result->num_rows > 0;
}

function fetchRows($conn, string $query, string $types = '', array $params = []): array {
    if (!$conn || $conn->connect_error) {
        return [];
    }
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        return [];
    }
    if ($types !== '' && !empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    if (!$stmt->execute()) {
        return [];
    }
    $result = $stmt->get_result();
    $rows = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
    }
    return $rows;
}

function publicUrl(string $path): string {
    return rtrim(SITE_URL, '/') . '/' . ltrim($path, '/');
}

$zones = [];
$restaurants = [];
$featuredItems = [];
$menuCatalog = [];
$cuisines = [];
$offers = [];
$stats = ['restaurants' => 0, 'items' => 0, 'zones' => 0, 'avg_time' => 0];

if ($isConnected && tableExists($conn, 'restaurants')) {
    $zones = fetchRows(
        $conn,
        "SELECT z.id, z.name, COUNT(r.id) AS restaurant_count
         FROM zones z
         LEFT JOIN restaurants r ON r.zone_id = z.id AND r.status = 'ACTIVE'
         WHERE z.is_active = 1
         GROUP BY z.id, z.name
         ORDER BY z.name"
    );

    $cuisines = fetchRows(
        $conn,
        "SELECT cuisine, COUNT(*) AS total
         FROM restaurants
         WHERE status = 'ACTIVE' AND cuisine IS NOT NULL AND cuisine <> ''
         GROUP BY cuisine
         ORDER BY total DESC, cuisine
         LIMIT 10"
    );

    $where = ["r.status = 'ACTIVE'"];
    $types = '';
    $params = [];
    if ($search !== '') {
        $where[] = "(r.name LIKE ? OR r.cuisine LIKE ? OR r.address_line LIKE ? OR EXISTS (
            SELECT 1 FROM menu_items mi
            WHERE mi.restaurant_id = r.id AND mi.name LIKE ?
        ))";
        $like = '%' . $search . '%';
        $types .= 'ssss';
        $params[] = $like;
        $params[] = $like;
        $params[] = $like;
        $params[] = $like;
    }
    if ($selectedZone !== '') {
        $where[] = "z.name = ?";
        $types .= 's';
        $params[] = $selectedZone;
    }

    $distanceSql = $hasLocation
        ? ", (6371 * ACOS(LEAST(1, COS(RADIANS(?)) * COS(RADIANS(r.latitude)) * COS(RADIANS(r.longitude) - RADIANS(?)) + SIN(RADIANS(?)) * SIN(RADIANS(r.latitude))))) AS distance_km"
        : ", NULL AS distance_km";
    $distanceOrder = $hasLocation ? "distance_km ASC," : "";
    $restaurantTypes = $hasLocation ? 'ddd' . $types : $types;
    $restaurantParams = $hasLocation ? array_merge([$lat, $lng, $lat], $params) : $params;

    $restaurants = fetchRows(
        $conn,
        "SELECT
            r.id, r.name, r.cuisine, r.rating, r.review_count,
            r.delivery_time_minutes, r.delivery_fee, r.min_order_value,
            r.packaging_charge, r.image_url, r.image_category, r.is_pure_veg,
            r.is_online, r.address_line, r.landmark, r.latitude, r.longitude,
            z.name AS zone_name, c.name AS city_name,
            COUNT(mi.id) AS menu_count, MIN(mi.price) AS starting_price
            {$distanceSql}
         FROM restaurants r
         LEFT JOIN zones z ON z.id = r.zone_id
         LEFT JOIN cities c ON c.id = r.city_id
         LEFT JOIN menu_items mi ON mi.restaurant_id = r.id AND mi.is_available = 1
         WHERE " . implode(' AND ', $where) . "
         GROUP BY r.id, z.name, c.name
         ORDER BY {$distanceOrder} r.is_online DESC, r.rating DESC, r.delivery_time_minutes ASC
         LIMIT 24",
        $restaurantTypes,
        $restaurantParams
    );

    $featuredItems = fetchRows(
        $conn,
        "SELECT
            mi.id, mi.name, mi.description, mi.price, mi.competitor_price,
            mi.is_veg, mi.rating, mi.is_bestseller, mi.image_url, mi.image_emoji,
            mi.preparation_time_minutes, r.id AS restaurant_id, r.name AS restaurant_name,
            r.delivery_time_minutes, r.delivery_fee
         FROM menu_items mi
         JOIN restaurants r ON r.id = mi.restaurant_id
         WHERE mi.is_available = 1 AND r.status = 'ACTIVE'
         ORDER BY mi.is_bestseller DESC, mi.rating DESC, mi.created_at DESC
         LIMIT 12"
    );

    $restaurantIds = array_values(array_unique(array_map('intval', array_column($restaurants, 'id'))));
    if (!empty($restaurantIds)) {
        $placeholders = implode(',', array_fill(0, count($restaurantIds), '?'));
        $menuRows = fetchRows(
            $conn,
            "SELECT
                mi.id, mi.name, mi.description, mi.price, mi.competitor_price,
                mi.is_veg, mi.rating, mi.is_bestseller, mi.image_url, mi.image_emoji,
                mi.preparation_time_minutes, r.id AS restaurant_id, r.name AS restaurant_name,
                r.delivery_time_minutes, r.delivery_fee
             FROM menu_items mi
             JOIN restaurants r ON r.id = mi.restaurant_id
             WHERE mi.is_available = 1 AND r.status = 'ACTIVE' AND r.id IN ({$placeholders})
             ORDER BY r.rating DESC, mi.is_bestseller DESC, mi.rating DESC, mi.name",
            str_repeat('i', count($restaurantIds)),
            $restaurantIds
        );
        foreach ($menuRows as $row) {
            $menuCatalog[(int) $row['restaurant_id']][] = $row;
        }
    }

    $offers = fetchRows(
        $conn,
        "SELECT
            r.id, r.name, r.cuisine, r.rating, r.delivery_time_minutes, r.image_url,
            MIN(mi.price) AS starting_price, COUNT(mi.id) AS menu_count
         FROM restaurants r
         LEFT JOIN menu_items mi ON mi.restaurant_id = r.id AND mi.is_available = 1
         WHERE r.status = 'ACTIVE'
         GROUP BY r.id
         ORDER BY r.rating DESC, menu_count DESC
         LIMIT 6"
    );

    $statRows = fetchRows(
        $conn,
        "SELECT
            COUNT(DISTINCT r.id) AS restaurants,
            COUNT(DISTINCT mi.id) AS items,
            COUNT(DISTINCT z.id) AS zones,
            ROUND(AVG(r.delivery_time_minutes)) AS avg_time
         FROM restaurants r
         LEFT JOIN menu_items mi ON mi.restaurant_id = r.id AND mi.is_available = 1
         LEFT JOIN zones z ON z.id = r.zone_id AND z.is_active = 1
         WHERE r.status = 'ACTIVE'"
    );
    if (!empty($statRows)) {
        $stats = array_merge($stats, array_map('intval', $statRows[0]));
    }
}

$heroSlides = !empty($offers) ? $offers : array_slice($restaurants, 0, 4);
$whatsAppLink = WHATSAPP_NUMBER !== ''
    ? 'https://wa.me/' . WHATSAPP_NUMBER . '?text=' . rawurlencode('Hi, I want help with my food order.')
    : '';
$seoDescription = 'Order food online from nearby hotels and restaurants. Browse menus, offers, delivery zones, popular dishes, and secure Razorpay checkout.';
$canonicalUrl = publicUrl('index.php');
$cartItemsJson = json_encode($featuredItems, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
$menuCatalogJson = json_encode($menuCatalog, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(SITE_NAME); ?> - Hotels, Restaurants, Offers and Online Food Delivery</title>
    <meta name="description" content="<?php echo e($seoDescription); ?>">
    <meta name="robots" content="index, follow, max-image-preview:large">
    <link rel="canonical" href="<?php echo e($canonicalUrl); ?>">
    <link rel="manifest" href="manifest.webmanifest">
    <meta property="og:title" content="<?php echo e(SITE_NAME); ?>">
    <meta property="og:description" content="<?php echo e($seoDescription); ?>">
    <meta property="og:type" content="website">
    <meta property="og:url" content="<?php echo e($canonicalUrl); ?>">
    <meta property="og:image" content="<?php echo e(publicUrl('img/logo.jpeg')); ?>">
    <meta name="twitter:card" content="summary_large_image">
    <script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "FoodEstablishment",
        "name": <?php echo json_encode(SITE_NAME); ?>,
        "url": <?php echo json_encode($canonicalUrl); ?>,
        "servesCuisine": <?php echo json_encode(array_values(array_filter(array_column($cuisines, 'cuisine')))); ?>,
        "potentialAction": {
            "@type": "SearchAction",
            "target": <?php echo json_encode(publicUrl('index.php?q={search_term_string}')); ?>,
            "query-input": "required name=search_term_string"
        }
    }
    </script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    <script src="https://checkout.razorpay.com/v1/checkout.js" defer></script>
    <?php if (RECAPTCHA_SITE_KEY !== ''): ?>
        <script src="https://www.google.com/recaptcha/api.js?render=<?php echo e(RECAPTCHA_SITE_KEY); ?>" defer></script>
    <?php endif; ?>
    <style>
        :root { color-scheme: light; --bg: #f6f7f9; --surface: #ffffff; --surface-2: #f1f4f8; --ink: #101828; --muted: #667085; --line: #dde3ea; --brand: #ff5722; --brand-dark: #bf3510; --green: #14803d; --shadow: 0 18px 45px rgba(18, 24, 38, 0.11); --shadow-strong: 0 24px 58px rgba(18, 24, 38, 0.16); }
        * { box-sizing: border-box; }
        html { scroll-behavior: smooth; }
        html, body { margin: 0; min-height: 100%; }
        body { background: radial-gradient(circle at top left, rgba(255,87,34,.08), transparent 34%), var(--bg); color: var(--ink); font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
        body.drawer-open { overflow: hidden; }
        a { color: inherit; text-decoration: none; }
        button, input, select { font: inherit; }
        button { cursor: pointer; }
        .wrap { width: min(1200px, calc(100% - 32px)); margin: 0 auto; }
        .topbar { position: sticky; top: 0; z-index: 40; border-bottom: 1px solid rgba(221, 227, 234, 0.88); background: rgba(255, 255, 255, 0.92); backdrop-filter: blur(18px); }
        .nav { display: grid; grid-template-columns: auto minmax(220px, 1fr) auto; align-items: center; min-height: 74px; gap: 16px; }
        .brand { display: inline-flex; align-items: center; gap: 11px; font-weight: 950; min-width: max-content; }
        .brand-mark { display: grid; place-items: center; width: 42px; height: 42px; border-radius: 10px; background: var(--brand); color: #fff; box-shadow: 0 10px 24px rgba(255, 87, 34, 0.28); }
        .nav-search { display: grid; grid-template-columns: 1fr auto auto; align-items: center; gap: 8px; padding: 8px; border: 1px solid var(--line); border-radius: 14px; background: var(--surface-2); }
        .nav-search input, .nav-search select { min-width: 0; border: 0; outline: 0; background: transparent; color: var(--ink); font-weight: 750; }
        .nav-search button, .icon-btn, .primary-btn, .ghost-btn { min-height: 42px; border: 0; border-radius: 11px; font-weight: 900; }
        .nav-search button, .primary-btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; padding: 0 15px; background: var(--brand); color: #fff; }
        .nav-actions { display: flex; align-items: center; justify-content: flex-end; gap: 9px; }
        .icon-btn { position: relative; display: grid; place-items: center; width: 44px; border: 1px solid var(--line); background: var(--surface); color: var(--ink); }
        .count-badge { position: absolute; top: -6px; right: -6px; min-width: 20px; height: 20px; display: grid; place-items: center; border-radius: 999px; background: var(--brand); color: #fff; font-size: 11px; font-weight: 950; }
        .menu-bar { border-top: 1px solid rgba(221, 227, 234, 0.7); }
        .menu-row { display: flex; align-items: center; gap: 6px; min-height: 48px; overflow-x: auto; }
        .menu-item { position: relative; flex: 0 0 auto; padding: 13px 12px; color: var(--muted); font-size: 14px; font-weight: 850; }
        .menu-item:hover { color: var(--ink); }
        .mega-trigger:hover .mega, .mega:focus-within { display: block; }
        .mega { display: none; position: absolute; top: 48px; left: 0; width: min(720px, calc(100vw - 32px)); padding: 18px; border: 1px solid var(--line); border-radius: 16px; background: var(--surface); box-shadow: var(--shadow); z-index: 50; }
        .mega-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
        .mega h3 { margin: 0 0 9px; font-size: 14px; }
        .mega a { display: flex; justify-content: space-between; gap: 12px; padding: 8px 0; color: var(--muted); font-size: 13px; font-weight: 800; }
        .mega a:hover { color: var(--brand-dark); }
        .hero { padding: 26px 0 18px; }
        .hero-panel { display: grid; grid-template-columns: minmax(0, 1.08fr) minmax(300px, 0.92fr); gap: 22px; align-items: stretch; }
        .hero-copy, .banner { border: 1px solid rgba(221,227,234,.9); border-radius: 22px; background: rgba(255,255,255,.96); box-shadow: var(--shadow); }
        .hero-copy { padding: 30px; }
        .eyebrow { display: inline-flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 999px; background: #fff0ea; color: var(--brand-dark); font-size: 13px; font-weight: 950; }
        h1 { margin: 18px 0 12px; max-width: 780px; font-size: clamp(34px, 6vw, 60px); line-height: 0.98; letter-spacing: 0; }
        .lead { max-width: 680px; margin: 0 0 22px; color: var(--muted); font-size: 17px; line-height: 1.58; font-weight: 650; }
        .hero-actions { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px; }
        .ghost-btn { display: inline-flex; align-items: center; gap: 8px; padding: 0 14px; border: 1px solid var(--line); background: var(--surface); color: var(--ink); }
        .stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
        .stat { padding: 14px; border: 1px solid var(--line); border-radius: 14px; background: var(--surface-2); }
        .stat strong { display: block; font-size: 22px; font-weight: 950; }
        .stat span { color: var(--muted); font-size: 12px; font-weight: 850; }
        .banner { position: relative; overflow: hidden; min-height: 408px; }
        .slide { position: absolute; inset: 0; display: grid; align-content: end; padding: 24px; opacity: 0; pointer-events: none; transition: opacity 420ms ease; color: #fff; background: linear-gradient(180deg, rgba(18,24,38,0.05), rgba(18,24,38,0.82)), var(--brand); }
        .slide.active { opacity: 1; pointer-events: auto; }
        .slide img { position: absolute; inset: 0; z-index: 0; width: 100%; height: 100%; object-fit: cover; }
        .slide::after { content: ""; position: absolute; inset: 0; z-index: 1; background: linear-gradient(180deg, rgba(18,24,38,0.04), rgba(18,24,38,0.78)); }
        .slide-content { position: relative; z-index: 2; }
        .slide h2 { margin: 8px 0; font-size: 30px; line-height: 1.08; }
        .slide p { margin: 0; color: rgba(255,255,255,0.85); font-weight: 750; }
        .slide-chip { display: inline-flex; align-items: center; gap: 7px; padding: 8px 10px; border-radius: 999px; background: rgba(255,255,255,0.18); font-size: 13px; font-weight: 950; }
        .slide-dots { position: absolute; right: 18px; bottom: 18px; z-index: 3; display: flex; gap: 7px; }
        .slide-dots button { width: 9px; height: 9px; padding: 0; border: 0; border-radius: 999px; background: rgba(255,255,255,0.45); }
        .slide-dots button.active { width: 24px; background: #fff; }
        .section { padding: 18px 0; }
        .section-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 18px; margin-bottom: 14px; }
        .section-head h2 { margin: 0 0 6px; font-size: 28px; }
        .section-head p { margin: 0; color: var(--muted); font-weight: 650; }
        .zone-strip { display: flex; gap: 10px; overflow-x: auto; padding-bottom: 3px; }
        .zone { flex: 0 0 auto; padding: 10px 14px; border: 1px solid var(--line); border-radius: 999px; background: var(--surface); color: var(--muted); font-size: 14px; font-weight: 900; }
        .zone.active, .zone:hover { border-color: var(--brand); color: var(--brand-dark); background: #fff4ee; }
        .restaurant-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
        .dish-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; }
        .restaurant-card, .dish-card, .footer-card { border: 1px solid rgba(221,227,234,.92); border-radius: 16px; background: rgba(255,255,255,.98); box-shadow: 0 10px 28px rgba(18, 24, 38, 0.06); overflow: hidden; transition: transform 180ms ease, box-shadow 180ms ease, border-color 180ms ease; }
        .restaurant-card:hover, .dish-card:hover { transform: translateY(-3px); border-color: rgba(255,87,34,.42); box-shadow: var(--shadow-strong); }
        .restaurant-image { position: relative; min-height: 184px; background: linear-gradient(135deg, #fff1eb, #edf5ff); }
        .restaurant-image img { width: 100%; height: 190px; object-fit: cover; display: block; transform: scale(1.01); transition: transform 260ms ease; }
        .restaurant-card:hover .restaurant-image img { transform: scale(1.05); }
        .image-fallback { display: grid; place-items: center; min-height: 190px; color: var(--brand); font-size: 42px; }
        .badge-row { position: absolute; left: 12px; right: 12px; bottom: 12px; display: flex; flex-wrap: wrap; gap: 7px; }
        .badge { display: inline-flex; align-items: center; gap: 6px; padding: 7px 9px; border-radius: 999px; background: rgba(255,255,255,0.92); color: var(--ink); font-size: 12px; font-weight: 950; }
        .badge.green { color: var(--green); }
        .restaurant-body { padding: 16px; }
        .restaurant-title { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
        .restaurant-title h3, .dish-card h3 { margin: 0; font-size: 18px; line-height: 1.2; }
        .rating { display: inline-flex; align-items: center; gap: 5px; padding: 6px 8px; border-radius: 8px; background: var(--green); color: #fff; font-size: 12px; font-weight: 950; }
        .meta { display: flex; flex-wrap: wrap; gap: 8px 12px; margin-top: 13px; color: var(--muted); font-size: 13px; font-weight: 800; }
        .meta span { display: inline-flex; align-items: center; gap: 6px; }
        .dish-card { padding: 14px; }
        .dish-media { display: grid; place-items: center; height: 126px; border-radius: 12px; background: linear-gradient(135deg, #fff7ed, #edf5ff); color: var(--brand); font-size: 40px; font-weight: 950; overflow: hidden; }
        .dish-media img { width: 100%; height: 100%; object-fit: cover; }
        .dish-card p { min-height: 40px; margin: 7px 0 0; color: var(--muted); font-size: 13px; line-height: 1.45; }
        .dish-foot { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-top: 12px; }
        .price { font-size: 18px; font-weight: 950; }
        .add { min-height: 36px; padding: 0 12px; border: 1px solid var(--brand); border-radius: 10px; color: var(--brand-dark); background: #fff7f3; font-size: 13px; font-weight: 950; }
        .card-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; }
        .review-stars { display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px; margin: 12px 0; }
        .review-stars button { min-height: 42px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface-2); font-weight: 950; }
        .review-stars button.active { border-color: var(--brand); color: var(--brand-dark); background: #fff4ee; }
        .review-text { width: 100%; min-height: 92px; padding: 12px; border: 1px solid var(--line); border-radius: 12px; resize: vertical; }
        .empty { padding: 28px; border: 1px dashed var(--line); border-radius: 16px; background: var(--surface); color: var(--muted); text-align: center; }
        .floating-left, .floating-right { position: fixed; z-index: 60; display: grid; gap: 10px; }
        .floating-left { left: 18px; bottom: 18px; }
        .floating-right { right: 18px; bottom: 18px; }
        .float-btn { display: grid; place-items: center; width: 48px; height: 48px; border: 1px solid var(--line); border-radius: 14px; background: var(--surface); color: var(--ink); box-shadow: 0 12px 30px rgba(18,24,38,0.14); }
        .whatsapp { background: #22c55e; color: #fff; border-color: #22c55e; }
        .recaptcha-note { max-width: 230px; padding: 9px 11px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); color: var(--muted); font-size: 11px; line-height: 1.35; box-shadow: 0 12px 30px rgba(18,24,38,0.12); }
        .drawer { position: fixed; inset: 0; z-index: 80; display: none; background: rgba(18,24,38,0.5); }
        .drawer.open { display: block; }
        .drawer-panel { position: absolute; top: 0; right: 0; width: min(430px, 100%); height: 100%; display: grid; grid-template-rows: auto 1fr auto; background: var(--surface); box-shadow: var(--shadow); }
        .drawer-head, .drawer-foot { padding: 18px; border-bottom: 1px solid var(--line); }
        .drawer-foot { border-top: 1px solid var(--line); border-bottom: 0; }
        .drawer-title { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
        .drawer-list { overflow: auto; padding: 12px 18px; }
        .cart-row { display: grid; grid-template-columns: 1fr auto; gap: 10px; padding: 12px 0; border-bottom: 1px solid var(--line); }
        .qty { display: inline-flex; align-items: center; gap: 8px; margin-top: 9px; padding: 6px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface-2); }
        .qty strong { min-width: 24px; text-align: center; }
        .qty button, .cart-qty-btn { width: 34px; height: 34px; display: inline-grid; place-items: center; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); color: var(--ink); font-weight: 950; }
        .qty button:hover, .cart-qty-btn:hover { border-color: var(--brand); color: var(--brand-dark); background: #fff7f3; }
        .cart-remove-btn { color: #b42318; }
        .checkout-form { display: grid; gap: 9px; margin-top: 14px; }
        .checkout-form input, .checkout-form textarea { width: 100%; padding: 11px 12px; border: 1px solid var(--line); border-radius: 11px; outline: 0; }
        .checkout-form textarea { min-height: 76px; resize: vertical; }
        .cart-tools { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-top: 10px; }
        .notify-panel { position: fixed; top: 92px; right: 18px; z-index: 70; width: min(360px, calc(100vw - 36px)); display: none; padding: 14px; border: 1px solid var(--line); border-radius: 16px; background: var(--surface); box-shadow: var(--shadow); }
        .notify-panel.open { display: block; }
        .notice { padding: 10px 0; border-bottom: 1px solid var(--line); }
        .notice:last-child { border-bottom: 0; }
        .notice strong { display: block; font-size: 14px; }
        .notice span { display: block; margin-top: 4px; color: var(--muted); font-size: 13px; }
        .modal { position: fixed; inset: 0; z-index: 90; display: none; place-items: center; padding: 20px; background: rgba(18,24,38,0.58); }
        .modal.open { display: grid; }
        .modal-box { width: min(520px, 100%); border-radius: 20px; background: var(--surface); overflow: hidden; box-shadow: var(--shadow); }
        .modal-media { min-height: 190px; background: linear-gradient(135deg, #fff1eb, #eaf2ff); }
        .modal-media img { width: 100%; height: 230px; object-fit: cover; display: block; }
        .modal-body { padding: 20px; }
        .modal-body h2 { margin: 0 0 8px; }
        .menu-panel { display: none; margin-top: 16px; padding: 16px; border: 1px solid var(--line); border-radius: 16px; background: var(--surface); box-shadow: 0 10px 28px rgba(18,24,38,0.06); }
        .menu-panel.open { display: block; }
        .menu-panel-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; margin-bottom: 14px; }
        .menu-panel-head h3 { margin: 0 0 5px; font-size: 22px; }
        .menu-panel-head p { margin: 0; color: var(--muted); font-weight: 700; }
        .detail-price-row, .tracking-stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; margin: 14px 0; }
        .price-box, .tracking-stat { padding: 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface-2); }
        .price-box span, .tracking-stat span { display: block; color: var(--muted); font-size: 12px; font-weight: 850; }
        .price-box strong, .tracking-stat strong { display: block; margin-top: 4px; font-size: 17px; font-weight: 950; }
        .quantity-picker { display: inline-flex; align-items: center; gap: 12px; padding: 8px; border: 1px solid var(--line); border-radius: 13px; background: var(--surface-2); }
        .quantity-picker button { width: 36px; height: 36px; border: 0; border-radius: 10px; background: var(--surface); font-size: 18px; font-weight: 950; }
        .tracking-panel { display: none; }
        .tracking-panel.open { display: block; }
        .tracking-card { display: grid; grid-template-columns: minmax(0, 1fr) minmax(300px, 0.78fr); gap: 16px; border: 1px solid var(--line); border-radius: 16px; background: var(--surface); box-shadow: 0 10px 28px rgba(18,24,38,0.06); padding: 16px; }
        .map-box { min-height: 230px; position: relative; overflow: hidden; border-radius: 14px; background: linear-gradient(135deg, #eaf7ee, #edf5ff); border: 1px solid var(--line); }
        .map-route { position: absolute; left: 18%; right: 18%; top: 50%; border-top: 4px dashed rgba(255,87,34,0.55); transform: rotate(-8deg); }
        .map-pin { position: absolute; display: grid; place-items: center; width: 42px; height: 42px; border-radius: 999px; background: var(--surface); color: var(--brand); box-shadow: 0 10px 22px rgba(18,24,38,0.16); }
        .map-pin.origin { left: 12%; top: 28%; }
        .map-pin.destination { right: 13%; bottom: 24%; color: var(--green); }
        .map-pin.moving { left: 48%; top: 44%; background: var(--brand); color: #fff; }
        .chat-box { border: 1px solid var(--line); border-radius: 14px; overflow: hidden; background: var(--surface); }
        .chat-log { height: 220px; overflow: auto; padding: 12px; background: var(--surface-2); }
        .chat-message { max-width: 86%; margin: 0 0 9px; padding: 9px 11px; border-radius: 12px; background: var(--surface); font-size: 13px; font-weight: 700; }
        .chat-message.customer { margin-left: auto; background: #fff4ee; color: var(--brand-dark); }
        .chat-form { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-top: 1px solid var(--line); }
        .chat-form input { min-width: 0; padding: 11px 12px; border: 1px solid var(--line); border-radius: 11px; outline: 0; }
        .footer { margin-top: 24px; padding: 36px 0; border-top: 1px solid var(--line); background: var(--surface); }
        .footer-grid { display: grid; grid-template-columns: 1.3fr repeat(3, 1fr); gap: 18px; }
        .footer-card { padding: 16px; box-shadow: none; }
        .support-card { background: #111827; color: #fff; border-color: #111827; }
        .support-card p, .support-card a { color: rgba(255,255,255,.78); }
        .support-card .primary-btn { margin-top: 12px; color: #fff; }
        .footer-card h3 { margin: 0 0 10px; font-size: 15px; }
        .footer-card a, .footer-card p { display: block; margin: 8px 0 0; color: var(--muted); font-size: 13px; font-weight: 760; }
        @media (max-width: 1040px) { .nav { grid-template-columns: 1fr auto; } .nav-search { grid-column: 1 / -1; grid-row: 2; margin-bottom: 12px; } .hero-panel, .tracking-card { grid-template-columns: 1fr; } .restaurant-grid, .dish-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .footer-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .stats { grid-template-columns: repeat(2, 1fr); } }
        @media (max-width: 700px) { .wrap { width: min(100% - 24px, 1200px); } .nav { gap: 10px; min-height: auto; padding: 12px 0; } .brand span:last-child { display: none; } .nav-actions { gap: 6px; } .nav-search { grid-template-columns: 1fr; } .nav-search button { width: 100%; } .menu-row { min-height: 44px; } .mega { display: none !important; } .hero-copy { padding: 20px; } .banner { min-height: 330px; } .section-head, .menu-panel-head { align-items: flex-start; flex-direction: column; } .restaurant-grid, .dish-grid, .stats, .footer-grid, .detail-price-row, .tracking-stats { grid-template-columns: 1fr; } .floating-right { right: 12px; bottom: 12px; } .floating-left { left: 12px; bottom: 12px; } .recaptcha-note { display: none; } }
    </style>
</head>
<body id="top">
    <header class="topbar">
        <div class="wrap nav">
            <a class="brand" href="index.php" aria-label="<?php echo e(SITE_NAME); ?> home"><span class="brand-mark"><i class="bi bi-bag-heart-fill"></i></span><span><?php echo e(SITE_NAME); ?></span></a>
            <form class="nav-search" method="GET" action="index.php" role="search">
                <input type="search" name="q" value="<?php echo e($search); ?>" placeholder="Search for hotels, dishes, cuisines">
                <select name="zone" aria-label="Delivery zone">
                    <option value="">All zones</option>
                    <?php foreach ($zones as $zone): ?>
                        <option value="<?php echo e($zone['name']); ?>" <?php echo $selectedZone === $zone['name'] ? 'selected' : ''; ?>><?php echo e($zone['name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <?php if ($hasLocation): ?><input type="hidden" name="lat" value="<?php echo e($lat); ?>"><input type="hidden" name="lng" value="<?php echo e($lng); ?>"><?php endif; ?>
                <button type="submit"><i class="bi bi-search"></i> Search</button>
            </form>
            <div class="nav-actions">
                <?php if ($currentUserId > 0): ?>
                    <a class="ghost-btn" href="google_login.php?action=logout" title="Logout"><?php echo e($currentUserName ?: 'Account'); ?></a>
                <?php elseif ($googleLoginConfigured): ?>
                    <a class="ghost-btn" href="google_login.php?action=start" title="Login with Google"><i class="bi bi-google"></i> Login</a>
                <?php else: ?>
                    <button class="ghost-btn" type="button" id="loginUnavailableBtn" title="Login setup pending"><i class="bi bi-person"></i> Guest</button>
                <?php endif; ?>
                <button class="icon-btn" type="button" id="locationBtn" title="Use GPS location" aria-label="Use GPS location"><i class="bi bi-crosshair"></i></button>
                <button class="icon-btn" type="button" id="notifyBtn" title="Notifications" aria-label="Notifications"><i class="bi bi-bell"></i><span class="count-badge" id="notifyCount">0</span></button>
                <button class="icon-btn" type="button" id="cartBtn" title="Cart" aria-label="Cart"><i class="bi bi-bag"></i><span class="count-badge" id="cartCount">0</span></button>
            </div>
        </div>
        <div class="menu-bar">
            <nav class="wrap menu-row" aria-label="Mega menu">
                <div class="menu-item mega-trigger">Browse
                    <div class="mega"><div class="mega-grid">
                        <div><h3>Delivery Zones</h3><a href="index.php">All areas <span><?php echo (int) $stats['restaurants']; ?></span></a><?php foreach (array_slice($zones, 0, 8) as $zone): ?><a href="index.php?zone=<?php echo rawurlencode($zone['name']); ?>"><?php echo e($zone['name']); ?> <span><?php echo (int) $zone['restaurant_count']; ?></span></a><?php endforeach; ?></div>
                        <div><h3>Cuisines</h3><?php foreach (array_slice($cuisines, 0, 8) as $cuisine): ?><a href="index.php?q=<?php echo rawurlencode($cuisine['cuisine']); ?>"><?php echo e($cuisine['cuisine']); ?> <span><?php echo (int) $cuisine['total']; ?></span></a><?php endforeach; ?></div>
                        <div><h3>Quick Links</h3><a href="#restaurants">Hotels and restaurants <span><i class="bi bi-arrow-right"></i></span></a><a href="#dishes">Popular dishes <span><i class="bi bi-arrow-right"></i></span></a><a href="#offers">Live offers <span><i class="bi bi-arrow-right"></i></span></a><a href="order_lifecycle.php">Order lifecycle <span><i class="bi bi-diagram-3"></i></span></a><a href="api_manager.php">API Manager <span><i class="bi bi-shield-check"></i></span></a></div>
                    </div></div>
                </div>
                <a class="menu-item" href="#restaurants">Restaurants</a><a class="menu-item" href="#dishes">Popular dishes</a><a class="menu-item" href="#offers">Offers</a><a class="menu-item" href="order_lifecycle.php">Order lifecycle</a><a class="menu-item" href="sitemap.php">Sitemap</a>
            </nav>
        </div>
    </header>

    <main>
        <section class="hero"><div class="wrap hero-panel">
            <div class="hero-copy">
                <span class="eyebrow"><i class="bi bi-geo-alt-fill"></i> <?php echo $hasLocation ? 'Sorted using your GPS location' : 'Fast food ordering for local delivery zones'; ?></span>
                <h1>Order from trusted hotels near you.</h1>
                <p class="lead">Discover restaurants, live offers, popular dishes, secure checkout, and delivery zones in one responsive food ordering experience.</p>
                <div class="hero-actions"><a class="primary-btn" href="#restaurants"><i class="bi bi-shop"></i> View hotels</a><button class="ghost-btn" type="button" id="heroLocationBtn"><i class="bi bi-crosshair"></i> Use my location</button><button class="ghost-btn" type="button" id="offerBtn"><i class="bi bi-percent"></i> Show offers</button></div>
                <div class="stats" aria-label="Marketplace stats"><div class="stat"><strong><?php echo (int) $stats['restaurants']; ?></strong><span>Active hotels</span></div><div class="stat"><strong><?php echo (int) $stats['items']; ?></strong><span>Menu items</span></div><div class="stat"><strong><?php echo (int) $stats['zones']; ?></strong><span>Delivery zones</span></div><div class="stat"><strong><?php echo (int) $stats['avg_time']; ?> min</strong><span>Avg delivery</span></div></div>
            </div>
            <aside class="banner" aria-label="Featured offers">
                <?php if (empty($heroSlides)): ?>
                    <div class="slide active"><div class="slide-content"><span class="slide-chip"><i class="bi bi-lightning-charge-fill"></i> Fresh launch</span><h2>Food ordering is ready for your hotels.</h2><p>Add restaurants and dishes in the database to make this banner dynamic.</p></div></div>
                <?php else: ?>
                    <?php foreach ($heroSlides as $index => $slide): ?>
                        <div class="slide <?php echo $index === 0 ? 'active' : ''; ?>"><?php if (!empty($slide['image_url'])): ?><img src="<?php echo e($slide['image_url']); ?>" alt="<?php echo e($slide['name']); ?>"><?php endif; ?><div class="slide-content"><span class="slide-chip"><i class="bi bi-star-fill"></i> <?php echo e(number_format((float) ($slide['rating'] ?? 4.5), 1)); ?> rated</span><h2><?php echo e($slide['name']); ?></h2><p><?php echo e(($slide['cuisine'] ?? 'Popular food') . ' from ' . money($slide['starting_price'] ?? 0) . ' - ' . (int) ($slide['delivery_time_minutes'] ?? 25) . ' min delivery'); ?></p></div></div>
                    <?php endforeach; ?>
                <?php endif; ?>
                <div class="slide-dots" id="slideDots" aria-label="Banner controls"></div>
            </aside>
        </div></section>

        <section class="section"><div class="wrap"><div class="section-head"><div><h2>Delivery zones</h2><p>Choose a service area to narrow restaurants and delivery availability.</p></div><?php if ($search !== '' || $selectedZone !== '' || $hasLocation): ?><a class="ghost-btn" href="index.php">Clear filters</a><?php endif; ?></div><div class="zone-strip"><a class="zone <?php echo $selectedZone === '' ? 'active' : ''; ?>" href="index.php<?php echo $search !== '' ? '?q=' . rawurlencode($search) : ''; ?>">All areas</a><?php foreach ($zones as $zone): ?><?php $query = array_filter(['q' => $search, 'zone' => $zone['name']], static function ($value) { return $value !== ''; }); $href = 'index.php' . (!empty($query) ? '?' . http_build_query($query) : ''); ?><a class="zone <?php echo $selectedZone === $zone['name'] ? 'active' : ''; ?>" href="<?php echo e($href); ?>"><?php echo e($zone['name']); ?> - <?php echo (int) $zone['restaurant_count']; ?></a><?php endforeach; ?></div></div></section>

        <section class="section" id="restaurants"><div class="wrap"><div class="section-head"><div><h2>Hotels and restaurants</h2><p>Live restaurants from the ordering database, sorted by availability, rating, speed, and location when enabled.</p></div></div>
            <?php if (!$isConnected): ?><div class="empty">Database is not connected. <?php echo e($connError ?: 'Please check server configuration.'); ?></div>
            <?php elseif (empty($restaurants)): ?><div class="empty">No restaurants match this search yet.</div>
            <?php else: ?><div class="restaurant-grid"><?php foreach ($restaurants as $restaurant): ?><article class="restaurant-card js-restaurant-card" data-restaurant-id="<?php echo (int) $restaurant['id']; ?>" data-restaurant-name="<?php echo e($restaurant['name']); ?>" data-restaurant-cuisine="<?php echo e($restaurant['cuisine']); ?>" tabindex="0" role="button" aria-label="Open <?php echo e($restaurant['name']); ?> dishes"><div class="restaurant-image"><?php if (!empty($restaurant['image_url'])): ?><img src="<?php echo e($restaurant['image_url']); ?>" alt="<?php echo e($restaurant['name']); ?>"><?php else: ?><div class="image-fallback"><i class="bi bi-shop"></i></div><?php endif; ?><div class="badge-row"><span class="badge green"><i class="bi bi-circle-fill"></i> <?php echo ((int) $restaurant['is_online']) === 1 ? 'Online' : 'Offline'; ?></span><?php if ((int) $restaurant['is_pure_veg'] === 1): ?><span class="badge"><i class="bi bi-flower1"></i> Pure veg</span><?php endif; ?></div></div><div class="restaurant-body"><div class="restaurant-title"><h3><?php echo e($restaurant['name']); ?></h3><span class="rating"><i class="bi bi-star-fill"></i> <?php echo e(number_format((float) $restaurant['rating'], 1)); ?></span></div><div class="meta"><span><i class="bi bi-shop"></i> <?php echo e($restaurant['cuisine']); ?></span><span><i class="bi bi-geo-alt"></i> <?php echo e($restaurant['zone_name'] ?: $restaurant['city_name'] ?: 'Nearby'); ?></span><span><i class="bi bi-clock"></i> <?php echo (int) $restaurant['delivery_time_minutes']; ?> min</span><span><i class="bi bi-currency-rupee"></i> Starts <?php echo money($restaurant['starting_price'] ?? 0); ?></span><span><i class="bi bi-bicycle"></i> Delivery <?php echo money($restaurant['delivery_fee']); ?></span><?php if ($hasLocation && $restaurant['distance_km'] !== null): ?><span><i class="bi bi-signpost-2"></i> <?php echo e(number_format((float) $restaurant['distance_km'], 1)); ?> km</span><?php endif; ?></div><div class="card-actions"><button class="add js-view-menu" type="button" data-restaurant-id="<?php echo (int) $restaurant['id']; ?>" data-restaurant-name="<?php echo e($restaurant['name']); ?>" data-restaurant-cuisine="<?php echo e($restaurant['cuisine']); ?>"><i class="bi bi-card-list"></i> View dishes</button><button class="add js-review" type="button" data-restaurant-id="<?php echo (int) $restaurant['id']; ?>" data-restaurant-name="<?php echo e($restaurant['name']); ?>"><i class="bi bi-star"></i> Rate & review</button><button class="add js-load-reviews" type="button" data-restaurant-id="<?php echo (int) $restaurant['id']; ?>" data-restaurant-name="<?php echo e($restaurant['name']); ?>"><i class="bi bi-chat-left-text"></i> Reviews</button></div></div></article><?php endforeach; ?></div><?php endif; ?>
            <div class="menu-panel" id="restaurantMenuPanel" aria-live="polite"><div class="menu-panel-head"><div><h3 id="restaurantMenuTitle">Restaurant dishes</h3><p id="restaurantMenuMeta">Choose dishes from one hotel at a time.</p></div><button class="ghost-btn" type="button" id="closeRestaurantMenu"><i class="bi bi-x-lg"></i> Close</button></div><div class="dish-grid" id="restaurantMenuGrid"></div></div>
        </div></section>

        <section class="section" id="dishes"><div class="wrap"><div class="section-head"><div><h2>Popular dishes</h2><p>Add items to cart and checkout through the Razorpay API when keys are configured.</p></div></div>
            <?php if (empty($featuredItems)): ?><div class="empty">No available dishes found yet.</div>
            <?php else: ?><div class="dish-grid"><?php foreach ($featuredItems as $item): ?><article class="dish-card js-dish-card" data-id="<?php echo (int) $item['id']; ?>" data-name="<?php echo e($item['name']); ?>" data-description="<?php echo e($item['description'] ?: $item['restaurant_name']); ?>" data-price="<?php echo e($item['price']); ?>" data-restaurant="<?php echo e($item['restaurant_name']); ?>" data-restaurant-id="<?php echo (int) $item['restaurant_id']; ?>" data-prep="<?php echo (int) $item['preparation_time_minutes']; ?>" data-delivery-fee="<?php echo e($item['delivery_fee']); ?>" data-image-url="<?php echo e($item['image_url']); ?>" data-image-emoji="<?php echo e($item['image_emoji']); ?>" tabindex="0" role="button" aria-label="Open <?php echo e($item['name']); ?> details"><div class="dish-media"><?php if (!empty($item['image_url'])): ?><img src="<?php echo e($item['image_url']); ?>" alt="<?php echo e($item['name']); ?>"><?php else: ?><?php echo e($item['image_emoji'] ?: strtoupper(substr($item['name'], 0, 1))); ?><?php endif; ?></div><h3><?php echo e($item['name']); ?></h3><p><?php echo e($item['description'] ?: $item['restaurant_name']); ?></p><div class="meta"><span><i class="bi bi-shop"></i> <?php echo e($item['restaurant_name']); ?></span><span><i class="bi bi-clock"></i> <?php echo (int) $item['preparation_time_minutes']; ?> min prep</span></div><div class="dish-foot"><span class="price"><?php echo money($item['price']); ?></span><button class="add js-open-dish" type="button"><i class="bi bi-plus-lg"></i> Add</button></div></article><?php endforeach; ?></div><?php endif; ?>
        </div></section>

        <section class="section" id="offers"><div class="wrap"><div class="section-head"><div><h2>Live offers</h2><p>Dynamic offer popups use the top hotels and current menu data.</p></div><button class="ghost-btn" type="button" id="openOfferBtn"><i class="bi bi-gift"></i> Open offer popup</button></div></div></section>

        <section class="section tracking-panel" id="liveOrderTracking"><div class="wrap"><div class="section-head"><div><h2>Live order tracking</h2><p id="trackingSubtitle">Your active order will appear here after checkout.</p></div><button class="ghost-btn" type="button" id="refreshTracking"><i class="bi bi-arrow-clockwise"></i> Refresh</button></div><div class="tracking-card"><div><div class="map-box"><div class="map-route"></div><div class="map-pin origin"><i class="bi bi-shop"></i></div><div class="map-pin moving" id="trackingMovingPin"><i class="bi bi-bicycle"></i></div><div class="map-pin destination"><i class="bi bi-geo-alt-fill"></i></div></div><div class="tracking-stats"><div class="tracking-stat"><span>Status</span><strong id="trackingStatus">Pending</strong></div><div class="tracking-stat"><span>Distance</span><strong id="trackingDistance">--</strong></div><div class="tracking-stat"><span>Estimated time</span><strong id="trackingEta">--</strong></div></div><p id="trackingHint" style="margin:0; color:var(--muted); font-weight:700;"></p></div><div><h3 id="trackingPartner" style="margin:0 0 8px;">Restaurant</h3><p id="trackingAddress" style="margin:0 0 12px; color:var(--muted); font-weight:700;"></p><div class="chat-box"><div class="chat-log" id="chatLog"><div class="empty">Chat opens when an active order is loaded.</div></div><form class="chat-form" id="chatForm"><input type="text" id="chatMessage" placeholder="Message restaurant or rider" autocomplete="off"><button class="primary-btn" type="submit"><i class="bi bi-send"></i></button></form></div></div></div></div></section>
    </main>

    <footer class="footer"><div class="wrap footer-grid"><div class="footer-card"><h3><?php echo e(SITE_NAME); ?></h3><p>Online food ordering website for hotels, restaurants, delivery zones, popular dishes, secure checkout, and customer notifications.</p><p><?php echo e(DB_NAME); ?></p></div><div class="footer-card"><h3>Top Zones</h3><?php foreach (array_slice($zones, 0, 6) as $zone): ?><a href="index.php?zone=<?php echo rawurlencode($zone['name']); ?>"><?php echo e($zone['name']); ?></a><?php endforeach; ?></div><div class="footer-card"><h3>Cuisines</h3><?php foreach (array_slice($cuisines, 0, 6) as $cuisine): ?><a href="index.php?q=<?php echo rawurlencode($cuisine['cuisine']); ?>"><?php echo e($cuisine['cuisine']); ?></a><?php endforeach; ?></div><div class="footer-card support-card"><h3>Customer support</h3><p>Need help with an order, refund, delivery, or restaurant issue? Chat with support on WhatsApp.</p><?php if ($whatsAppLink !== ''): ?><a class="primary-btn" href="<?php echo e($whatsAppLink); ?>" target="_blank" rel="noopener"><i class="bi bi-whatsapp"></i> WhatsApp chat</a><?php else: ?><p>Set WHATSAPP_NUMBER in the secure environment to enable chat.</p><?php endif; ?><a href="order_lifecycle.php">Order lifecycle</a><a href="sitemap.php">Sitemap</a></div></div></footer>

    <div class="floating-left"><?php if ($whatsAppLink !== ''): ?><a class="float-btn whatsapp" href="<?php echo e($whatsAppLink); ?>" target="_blank" rel="noopener" aria-label="WhatsApp chat"><i class="bi bi-whatsapp"></i></a><?php endif; ?></div>
    <div class="floating-right"><?php if (RECAPTCHA_SITE_KEY !== ''): ?><div class="recaptcha-note">Protected by reCAPTCHA. Checkout requests can verify tokens server-side.</div><?php else: ?><div class="recaptcha-note">reCAPTCHA site key is not configured yet.</div><?php endif; ?><button class="float-btn" type="button" id="goTopBtn" aria-label="Go to top"><i class="bi bi-arrow-up"></i></button></div>

    <aside class="notify-panel" id="notifyPanel" aria-live="polite"><div class="drawer-title"><strong>Notifications</strong><button class="icon-btn" type="button" id="enableNotifications" title="Enable browser notifications" aria-label="Enable browser notifications"><i class="bi bi-volume-up"></i></button></div><div id="noticeList"></div></aside>
    <div class="drawer" id="cartDrawer" aria-hidden="true"><div class="drawer-panel"><div class="drawer-head"><div class="drawer-title"><strong>Your cart</strong><button class="icon-btn" type="button" id="closeCart" aria-label="Close cart"><i class="bi bi-x-lg"></i></button></div><div class="cart-tools"><span id="cartRestaurant" style="color:var(--muted); font-size:13px; font-weight:800;"></span><button class="ghost-btn" type="button" id="clearCartBtn"><i class="bi bi-trash"></i> Clear</button></div></div><div class="drawer-list" id="cartList"></div><div class="drawer-foot"><div class="drawer-title"><strong>Total</strong><strong id="cartTotal">Rs. 0</strong></div><div class="checkout-form"><input id="checkoutName" type="text" placeholder="Full name" autocomplete="name"><input id="checkoutPhone" type="tel" placeholder="Mobile number" autocomplete="tel"><textarea id="checkoutAddress" placeholder="Delivery address"></textarea><input id="checkoutInstructions" type="text" placeholder="Delivery instructions optional"></div><button class="primary-btn" type="button" id="checkoutBtn" style="width:100%; margin-top:12px;"><i class="bi bi-credit-card"></i> Pay with Razorpay</button><p style="margin:10px 0 0; color:var(--muted); font-size:12px;">Cart saves real orders and order items before Razorpay checkout. Use GPS to attach latitude and longitude.</p></div></div></div>
    <div class="modal" id="offerModal" aria-hidden="true"><div class="modal-box"><div class="modal-media" id="offerMedia"></div><div class="modal-body"><h2 id="offerTitle">Today offer</h2><p id="offerText"></p><div class="hero-actions" style="margin:16px 0 0;"><a class="primary-btn" href="#restaurants" id="offerCta">Order now</a><button class="ghost-btn" type="button" id="closeOffer">Close</button></div></div></div></div>
    <div class="modal" id="dishModal" aria-hidden="true"><div class="modal-box"><div class="modal-media" id="dishDetailMedia"></div><div class="modal-body"><h2 id="dishDetailTitle">Dish details</h2><p id="dishDetailText" style="color:var(--muted); font-weight:700;"></p><div class="detail-price-row"><div class="price-box"><span>Item price</span><strong id="dishDetailPrice">Rs. 0</strong></div><div class="price-box"><span>Quantity</span><strong id="dishDetailQuantity">1</strong></div><div class="price-box"><span>Total</span><strong id="dishDetailTotal">Rs. 0</strong></div></div><div class="hero-actions" style="align-items:center; margin:16px 0 0;"><div class="quantity-picker"><button type="button" id="dishQtyMinus">-</button><strong id="dishQtyValue">1</strong><button type="button" id="dishQtyPlus">+</button></div><button class="primary-btn" type="button" id="addDishDetail"><i class="bi bi-bag-plus"></i> Add food</button><button class="ghost-btn" type="button" id="closeDishDetail">Close</button></div></div></div></div>
    <div class="modal" id="reviewModal" aria-hidden="true"><div class="modal-box"><div class="modal-body"><h2 id="reviewTitle">Rate hotel</h2><p id="reviewHint"><?php echo $currentUserId > 0 ? 'Share your rating and review.' : ($googleLoginConfigured ? 'Login with Google to submit a rating.' : 'Reviews are visible. Google login setup is pending, so review submission is disabled.'); ?></p><div class="review-stars" id="reviewStars"><button type="button" data-star="1">1</button><button type="button" data-star="2">2</button><button type="button" data-star="3">3</button><button type="button" data-star="4">4</button><button type="button" data-star="5">5</button></div><textarea class="review-text" id="reviewText" placeholder="Write your experience"></textarea><div id="reviewsList" style="margin-top:12px;"></div><div class="hero-actions" style="margin:16px 0 0;"><?php if ($currentUserId > 0): ?><button class="primary-btn" type="button" id="submitReview">Submit review</button><?php elseif ($googleLoginConfigured): ?><a class="primary-btn" href="google_login.php?action=start"><i class="bi bi-google"></i> Login with Google</a><?php else: ?><button class="primary-btn" type="button" disabled><i class="bi bi-lock"></i> Login unavailable</button><?php endif; ?><button class="ghost-btn" type="button" id="closeReview">Close</button></div></div></div></div>

    <script>
        window.Storefront = {
            csrfToken: <?php echo json_encode($csrfToken); ?>,
            razorpayKey: <?php echo json_encode(RAZORPAY_KEY_ID); ?>,
            recaptchaSiteKey: <?php echo json_encode(RECAPTCHA_SITE_KEY); ?>,
            loggedIn: <?php echo $currentUserId > 0 ? 'true' : 'false'; ?>,
            googleLoginConfigured: <?php echo $googleLoginConfigured ? 'true' : 'false'; ?>,
            loginUnavailable: <?php echo ($_GET['login'] ?? '') === 'unavailable' ? 'true' : 'false'; ?>,
            offers: <?php echo json_encode($offers, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT); ?>,
            items: <?php echo $cartItemsJson ?: '[]'; ?>,
            menuCatalog: <?php echo $menuCatalogJson ?: '{}'; ?>
        };
    </script>
    <script>
        (() => {
            const money = (amount) => 'Rs. ' + Math.round(Number(amount || 0)).toLocaleString('en-IN');
            const cartKey = 'newone_cart_v1';
            const cart = new Map(JSON.parse(localStorage.getItem(cartKey) || '[]'));
            const cartBtn = document.getElementById('cartBtn');
            const cartDrawer = document.getElementById('cartDrawer');
            const cartList = document.getElementById('cartList');
            const cartCount = document.getElementById('cartCount');
            const cartTotal = document.getElementById('cartTotal');
            const cartRestaurant = document.getElementById('cartRestaurant');
            const checkoutBtn = document.getElementById('checkoutBtn');
            const orderKey = 'newone_active_order_v1';
            const orderPhoneKey = 'newone_active_order_phone_v1';
            const restaurantMenuPanel = document.getElementById('restaurantMenuPanel');
            const restaurantMenuGrid = document.getElementById('restaurantMenuGrid');
            const dishModal = document.getElementById('dishModal');
            let activeDish = null;
            let activeDishQty = 1;
            let activeOrderId = localStorage.getItem(orderKey) || '';
            let activeOrderPhone = localStorage.getItem(orderPhoneKey) || '';
            const notifyPanel = document.getElementById('notifyPanel');
            const notifyCount = document.getElementById('notifyCount');
            const noticeList = document.getElementById('noticeList');
            let noticesSeen = 0;
            let audioContext = null;
            const persistCart = () => localStorage.setItem(cartKey, JSON.stringify([...cart]));
            const sound = () => { try { audioContext = audioContext || new (window.AudioContext || window.webkitAudioContext)(); const oscillator = audioContext.createOscillator(); const gain = audioContext.createGain(); oscillator.frequency.value = 880; gain.gain.value = 0.035; oscillator.connect(gain); gain.connect(audioContext.destination); oscillator.start(); setTimeout(() => oscillator.stop(), 140); } catch (error) {} };
            const toast = (message) => { if ('Notification' in window && Notification.permission === 'granted') { new Notification('<?php echo e(SITE_NAME); ?>', { body: message, icon: 'img/logo.jpeg' }); } sound(); };
            const escapeHtml = (value) => String(value == null ? '' : value).replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }[char]));
            const normalizeDish = (source) => ({
                id: String(source.id || (source.dataset && source.dataset.id) || ''),
                name: source.name || (source.dataset && source.dataset.name) || '',
                description: source.description || (source.dataset && source.dataset.description) || '',
                price: Number(source.price || (source.dataset && source.dataset.price) || 0),
                restaurant: source.restaurant_name || source.restaurant || (source.dataset && source.dataset.restaurant) || '',
                restaurantId: String(source.restaurant_id || source.restaurantId || (source.dataset && source.dataset.restaurantId) || ''),
                prep: Number(source.preparation_time_minutes || source.prep || (source.dataset && source.dataset.prep) || 0),
                deliveryFee: Number(source.delivery_fee || source.deliveryFee || (source.dataset && source.dataset.deliveryFee) || 0),
                imageUrl: source.image_url || source.imageUrl || (source.dataset && source.dataset.imageUrl) || '',
                imageEmoji: source.image_emoji || source.imageEmoji || (source.dataset && source.dataset.imageEmoji) || ''
            });
            const addToCart = (dish, qty = 1) => {
                const id = String(dish.id);
                const restaurantId = String(dish.restaurantId || '');
                const first = cart.values().next().value;
                if (first && first.restaurantId !== restaurantId) {
                    alert('Please checkout or clear the current cart before adding products from another restaurant.');
                    return false;
                }
                const current = cart.get(id) || { id, name: dish.name, price: Number(dish.price), restaurant: dish.restaurant, restaurantId, qty: 0 };
                current.qty += Math.max(1, Number(qty || 1));
                cart.set(id, current);
                renderCart();
                toast(`${current.name} added to cart`);
                return true;
            };
            const updateDishDetailTotals = () => {
                if (!activeDish) return;
                document.getElementById('dishQtyValue').textContent = activeDishQty;
                document.getElementById('dishDetailQuantity').textContent = activeDishQty;
                document.getElementById('dishDetailTotal').textContent = money(activeDish.price * activeDishQty);
            };
            const openDishDetail = (dishInput) => {
                activeDish = normalizeDish(dishInput);
                activeDishQty = 1;
                document.getElementById('dishDetailTitle').textContent = activeDish.name;
                document.getElementById('dishDetailText').textContent = `${activeDish.description || activeDish.restaurant} - ${activeDish.restaurant} - ${activeDish.prep || 20} min prep`;
                document.getElementById('dishDetailPrice').textContent = money(activeDish.price);
                document.getElementById('dishDetailMedia').innerHTML = activeDish.imageUrl ? `<img src="${escapeHtml(activeDish.imageUrl)}" alt="${escapeHtml(activeDish.name)}">` : `<div class="image-fallback">${escapeHtml(activeDish.imageEmoji || activeDish.name.slice(0, 1).toUpperCase())}</div>`;
                updateDishDetailTotals();
                dishModal.classList.add('open');
                dishModal.setAttribute('aria-hidden', 'false');
            };
            const renderDishCard = (dish) => {
                const normalized = normalizeDish(dish);
                const card = document.createElement('article');
                card.className = 'dish-card js-dish-card';
                Object.entries({
                    id: normalized.id,
                    name: normalized.name,
                    description: normalized.description,
                    price: normalized.price,
                    restaurant: normalized.restaurant,
                    restaurantId: normalized.restaurantId,
                    prep: normalized.prep,
                    deliveryFee: normalized.deliveryFee,
                    imageUrl: normalized.imageUrl,
                    imageEmoji: normalized.imageEmoji
                }).forEach(([key, value]) => { card.dataset[key] = value; });
                card.tabIndex = 0;
                card.setAttribute('role', 'button');
                card.innerHTML = `<div class="dish-media">${normalized.imageUrl ? `<img src="${escapeHtml(normalized.imageUrl)}" alt="${escapeHtml(normalized.name)}">` : escapeHtml(normalized.imageEmoji || normalized.name.slice(0, 1).toUpperCase())}</div><h3>${escapeHtml(normalized.name)}</h3><p>${escapeHtml(normalized.description || normalized.restaurant)}</p><div class="meta"><span><i class="bi bi-shop"></i> ${escapeHtml(normalized.restaurant)}</span><span><i class="bi bi-clock"></i> ${normalized.prep || 20} min prep</span></div><div class="dish-foot"><span class="price">${money(normalized.price)}</span><button class="add js-open-dish" type="button"><i class="bi bi-plus-lg"></i> Add</button></div>`;
                return card;
            };
            const openRestaurantMenu = (restaurantId, restaurantName, cuisine) => {
                const catalog = window.Storefront.menuCatalog || {};
                const dishes = catalog[String(restaurantId)] || catalog[Number(restaurantId)] || [];
                document.getElementById('restaurantMenuTitle').textContent = restaurantName || 'Restaurant dishes';
                document.getElementById('restaurantMenuMeta').textContent = dishes.length ? `${dishes.length} available dishes${cuisine ? ` - ${cuisine}` : ''}` : 'No available dishes for this restaurant yet.';
                restaurantMenuGrid.innerHTML = '';
                dishes.forEach((dish) => restaurantMenuGrid.appendChild(renderDishCard(dish)));
                if (!dishes.length) restaurantMenuGrid.innerHTML = '<div class="empty">No dishes are available for this hotel right now.</div>';
                restaurantMenuPanel.classList.add('open');
                restaurantMenuPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });
            };
            const renderCart = () => { let count = 0; let total = 0; const first = cart.values().next().value; cartList.innerHTML = ''; cartRestaurant.textContent = first ? `Ordering from ${first.restaurant}` : ''; if (cart.size === 0) cartList.innerHTML = '<div class="empty">Your cart is empty. Add products from popular dishes.</div>'; cart.forEach((item, id) => { count += item.qty; total += item.qty * Number(item.price || 0); const row = document.createElement('div'); row.className = 'cart-row'; row.innerHTML = `<div><strong>${escapeHtml(item.name)}</strong><div class="meta"><span><i class="bi bi-shop"></i> ${escapeHtml(item.restaurant)}</span></div><div class="qty" aria-label="Quantity controls"><button class="cart-qty-btn" type="button" data-cart-minus="${id}" aria-label="Decrease ${escapeHtml(item.name)}"><i class="bi bi-dash-lg"></i></button><strong>${item.qty}</strong><button class="cart-qty-btn" type="button" data-cart-plus="${id}" aria-label="Increase ${escapeHtml(item.name)}"><i class="bi bi-plus-lg"></i></button><button class="cart-qty-btn cart-remove-btn" type="button" data-cart-remove="${id}" title="Remove" aria-label="Remove ${escapeHtml(item.name)}"><i class="bi bi-trash"></i></button></div></div><strong>${money(item.qty * Number(item.price || 0))}</strong>`; cartList.appendChild(row); }); cartCount.textContent = count; cartTotal.textContent = money(total); checkoutBtn.disabled = cart.size === 0; persistCart(); };
            document.addEventListener('click', (event) => {
                const menuButton = event.target.closest('.js-view-menu');
                if (menuButton) {
                    event.stopPropagation();
                    openRestaurantMenu(menuButton.dataset.restaurantId, menuButton.dataset.restaurantName, menuButton.dataset.restaurantCuisine);
                    return;
                }
                const restaurantCard = event.target.closest('.js-restaurant-card');
                if (restaurantCard && !event.target.closest('button, a')) {
                    openRestaurantMenu(restaurantCard.dataset.restaurantId, restaurantCard.dataset.restaurantName, restaurantCard.dataset.restaurantCuisine);
                    return;
                }
                const dishCard = event.target.closest('.js-dish-card');
                if (dishCard && !event.target.closest('.js-add-cart')) {
                    openDishDetail(dishCard.dataset);
                }
            });
            document.addEventListener('keydown', (event) => {
                if (event.key !== 'Enter' && event.key !== ' ') return;
                const card = event.target.closest('.js-restaurant-card, .js-dish-card');
                if (!card) return;
                event.preventDefault();
                if (card.classList.contains('js-restaurant-card')) openRestaurantMenu(card.dataset.restaurantId, card.dataset.restaurantName, card.dataset.restaurantCuisine);
                if (card.classList.contains('js-dish-card')) openDishDetail(card.dataset);
            });
            document.getElementById('closeRestaurantMenu').addEventListener('click', () => restaurantMenuPanel.classList.remove('open'));
            document.getElementById('dishQtyMinus').addEventListener('click', () => { activeDishQty = Math.max(1, activeDishQty - 1); updateDishDetailTotals(); });
            document.getElementById('dishQtyPlus').addEventListener('click', () => { activeDishQty = Math.min(20, activeDishQty + 1); updateDishDetailTotals(); });
            document.getElementById('addDishDetail').addEventListener('click', () => { if (activeDish && addToCart(activeDish, activeDishQty)) { dishModal.classList.remove('open'); dishModal.setAttribute('aria-hidden', 'true'); } });
            document.getElementById('closeDishDetail').addEventListener('click', () => { dishModal.classList.remove('open'); dishModal.setAttribute('aria-hidden', 'true'); });
            cartList.addEventListener('click', (event) => { const plus = event.target.closest('[data-cart-plus]'); const minus = event.target.closest('[data-cart-minus]'); const remove = event.target.closest('[data-cart-remove]'); const id = (plus && plus.dataset.cartPlus) || (minus && minus.dataset.cartMinus) || (remove && remove.dataset.cartRemove); if (!id || !cart.has(id)) return; if (remove) { cart.delete(id); renderCart(); return; } const item = cart.get(id); item.qty += plus ? 1 : -1; if (item.qty <= 0) cart.delete(id); renderCart(); });
            document.getElementById('clearCartBtn').addEventListener('click', () => { cart.clear(); renderCart(); });
            cartBtn.addEventListener('click', () => { cartDrawer.classList.add('open'); document.body.classList.add('drawer-open'); });
            document.getElementById('closeCart').addEventListener('click', () => { cartDrawer.classList.remove('open'); document.body.classList.remove('drawer-open'); });
            cartDrawer.addEventListener('click', (event) => { if (event.target === cartDrawer) { cartDrawer.classList.remove('open'); document.body.classList.remove('drawer-open'); } });
            checkoutBtn.addEventListener('click', async () => {
                const items = [...cart.values()];
                const amount = items.reduce((sum, item) => sum + item.qty * Number(item.price || 0), 0);
                if (amount <= 0) return;
                if (!window.Storefront.razorpayKey) {
                    alert('Razorpay public key is not configured yet.');
                    return;
                }
                const customer = {
                    name: document.getElementById('checkoutName').value.trim(),
                    phone: document.getElementById('checkoutPhone').value.trim(),
                    address: document.getElementById('checkoutAddress').value.trim(),
                    instructions: document.getElementById('checkoutInstructions').value.trim(),
                    lat: new URL(location.href).searchParams.get('lat') || 0,
                    lng: new URL(location.href).searchParams.get('lng') || 0
                };
                if (!customer.name || customer.phone.replace(/\D+/g, '').length < 10 || !customer.address) {
                    alert('Please enter name, valid phone, and delivery address.');
                    return;
                }
                let recaptchaToken = '';
                if (window.Storefront.recaptchaSiteKey && window.grecaptcha) {
                    recaptchaToken = await grecaptcha.execute(window.Storefront.recaptchaSiteKey, { action: 'checkout' });
                }
                checkoutBtn.disabled = true;
                const response = await fetch('create_razorpay_order.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': window.Storefront.csrfToken },
                    body: JSON.stringify({ items, customer, recaptcha_token: recaptchaToken })
                });
                const payload = await response.json();
                checkoutBtn.disabled = false;
                if (payload.status !== 'success') {
                    alert(payload.message || 'Could not start payment.');
                    return;
                }
                const rzp = new Razorpay({
                    key: window.Storefront.razorpayKey,
                    amount: payload.amount,
                    currency: payload.currency,
                    name: '<?php echo e(SITE_NAME); ?>',
                    description: `Order ${payload.public_id || ''}`,
                    order_id: payload.order_id,
                    handler: async (payment) => {
                        const verifyResponse = await fetch('verify_payment.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': window.Storefront.csrfToken },
                            body: JSON.stringify({
                                local_order_id: payload.local_order_id,
                                razorpay_order_id: payment.razorpay_order_id,
                                razorpay_payment_id: payment.razorpay_payment_id,
                                razorpay_signature: payment.razorpay_signature
                            })
                        });
                        const verified = await verifyResponse.json();
                        if (verified.status !== 'success') {
                            alert(verified.message || 'Payment completed but invoice verification failed.');
                            return;
                        }
                        activeOrderId = String(payload.local_order_id || '');
                        if (activeOrderId) localStorage.setItem(orderKey, activeOrderId);
                        activeOrderPhone = customer.phone.replace(/\D+/g, '');
                        if (activeOrderPhone) localStorage.setItem(orderPhoneKey, activeOrderPhone);
                        cart.clear();
                        renderCart();
                        toast('Payment completed. GST invoice is ready.');
                        cartDrawer.classList.remove('open');
                        document.body.classList.remove('drawer-open');
                        revealTracking(true);
                        window.open(verified.invoice_url, '_blank', 'noopener');
                    },
                    theme: { color: '#ff5722' }
                });
                rzp.open();
            });
            const useLocation = () => { if (!navigator.geolocation) { alert('GPS location is not available on this device.'); return; } navigator.geolocation.getCurrentPosition((position) => { const url = new URL(window.location.href); url.searchParams.set('lat', position.coords.latitude.toFixed(7)); url.searchParams.set('lng', position.coords.longitude.toFixed(7)); window.location.href = url.toString(); }, () => alert('Location permission was denied or unavailable.'), { enableHighAccuracy: true, timeout: 10000 }); };
            document.getElementById('locationBtn').addEventListener('click', useLocation);
            document.getElementById('heroLocationBtn').addEventListener('click', useLocation);
            document.getElementById('goTopBtn').addEventListener('click', () => window.scrollTo({ top: 0, behavior: 'smooth' }));
            const slides = [...document.querySelectorAll('.slide')];
            const dots = document.getElementById('slideDots');
            let slideIndex = 0;
            const showSlide = (index) => { slideIndex = (index + slides.length) % slides.length; slides.forEach((slide, i) => slide.classList.toggle('active', i === slideIndex)); dots.querySelectorAll('button').forEach((dot, i) => dot.classList.toggle('active', i === slideIndex)); };
            slides.forEach((_, index) => { const dot = document.createElement('button'); dot.type = 'button'; dot.addEventListener('click', () => showSlide(index)); dots.appendChild(dot); });
            if (slides.length > 0) { showSlide(0); setInterval(() => showSlide(slideIndex + 1), 4500); }
            const offerModal = document.getElementById('offerModal');
            const openOffer = () => { const offers = window.Storefront.offers || []; if (offers.length > 0) { const offer = offers[Math.floor(Math.random() * offers.length)]; document.getElementById('offerTitle').textContent = offer.name || 'Today offer'; document.getElementById('offerText').textContent = `${offer.cuisine || 'Fresh food'} starts at ${money(offer.starting_price || 0)} with fast delivery.`; document.getElementById('offerMedia').innerHTML = offer.image_url ? `<img src="${offer.image_url}" alt="${offer.name}">` : ''; } offerModal.classList.add('open'); offerModal.setAttribute('aria-hidden', 'false'); };
            document.getElementById('offerBtn').addEventListener('click', openOffer);
            document.getElementById('openOfferBtn').addEventListener('click', openOffer);
            document.getElementById('closeOffer').addEventListener('click', () => { offerModal.classList.remove('open'); offerModal.setAttribute('aria-hidden', 'true'); });
            setTimeout(openOffer, 2500);
            const loadNotifications = async () => { try { const response = await fetch('notifications_feed.php'); const payload = await response.json(); const notices = payload.notifications || []; notifyCount.textContent = notices.length; noticeList.innerHTML = notices.length ? '' : '<div class="empty">No notifications yet.</div>'; notices.forEach((notice) => { const item = document.createElement('div'); item.className = 'notice'; item.innerHTML = `<strong>${escapeHtml(notice.title)}</strong><span>${escapeHtml(notice.body)}</span>`; noticeList.appendChild(item); }); if (notices.length > noticesSeen && noticesSeen !== 0) toast((notices[0] && notices[0].title) || 'New notification'); noticesSeen = notices.length; } catch (error) {} };
            document.getElementById('notifyBtn').addEventListener('click', () => { notifyPanel.classList.toggle('open'); loadNotifications(); });
            document.getElementById('enableNotifications').addEventListener('click', async () => { if ('Notification' in window) { await Notification.requestPermission(); toast('Notifications enabled with sound'); } });
            const loginUnavailableButton = document.getElementById('loginUnavailableBtn');
            if (loginUnavailableButton) loginUnavailableButton.addEventListener('click', () => alert('Google login is not configured yet. You can still browse dishes and checkout as a guest.'));
            if (window.Storefront.loginUnavailable) {
                setTimeout(() => alert('Google login is not configured yet. You can still browse dishes and checkout as a guest.'), 250);
            }
            const reviewModal = document.getElementById('reviewModal');
            const reviewTitle = document.getElementById('reviewTitle');
            const reviewsList = document.getElementById('reviewsList');
            const reviewText = document.getElementById('reviewText');
            const reviewStars = document.getElementById('reviewStars');
            let activeRestaurantId = 0;
            let activeRating = 5;
            const paintStars = () => reviewStars.querySelectorAll('button').forEach((button) => button.classList.toggle('active', Number(button.dataset.star) <= activeRating));
            const openReview = async (button) => {
                activeRestaurantId = Number(button.dataset.restaurantId || 0);
                activeRating = 5;
                reviewText.value = '';
                reviewTitle.textContent = button.dataset.restaurantName || 'Rate hotel';
                paintStars();
                reviewModal.classList.add('open');
                reviewModal.setAttribute('aria-hidden', 'false');
                reviewsList.innerHTML = '<div class="empty">Loading reviews...</div>';
                try {
                    const response = await fetch(`reviews.php?restaurant_id=${activeRestaurantId}`);
                    const payload = await response.json();
                    const reviews = payload.reviews || [];
                    reviewsList.innerHTML = reviews.length ? '' : '<div class="empty">No reviews yet. Be the first to review.</div>';
                    reviews.forEach((review) => {
                        const item = document.createElement('div');
                        item.className = 'notice';
                        item.innerHTML = `<strong>${'★'.repeat(Number(review.rating || 0))} ${review.name || 'Customer'}</strong><span>${review.review_text || 'Rated this hotel'}</span>`;
                        reviewsList.appendChild(item);
                    });
                } catch (error) {
                    reviewsList.innerHTML = '<div class="empty">Reviews could not be loaded.</div>';
                }
            };
            document.querySelectorAll('.js-review, .js-load-reviews').forEach((button) => button.addEventListener('click', () => openReview(button)));
            reviewStars.addEventListener('click', (event) => {
                const button = event.target.closest('[data-star]');
                if (!button) return;
                activeRating = Number(button.dataset.star);
                paintStars();
            });
            document.getElementById('closeReview').addEventListener('click', () => {
                reviewModal.classList.remove('open');
                reviewModal.setAttribute('aria-hidden', 'true');
            });
            const submitReviewButton = document.getElementById('submitReview');
            if (submitReviewButton) submitReviewButton.addEventListener('click', async () => {
                if (!window.Storefront.loggedIn) {
                    if (window.Storefront.googleLoginConfigured) {
                        window.location.href = 'google_login.php?action=start';
                    } else {
                        alert('Google login is not configured yet.');
                    }
                    return;
                }
                const response = await fetch('reviews.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': window.Storefront.csrfToken },
                    body: JSON.stringify({ restaurant_id: activeRestaurantId, rating: activeRating, review_text: reviewText.value })
                });
                const payload = await response.json();
                if (payload.status !== 'success') {
                    alert(payload.message || 'Review could not be submitted.');
                    return;
                }
                toast('Review submitted for moderation');
                reviewModal.classList.remove('open');
            });
            const trackingPanel = document.getElementById('liveOrderTracking');
            const renderTracking = (payload) => {
                if (!payload || payload.status !== 'success' || !payload.order) {
                    document.getElementById('trackingSubtitle').textContent = (payload && payload.message) || 'No active order is ready to track yet.';
                    document.getElementById('chatLog').innerHTML = '<div class="empty">Tracking starts after a paid order is created.</div>';
                    return;
                }
                const order = payload.order;
                const actor = payload.actor || {};
                document.getElementById('trackingSubtitle').textContent = `Order ${order.public_id || '#' + order.id} - ${order.restaurant_name || 'Restaurant'}`;
                document.getElementById('trackingStatus').textContent = String(order.status || 'Pending').replace(/_/g, ' ');
                document.getElementById('trackingDistance').textContent = payload.distance_km ? `${Number(payload.distance_km).toFixed(1)} km` : '--';
                document.getElementById('trackingEta').textContent = payload.eta_minutes ? `${payload.eta_minutes} min` : '--';
                document.getElementById('trackingPartner').textContent = actor.name || 'Restaurant';
                document.getElementById('trackingAddress').textContent = actor.note || '';
                document.getElementById('trackingHint').textContent = payload.hint || '';
                document.getElementById('trackingMovingPin').innerHTML = actor.type === 'restaurant' ? '<i class="bi bi-shop"></i>' : '<i class="bi bi-bicycle"></i>';
                document.getElementById('chatMessage').placeholder = actor.type === 'restaurant' ? 'Message restaurant before pickup' : 'Message your rider';
                const messages = payload.messages || [];
                document.getElementById('chatLog').innerHTML = messages.length ? '' : '<div class="empty">No messages yet. Start the conversation here.</div>';
                messages.forEach((message) => {
                    const bubble = document.createElement('div');
                    bubble.className = `chat-message ${message.sender_role === 'CUSTOMER' ? 'customer' : ''}`;
                    bubble.textContent = message.message;
                    document.getElementById('chatLog').appendChild(bubble);
                });
                document.getElementById('chatLog').scrollTop = document.getElementById('chatLog').scrollHeight;
            };
            const loadTracking = async () => {
                if (!activeOrderId) return;
                try {
                    const phoneQuery = activeOrderPhone ? `&phone=${encodeURIComponent(activeOrderPhone)}` : '';
                    const response = await fetch(`order_tracking.php?order_id=${encodeURIComponent(activeOrderId)}${phoneQuery}`);
                    renderTracking(await response.json());
                } catch (error) {
                    renderTracking({ status: 'error', message: 'Live tracking could not be loaded.' });
                }
            };
            const revealTracking = (force = false) => {
                if (!activeOrderId) return;
                const scrolled = (window.scrollY + window.innerHeight) / Math.max(document.documentElement.scrollHeight, 1);
                if (force || scrolled >= 0.5) {
                    trackingPanel.classList.add('open');
                    loadTracking();
                }
            };
            document.getElementById('refreshTracking').addEventListener('click', () => revealTracking(true));
            document.getElementById('chatForm').addEventListener('submit', async (event) => {
                event.preventDefault();
                const input = document.getElementById('chatMessage');
                const message = input.value.trim();
                if (!activeOrderId || !message) return;
                input.value = '';
                try {
                    const response = await fetch('order_tracking.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': window.Storefront.csrfToken },
                        body: JSON.stringify({ order_id: activeOrderId, phone: activeOrderPhone, message })
                    });
                    renderTracking(await response.json());
                } catch (error) {
                    alert('Message could not be sent right now.');
                }
            });
            window.addEventListener('scroll', () => revealTracking(false), { passive: true });
            setInterval(() => { if (trackingPanel.classList.contains('open')) loadTracking(); }, 15000);
            revealTracking(false);
            loadNotifications();
            setInterval(loadNotifications, 30000);
            renderCart();
        })();
    </script>
</body>
</html>
