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

// Initialize database connection
$database = new Database();
$db = $database->getConnection();

// Get restaurant settings with proper error handling
$settings = [];
try {
    $query = "SELECT * FROM restaurant_settings WHERE id = 1";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $settings = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $settings = [
        'restaurant_name' => 'XYz GoalGPT Restaurant',
        'contact_number' => '+911234567890',
        'delivery_charge' => 40.000,
        'min_order_amount' => 100.000,
        'address' => 'Muharraq, Bahrain',
        'country' => 'Bahrain',
        'currency' => 'BHD',
        'timezone' => 'Asia/Bahrain',
        'logo_url' => '',
        'favicon_url' => '',
        'website_theme' => 'default',
        'website_enabled' => 1,
        'website_maintenance_mode' => 0,
        'website_maintenance_message' => ''
    ];
}

// Check if website is enabled
if (!($settings['website_enabled'] ?? 1)) {
    die('<div style="text-align:center; padding:100px; font-family:Arial, sans-serif;"><h2>Website Disabled</h2><p>Our website is currently undergoing maintenance. Please contact us via WhatsApp for orders.</p></div>');
}

// Check if maintenance mode is enabled
if ($settings['website_maintenance_mode'] ?? 0) {
    $message = $settings['website_maintenance_message'] ?? 'We are currently upgrading our system. Please try again later or contact us via WhatsApp.';
    die('<div style="text-align:center; padding:50px; font-family:Arial, sans-serif;"><h2>🚧 Maintenance Mode</h2><p>' . htmlspecialchars($message) . '</p></div>');
}

// Parse working hours
$workingHours = [];
if (!empty($settings['working_hours'])) {
    try {
        $workingHours = json_decode($settings['working_hours'], true);
    } catch (Exception $e) {
        $workingHours = [];
    }
}

if (empty($workingHours)) {
    $workingHours = [
        'sunday' => ['open' => '10:00', 'close' => '22:00', 'enabled' => true],
        'monday' => ['open' => '10:00', 'close' => '22:00', 'enabled' => true],
        'tuesday' => ['open' => '10:00', 'close' => '22:00', 'enabled' => true],
        'wednesday' => ['open' => '10:00', 'close' => '22:00', 'enabled' => true],
        'thursday' => ['open' => '10:00', 'close' => '22:00', 'enabled' => true],
        'friday' => ['open' => '12:00', 'close' => '23:00', 'enabled' => true],
        'saturday' => ['open' => '10:00', 'close' => '23:00', 'enabled' => true]
    ];
}

// Get menu categories
$query = "SELECT DISTINCT category FROM menu_items WHERE availability = 1 ORDER BY category";
$stmt = $db->prepare($query);
$stmt->execute();
$categories = $stmt->fetchAll(PDO::FETCH_COLUMN);

// Get all menu items
$query = "SELECT * FROM menu_items WHERE availability = 1 ORDER BY category, display_order, name";
$stmt = $db->prepare($query);
$stmt->execute();
$menuItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Group by category and decode options
$menuByCategory = [];
foreach ($menuItems as $item) {
    $options = [];
    if (!empty($item['options'])) {
        try {
            $decoded = json_decode($item['options'], true);
            if (is_array($decoded)) {
                $options = $decoded;
            }
        } catch (Exception $e) {
            $options = [];
        }
    }
    $item['options'] = $options;
    
    $menuByCategory[$item['category']][] = $item;
}

// Get delivery areas
$query = "SELECT * FROM delivery_areas WHERE is_active = 1 ORDER BY area_name";
$stmt = $db->prepare($query);
$stmt->execute();
$deliveryAreas = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Initialize cart
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// Apply theme colors
$theme = $settings['website_theme'] ?? 'default';
$theme_colors = [
    'default' => ['primary' => '#FF6B35', 'primary-dark' => '#E55A2B', 'primary-light' => '#FF8C5A'],
    'blue' => ['primary' => '#3498db', 'primary-dark' => '#2980b9', 'primary-light' => '#5dade2'],
    'green' => ['primary' => '#27ae60', 'primary-dark' => '#219653', 'primary-light' => '#52c674'],
    'dark' => ['primary' => '#2c3e50', 'primary-dark' => '#1a252f', 'primary-light' => '#34495e'],
    'purple' => ['primary' => '#9b59b6', 'primary-dark' => '#8e44ad', 'primary-light' => '#af7ac5']
];

$colors = $theme_colors[$theme] ?? $theme_colors['default'];

// Format price based on currency
function formatPrice($price, $currency = 'BHD') {
    $symbols = [
        'BHD' => '.د.ب',
        'USD' => '$',
        'EUR' => '€',
        'GBP' => '£',
        'INR' => '₹',
        'SAR' => 'ر.س',
        'QAR' => 'ر.ق',
        'AED' => 'د.إ',
        'PKR' => '₨'
    ];
    
    $symbol = $symbols[$currency] ?? $currency . ' ';
    $decimals = in_array($currency, ['BHD', 'USD', 'EUR', 'GBP', 'PKR']) ? 2 : 2;
    
    return $symbol . number_format(floatval($price), $decimals);
}

// Function to get image URL
function getItemImage($item) {
    if (empty($item['image'])) {
        return null;
    }
    
    if (strpos($item['image'], 'http') === 0) {
        return $item['image'];
    }
    
    $upload_path = $item['image'];
    if (file_exists($upload_path)) {
        return $upload_path;
    }
    
    return $item['image'];
}

// Function to get emoji for category
function getCategoryEmoji($category) {
    $category = strtolower($category);
    $emojis = [
        'pizza' => '🍕',
        'appetizers' => '🥗',
        'salads' => '🥗',
        'beverages' => '🥤',
        'desserts' => '🍰',
        'burgers' => '🍔',
        'pasta' => '🍝',
        'seafood' => '🐟',
        'chicken' => '🍗',
        'vegetarian' => '🥦'
    ];
    
    return $emojis[$category] ?? '🍽️';
}

// API Key for order processing
$api_key = 'restaurant_order_2024';

// Check for order success in URL
$order_success = isset($_GET['order_success']) && $_GET['order_success'] == 'true';
$order_number = $_GET['order_number'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($settings['restaurant_name']); ?> - Order Online • Fast Delivery</title>
    
    <!-- Favicon -->
    <?php if (!empty($settings['favicon_url'])): ?>
    <link rel="icon" href="<?php echo htmlspecialchars($settings['favicon_url']); ?>" type="image/x-icon">
    <?php endif; ?>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&family=Playfair+Display:wght@700;800&display=swap" rel="stylesheet">
    
    <!-- HTML2Canvas for receipt generation -->
    <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    
    <style>
        /* ============================================
           MOBILE FIRST DESIGN WITH PERFECT ALIGNMENT
           ============================================ */

        /* ===== CSS RESET ===== */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }

        :root {
            /* Theme Colors */
            --primary: <?php echo $colors['primary']; ?>;
            --primary-dark: <?php echo $colors['primary-dark']; ?>;
            --primary-light: <?php echo $colors['primary-light']; ?>;
            --secondary: #1A1A2E;
            --accent: #0F3460;
            --success: #25D366;
            --success-dark: #128C7E;
            --warning: #FDCB6E;
            --danger: #D63031;
            --light: #FFFFFF;
            --dark: #121212;
            --gray-100: #F8F9FA;
            --gray-200: #E9ECEF;
            --gray-300: #DEE2E6;
            --gray-400: #CED4DA;
            --gray-500: #ADB5BD;
            --gray-600: #6C757D;
            --gray-700: #495057;
            --gray-800: #343A40;
            --gray-900: #212529;
            
            /* Gradients */
            --gradient-primary: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
            --gradient-dark: linear-gradient(135deg, #1A1A2E 0%, #16213E 100%);
            --gradient-whatsapp: linear-gradient(135deg, #25D366 0%, #128C7E 100%);
            
            /* Typography */
            --font-heading: 'Playfair Display', serif;
            --font-body: 'Poppins', sans-serif;
            
            /* Spacing - Mobile First */
            --space-xs: 0.5rem;
            --space-sm: 0.75rem;
            --space-md: 1rem;
            --space-lg: 1.5rem;
            --space-xl: 2rem;
            --space-xxl: 3rem;
            
            /* Border Radius */
            --radius-sm: 6px;
            --radius-md: 10px;
            --radius-lg: 14px;
            --radius-xl: 18px;
            --radius-full: 9999px;
            
            /* Shadows */
            --shadow-sm: 0 1px 3px rgba(0,0,0,0.12);
            --shadow-md: 0 2px 8px rgba(0,0,0,0.15);
            --shadow-lg: 0 4px 16px rgba(0,0,0,0.2);
            --shadow-xl: 0 8px 24px rgba(0,0,0,0.25);
            
            /* Transitions */
            --transition-fast: 0.2s ease;
            --transition-normal: 0.3s ease;
            --transition-slow: 0.5s ease;
        }

        html {
            font-size: 14px;
            scroll-behavior: smooth;
            -webkit-text-size-adjust: 100%;
        }

        body {
            font-family: var(--font-body);
            font-size: 1rem;
            line-height: 1.6;
            color: var(--secondary);
            background: var(--light);
            overflow-x: hidden;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }

        /* Container - Mobile First */
        .container {
            width: 100%;
            padding: 0 var(--space-md);
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        /* ===== TYPOGRAPHY - MOBILE OPTIMIZED ===== */
        h1, h2, h3, h4, h5, h6 {
            font-family: var(--font-heading);
            font-weight: 700;
            line-height: 1.3;
            margin-bottom: var(--space-sm);
            text-align: center;
            width: 100%;
        }

        h1 { font-size: 1.75rem; }
        h2 { font-size: 1.5rem; }
        h3 { font-size: 1.25rem; }
        h4 { font-size: 1.125rem; }
        h5 { font-size: 1rem; }
        h6 { font-size: 0.875rem; }

        p {
            margin-bottom: var(--space-sm);
            font-size: 0.9375rem;
            text-align: center;
            width: 100%;
            max-width: 100%;
            word-wrap: break-word;
        }

        .section-title {
            text-align: center;
            margin-bottom: var(--space-lg);
            position: relative;
            padding-bottom: var(--space-md);
            width: 100%;
        }

        .section-title::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60px;
            height: 3px;
            background: var(--gradient-primary);
            border-radius: 1.5px;
        }

        /* ===== BUTTONS - CENTERED MOBILE ===== */
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            padding: 0.875rem 1.5rem;
            border: none;
            border-radius: var(--radius-md);
            font-family: var(--font-body);
            font-size: 0.9375rem;
            font-weight: 600;
            text-decoration: none;
            cursor: pointer;
            transition: all var(--transition-normal);
            -webkit-appearance: none;
            touch-action: manipulation;
            min-height: 44px;
            min-width: 44px;
            width: 100%;
            max-width: 300px;
            margin: 0 auto;
        }

        .btn-primary {
            background: var(--gradient-primary);
            color: var(--light);
            box-shadow: var(--shadow-md);
        }

        .btn-primary:hover, .btn-primary:active {
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }

        .btn-outline {
            background: transparent;
            color: var(--primary);
            border: 2px solid var(--primary);
        }

        .btn-outline:hover, .btn-outline:active {
            background: var(--primary);
            color: var(--light);
        }

        .btn-success {
            background: var(--gradient-whatsapp);
            color: var(--light);
        }

        .btn-block {
            width: 100%;
            display: flex;
        }

        .btn-lg {
            padding: 1rem 2rem;
            font-size: 1rem;
        }

        .btn-sm {
            padding: 0.625rem 1rem;
            font-size: 0.875rem;
            min-height: 36px;
            min-width: 36px;
        }

        /* ===== NAVIGATION - MOBILE FRIENDLY ===== */
        .navbar {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(10px);
            z-index: 1000;
            box-shadow: var(--shadow-sm);
            padding: var(--space-sm) 0;
        }

        .nav-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            padding: 0 var(--space-md);
        }

        .logo {
            display: flex;
            align-items: center;
            gap: var(--space-sm);
            text-decoration: none;
            max-width: 200px;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: var(--gradient-primary);
            border-radius: var(--radius-sm);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--light);
            font-size: 1.25rem;
            overflow: hidden;
            flex-shrink: 0;
        }

        .logo-icon img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .logo-text {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            overflow: hidden;
        }

        .logo-text h1 {
            font-size: 1rem;
            margin: 0;
            text-align: left;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 150px;
        }

        .logo-text span {
            font-size: 0.7rem;
            color: var(--gray-600);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 150px;
        }

        .nav-menu {
            position: fixed;
            top: 60px;
            left: 0;
            width: 100%;
            background: var(--light);
            padding: var(--space-md);
            box-shadow: var(--shadow-lg);
            transform: translateY(-100%);
            opacity: 0;
            visibility: hidden;
            transition: all var(--transition-normal);
            z-index: 999;
        }

        .nav-menu.show {
            transform: translateY(0);
            opacity: 1;
            visibility: visible;
        }

        .nav-links {
            display: flex;
            flex-direction: column;
            gap: var(--space-sm);
            align-items: center;
        }

        .nav-link {
            color: var(--secondary);
            text-decoration: none;
            font-weight: 500;
            padding: var(--space-sm);
            border-radius: var(--radius-sm);
            transition: all var(--transition-normal);
            display: flex;
            align-items: center;
            gap: var(--space-sm);
            width: 100%;
            justify-content: center;
        }

        .nav-link:hover, .nav-link.active {
            background: var(--gray-100);
            color: var(--primary);
        }

        .nav-actions {
            display: flex;
            align-items: center;
            gap: var(--space-sm);
        }

        .cart-btn {
            position: relative;
            background: none;
            border: none;
            padding: var(--space-xs);
            cursor: pointer;
            font-size: 1.25rem;
            color: var(--secondary);
        }

        .cart-count {
            position: absolute;
            top: -5px;
            right: -5px;
            background: var(--danger);
            color: var(--light);
            font-size: 0.75rem;
            width: 18px;
            height: 18px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
        }

        .mobile-menu-btn {
            background: none;
            border: none;
            font-size: 1.5rem;
            color: var(--secondary);
            cursor: pointer;
            padding: var(--space-xs);
        }

        /* ===== HERO SECTION - MOBILE CENTERED ===== */
        .hero {
            min-height: 100vh;
            background: linear-gradient(rgba(26, 26, 46, 0.9), rgba(15, 52, 96, 0.95));
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 5rem var(--space-md) var(--space-xl);
            margin-top: 60px;
            position: relative;
            text-align: center;
        }

        .hero::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80') center/cover;
            z-index: -1;
            opacity: 0.3;
        }

        .hero-content {
            color: var(--light);
            text-align: center;
            width: 100%;
            z-index: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .hero-title {
            font-size: 2rem;
            margin-bottom: var(--space-md);
            color: var(--light);
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
            max-width: 100%;
        }

        .hero-subtitle {
            font-size: 1rem;
            color: rgba(255,255,255,0.9);
            margin-bottom: var(--space-xl);
            text-shadow: 0 1px 2px rgba(0,0,0,0.3);
            max-width: 600px;
        }

        .hero-buttons {
            display: flex;
            flex-direction: column;
            gap: var(--space-sm);
            margin-bottom: var(--space-xl);
            width: 100%;
            align-items: center;
        }

        .hero-features {
            display: grid;
            grid-template-columns: 1fr;
            gap: var(--space-md);
            width: 100%;
            max-width: 400px;
        }

        .feature-card {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: var(--radius-lg);
            padding: var(--space-md);
            text-align: center;
        }

        .feature-icon {
            width: 50px;
            height: 50px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto var(--space-sm);
            color: var(--primary-light);
            font-size: 1.25rem;
        }

        /* ===== TRACK ORDER - MOBILE CENTERED ===== */
        .track-section {
            padding: var(--space-xl) var(--space-md);
            background: var(--gray-100);
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
        }

        .track-card {
            background: var(--light);
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-md);
            overflow: hidden;
            width: 100%;
            max-width: 600px;
        }

        .track-header {
            background: var(--gradient-primary);
            padding: var(--space-lg);
            text-align: center;
            color: var(--light);
        }

        .track-form {
            padding: var(--space-lg);
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .input-group {
            margin-bottom: var(--space-md);
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .form-input {
            width: 100%;
            max-width: 400px;
            padding: 0.875rem 1rem;
            border: 2px solid var(--gray-300);
            border-radius: var(--radius-md);
            font-family: var(--font-body);
            font-size: 1rem;
            transition: all var(--transition-normal);
            -webkit-appearance: none;
            text-align: center;
        }

        .form-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(255, 107, 53, 0.1);
        }

        .track-result {
            padding: var(--space-lg);
            min-height: 200px;
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: center;
        }

        /* ===== MENU SECTION - MOBILE GRID ===== */
        .menu-section {
            padding: var(--space-xl) var(--space-md);
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
        }

        .category-tabs {
            display: flex;
            gap: var(--space-sm);
            margin-bottom: var(--space-lg);
            overflow-x: auto;
            padding: var(--space-sm) 0;
            -webkit-overflow-scrolling: touch;
            scrollbar-width: none;
            width: 100%;
            justify-content: flex-start;
        }

        .category-tabs::-webkit-scrollbar {
            display: none;
        }

        .category-tab {
            padding: 0.625rem 1.25rem;
            background: var(--gray-100);
            border: none;
            border-radius: var(--radius-full);
            font-family: var(--font-body);
            font-weight: 500;
            color: var(--gray-700);
            cursor: pointer;
            white-space: nowrap;
            transition: all var(--transition-normal);
            flex-shrink: 0;
        }

        .category-tab.active {
            background: var(--gradient-primary);
            color: var(--light);
        }

        .menu-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: var(--space-lg);
            width: 100%;
            max-width: 1200px;
        }

        .menu-item-card {
            background: var(--light);
            border-radius: var(--radius-lg);
            overflow: hidden;
            box-shadow: var(--shadow-md);
            transition: all var(--transition-normal);
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
        }

        .menu-item-card:hover {
            transform: translateY(-4px);
            box-shadow: var(--shadow-lg);
        }

        .menu-item-image {
            height: 200px;
            width: 100%;
            position: relative;
            overflow: hidden;
            background: var(--gray-100);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .menu-item-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform var(--transition-slow);
        }

        .menu-item-card:hover .menu-item-image img {
            transform: scale(1.05);
        }

        .menu-item-emoji {
            font-size: 4rem;
            line-height: 1;
        }

        .item-badge {
            position: absolute;
            top: var(--space-sm);
            right: var(--space-sm);
            background: var(--gradient-primary);
            color: var(--light);
            padding: 0.375rem 0.75rem;
            border-radius: var(--radius-full);
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .menu-item-content {
            padding: var(--space-md);
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: var(--space-sm);
            width: 100%;
        }

        .item-price {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--primary);
            text-align: right;
        }

        .item-description {
            color: var(--gray-600);
            margin-bottom: var(--space-md);
            font-size: 0.875rem;
            text-align: center;
            width: 100%;
        }

        .item-options {
            margin-bottom: var(--space-md);
            width: 100%;
        }

        .option-select {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid var(--gray-300);
            border-radius: var(--radius-md);
            font-family: var(--font-body);
            font-size: 0.9375rem;
            background: var(--light);
            color: var(--secondary);
            text-align: center;
        }

        .item-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            gap: var(--space-sm);
        }

        .quantity-control {
            display: flex;
            align-items: center;
            gap: var(--space-sm);
            background: var(--gray-100);
            border-radius: var(--radius-md);
            padding: 0.375rem;
        }

        .qty-btn {
            width: 32px;
            height: 32px;
            border: none;
            background: var(--light);
            color: var(--primary);
            border-radius: var(--radius-sm);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
            font-weight: 600;
        }

        .qty-display {
            min-width: 32px;
            text-align: center;
            font-weight: 600;
            font-size: 1rem;
        }

        /* ===== CONTACT SECTION - MOBILE LAYOUT ===== */
        .contact-section {
            padding: var(--space-xl) var(--space-md);
            background: var(--gray-100);
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
        }

        .contact-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: var(--space-lg);
            width: 100%;
            max-width: 1200px;
        }

        .contact-card {
            background: var(--light);
            border-radius: var(--radius-lg);
            padding: var(--space-md);
            box-shadow: var(--shadow-sm);
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
        }

        .contact-icon {
            width: 50px;
            height: 50px;
            background: var(--gradient-primary);
            border-radius: var(--radius-md);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--light);
            font-size: 1.25rem;
            margin-bottom: var(--space-sm);
        }

        /* Working Hours List - Better Alignment */
        .hours-list {
            list-style: none;
            padding: 0;
            margin: 0;
            width: 100%;
        }

        .hours-list li {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid var(--gray-200);
            font-size: 0.875rem;
        }

        .hours-list li:last-child {
            border-bottom: none;
        }

        .day-name {
            color: var(--gray-700);
            font-weight: 500;
        }

        .day-time {
            color: var(--gray-600);
        }

        /* Delivery Info List */
        .delivery-list {
            list-style: none;
            padding: 0;
            margin: 0;
            width: 100%;
        }

        .delivery-list li {
            padding: 0.5rem 0;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            font-size: 0.875rem;
            text-align: left;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .delivery-list li:last-child {
            border-bottom: none;
        }

        /* ===== FOOTER - MOBILE OPTIMIZED ===== */
        .footer {
            background: var(--secondary);
            color: var(--light);
            padding: var(--space-xl) var(--space-md);
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
            margin-top: auto;
        }

        .footer-content {
            display: grid;
            grid-template-columns: 1fr;
            gap: var(--space-xl);
            width: 100%;
            max-width: 1200px;
        }

        .footer-section {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
        }

        .footer-section h4 {
            color: var(--light);
            margin-bottom: var(--space-md);
            font-size: 1.125rem;
            width: 100%;
        }

        .footer-links {
            list-style: none;
            padding: 0;
            margin: 0;
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .footer-links li {
            margin-bottom: 0.5rem;
            width: 100%;
        }

        .footer-links a {
            color: rgba(255,255,255,0.7);
            text-decoration: none;
            font-size: 0.875rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            justify-content: center;
        }

        .footer-bottom {
            text-align: center;
            padding-top: var(--space-lg);
            margin-top: var(--space-xl);
            border-top: 1px solid rgba(255,255,255,0.1);
            color: rgba(255,255,255,0.5);
            font-size: 0.75rem;
            width: 100%;
        }

        /* Footer Logo */
        .footer-logo {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: var(--space-sm);
            margin-bottom: 1rem;
        }

        .footer-logo-icon {
            width: 60px;
            height: 60px;
            background: var(--gradient-primary);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
            overflow: hidden;
        }

        .footer-logo-icon img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        /* ===== WHATSAPP POPUP ===== */
        .whatsapp-popup {
            position: fixed;
            bottom: var(--space-lg);
            right: var(--space-lg);
            z-index: 999;
        }

        .whatsapp-toggle {
            width: 56px;
            height: 56px;
            background: var(--gradient-whatsapp);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--light);
            font-size: 1.75rem;
            cursor: pointer;
            box-shadow: var(--shadow-lg);
            border: none;
            transition: all var(--transition-normal);
        }

        .whatsapp-content {
            position: absolute;
            bottom: 65px;
            right: 0;
            width: 280px;
            background: var(--light);
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-xl);
            padding: var(--space-md);
            transform: translateY(10px) scale(0.95);
            opacity: 0;
            visibility: hidden;
            transition: all var(--transition-normal);
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .whatsapp-content.show {
            transform: translateY(0) scale(1);
            opacity: 1;
            visibility: visible;
        }

        .whatsapp-header {
            display: flex;
            align-items: center;
            gap: var(--space-sm);
            margin-bottom: var(--space-md);
            width: 100%;
            justify-content: center;
        }

        .whatsapp-phone {
            background: var(--gray-100);
            padding: var(--space-sm);
            border-radius: var(--radius-md);
            margin-bottom: var(--space-md);
            text-align: center;
            font-weight: 600;
            width: 100%;
        }

        .whatsapp-buttons {
            display: flex;
            flex-direction: column;
            gap: var(--space-sm);
            width: 100%;
        }

        /* ===== MODAL STYLES ===== */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 2000;
            padding: var(--space-md);
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
            align-items: flex-start;
            justify-content: center;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background: var(--light);
            border-radius: var(--radius-lg);
            max-width: 500px;
            width: 100%;
            margin: var(--space-md) auto;
            animation: slideUp 0.3s ease;
            overflow: hidden;
            max-height: 90vh;
            display: flex;
            flex-direction: column;
        }

        .modal-header {
            padding: var(--space-lg);
            background: var(--gradient-primary);
            color: var(--light);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-body {
            padding: var(--space-lg);
            flex: 1;
            overflow-y: auto;
        }

        .modal-footer {
            padding: var(--space-lg);
            border-top: 1px solid var(--gray-200);
            display: flex;
            flex-direction: column;
            gap: var(--space-sm);
        }

        .close-btn {
            background: none;
            border: none;
            color: var(--light);
            font-size: 1.25rem;
            cursor: pointer;
            padding: var(--space-xs);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* Form Styles */
        .form-group {
            margin-bottom: var(--space-md);
            width: 100%;
        }

        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: var(--gray-700);
        }

        /* Order Summary */
        .order-summary {
            background: var(--gray-100);
            border-radius: var(--radius-md);
            padding: var(--space-md);
            margin-top: var(--space-md);
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid var(--gray-200);
            font-size: 0.9375rem;
        }

        .summary-row:last-child {
            border-bottom: none;
        }

        .summary-row.total {
            font-weight: 700;
            font-size: 1.125rem;
            color: var(--primary);
            padding-top: 1rem;
            border-top: 2px solid var(--gray-300);
        }

        /* Cart Items */
        .cart-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: var(--space-md) 0;
            border-bottom: 1px solid var(--gray-200);
        }

        .cart-item-details {
            flex: 1;
        }

        .cart-item-details h4 {
            margin: 0 0 0.25rem;
            font-size: 1rem;
            text-align: left;
        }

        .cart-item-info {
            font-size: 0.875rem;
            color: var(--gray-600);
        }

        .cart-item-actions {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            gap: 0.5rem;
        }

        .cart-item-price {
            font-weight: 600;
            color: var(--primary);
            font-size: 1rem;
        }

        .cart-item-qty {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            background: var(--gray-100);
            border-radius: var(--radius-sm);
            padding: 0.25rem;
        }

        .cart-empty {
            text-align: center;
            padding: var(--space-xl);
            color: var(--gray-500);
        }

        .cart-empty i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: var(--gray-300);
        }

        /* ===== ORDER CONFIRMATION MODAL ===== */
        .order-confirm-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 2000;
            padding: var(--space-md);
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
            align-items: center;
            justify-content: center;
        }

        .order-confirm-modal.active {
            display: flex;
        }

        .order-confirm-content {
            background: var(--light);
            border-radius: var(--radius-lg);
            max-width: 500px;
            width: 100%;
            margin: var(--space-md) auto;
            animation: slideUp 0.3s ease;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
        }

        .order-confirm-header {
            background: var(--gradient-primary);
            padding: var(--space-xl);
            text-align: center;
            color: var(--light);
            width: 100%;
        }

        .order-confirm-body {
            padding: var(--space-xl);
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .order-number-display {
            font-size: 1.5rem;
            font-weight: bold;
            color: var(--primary);
            background: #fff5f0;
            padding: 1rem 2rem;
            border-radius: var(--radius-md);
            margin: 1rem 0;
            text-align: center;
            width: 100%;
            max-width: 300px;
        }

        .whatsapp-support-btn {
            background: var(--gradient-whatsapp);
            color: white;
            border: none;
            padding: 1rem 2rem;
            border-radius: var(--radius-md);
            font-weight: bold;
            font-size: 1rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin: 1rem 0;
            text-decoration: none;
            width: 100%;
            max-width: 300px;
            justify-content: center;
        }

        .receipt-btn {
            background: var(--primary);
            color: white;
            border: none;
            padding: 1rem 2rem;
            border-radius: var(--radius-md);
            font-weight: bold;
            font-size: 1rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin: 0.5rem 0;
            text-decoration: none;
            width: 100%;
            max-width: 300px;
            justify-content: center;
        }

        .continue-btn {
            background: var(--gray-200);
            color: var(--gray-700);
            border: none;
            padding: 1rem 2rem;
            border-radius: var(--radius-md);
            font-weight: bold;
            font-size: 1rem;
            cursor: pointer;
            margin-top: 1rem;
            width: 100%;
            max-width: 300px;
        }

        /* ===== DESKTOP RESPONSIVE ===== */
        @media (min-width: 768px) {
            html { font-size: 16px; }
            
            .container { 
                max-width: 720px; 
                padding: 0 var(--space-lg);
                align-items: center;
            }
            
            h1 { font-size: 2.5rem; text-align: center; }
            h2 { font-size: 2rem; text-align: center; }
            h3 { font-size: 1.75rem; text-align: center; }
            
            .logo-text { display: flex; }
            .logo-text h1 { font-size: 1.25rem; text-align: left; }
            .logo-text span { font-size: 0.75rem; }
            
            .nav-menu {
                position: static;
                transform: none;
                opacity: 1;
                visibility: visible;
                background: transparent;
                box-shadow: none;
                padding: 0;
            }
            
            .nav-links {
                flex-direction: row;
                gap: var(--space-lg);
            }
            
            .nav-link {
                padding: var(--space-xs) 0;
                background: transparent;
                width: auto;
            }
            
            .mobile-menu-btn { display: none; }
            
            .hero-title { font-size: 2.5rem; }
            .hero-buttons { flex-direction: row; }
            .hero-features { grid-template-columns: repeat(3, 1fr); }
            
            .menu-grid { grid-template-columns: repeat(2, 1fr); }
            .contact-grid { grid-template-columns: 1fr 1fr; }
            
            .footer-content { 
                grid-template-columns: repeat(2, 1fr);
                align-items: start;
            }
            
            .footer-section { align-items: flex-start; text-align: left; }
            .footer-links { align-items: flex-start; }
            .footer-links a { justify-content: flex-start; }
            
            .btn { width: auto; }
        }

        @media (min-width: 992px) {
            .container { max-width: 960px; }
            .menu-grid { grid-template-columns: repeat(3, 1fr); }
            .footer-content { grid-template-columns: repeat(4, 1fr); }
            .hero-title { font-size: 3rem; }
        }

        @media (min-width: 1200px) {
            .container { max-width: 1140px; }
            .hero-title { font-size: 3.5rem; }
        }

        /* ===== UTILITY CLASSES ===== */
        .text-center { text-align: center !important; }
        .text-left { text-align: left !important; }
        .text-right { text-align: right !important; }
        .w-100 { width: 100% !important; }
        .mx-auto { margin-left: auto !important; margin-right: auto !important; }
        .d-flex { display: flex !important; }
        .flex-column { flex-direction: column !important; }
        .align-items-center { align-items: center !important; }
        .justify-content-center { justify-content: center !important; }
        .mt-1 { margin-top: 0.25rem !important; }
        .mt-2 { margin-top: 0.5rem !important; }
        .mt-3 { margin-top: 1rem !important; }
        .mt-4 { margin-top: 1.5rem !important; }
        .mb-1 { margin-bottom: 0.25rem !important; }
        .mb-2 { margin-bottom: 0.5rem !important; }
        .mb-3 { margin-bottom: 1rem !important; }
        .mb-4 { margin-bottom: 1.5rem !important; }

        /* ===== ANIMATIONS ===== */
        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        /* ===== RECEIPT STYLES ===== */
        .receipt-container {
            max-width: 400px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            font-family: 'Courier New', monospace;
        }

        .receipt-header {
            text-align: center;
            border-bottom: 2px dashed #000;
            padding-bottom: 10px;
            margin-bottom: 15px;
        }

        .receipt-header h2 {
            font-size: 24px;
            margin: 0;
        }

        .receipt-info {
            margin-bottom: 15px;
        }

        .receipt-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
        }

        .receipt-items {
            margin: 15px 0;
        }

        .receipt-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            border-bottom: 1px dashed #ccc;
            padding-bottom: 5px;
        }

        .receipt-totals {
            margin-top: 15px;
            border-top: 2px dashed #000;
            padding-top: 10px;
        }

        .receipt-footer {
            text-align: center;
            margin-top: 20px;
            font-size: 12px;
            color: #666;
        }

        .receipt-qr {
            text-align: center;
            margin: 20px 0;
        }

        /* ===== IMAGE UPLOAD STYLES ===== */
        .image-upload-container {
            margin: 20px 0;
            text-align: center;
        }

        .image-preview {
            width: 150px;
            height: 150px;
            border: 2px dashed #ddd;
            border-radius: 10px;
            margin: 10px auto;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            background: #f8f9fa;
        }

        .image-preview img {
            max-width: 100%;
            max-height: 100%;
            object-fit: cover;
        }

        .upload-btn {
            background: var(--primary);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin-top: 10px;
        }

        .upload-btn:hover {
            background: var(--primary-dark);
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar">
        <div class="container">
            <div class="nav-container">
                <a href="#" class="logo">
                    <div class="logo-icon">
                        <?php if (!empty($settings['logo_url'])): ?>
                        <img src="<?php echo htmlspecialchars($settings['logo_url']); ?>" alt="<?php echo htmlspecialchars($settings['restaurant_name']); ?>">
                        <?php else: ?>
                        <i class="fas fa-utensils"></i>
                        <?php endif; ?>
                    </div>
                    <div class="logo-text">
                        <h1><?php echo htmlspecialchars($settings['restaurant_name']); ?></h1>
                        <span>Order Online • Fast Delivery</span>
                    </div>
                </a>
                
                <div class="nav-menu">
                    <div class="nav-links">
                        <a href="#home" class="nav-link active">
                            <i class="fas fa-home"></i> Home
                        </a>
                        <a href="#menu" class="nav-link">
                            <i class="fas fa-utensils"></i> Menu
                        </a>
                        <a href="#track-order" class="nav-link">
                            <i class="fas fa-truck"></i> Track Order
                        </a>
                        <a href="#contact" class="nav-link">
                            <i class="fas fa-phone"></i> Contact
                        </a>
                    </div>
                </div>
                
                <div class="nav-actions">
                    <button class="cart-btn" onclick="openCart()">
                        <i class="fas fa-shopping-cart"></i>
                        <span class="cart-count" id="cart-count">0</span>
                    </button>
                    <button class="mobile-menu-btn" onclick="toggleMobileMenu()">
                        <i class="fas fa-bars"></i>
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- Hero Section -->
    <section id="home" class="hero">
        <div class="container">
            <div class="hero-content">
                <h1 class="hero-title">
                    Delicious Food<br>
                    <span style="color: var(--primary);">Delivered to You</span>
                </h1>
                <p class="hero-subtitle">Fresh ingredients, authentic flavors, delivered in 30-45 minutes</p>
                
                <div class="hero-buttons">
                    <a href="#menu" class="btn btn-primary btn-lg">
                        <i class="fas fa-utensils"></i> Order Now
                    </a>
                    <a href="#track-order" class="btn btn-outline btn-lg">
                        <i class="fas fa-truck"></i> Track Order
                    </a>
                </div>
                
                <div class="hero-features">
                    <div class="feature-card">
                        <div class="feature-icon">
                            <i class="fas fa-clock"></i>
                        </div>
                        <h4>Fast Delivery</h4>
                        <p>30-45 minutes</p>
                    </div>
                    <div class="feature-card">
                        <div class="feature-icon">
                            <i class="fas fa-truck"></i>
                        </div>
                        <h4>Free Delivery</h4>
                        <p>Inside Muharraq</p>
                    </div>
                    <div class="feature-card">
                        <div class="feature-icon">
                            <i class="fas fa-star"></i>
                        </div>
                        <h4>4.8 Rating</h4>
                        <p>500+ Reviews</p>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Track Order Section -->
    <section id="track-order" class="track-section">
        <div class="container">
            <h2 class="section-title">Track Your Order</h2>
            
            <div class="track-card">
                <div class="track-header">
                    <h3 style="color: white; margin: 0;">Order Tracking</h3>
                    <p style="color: rgba(255,255,255,0.9); margin: 0.5rem 0 0;">Track Website, POS & WhatsApp orders</p>
                </div>
                
                <div class="track-form">
                    <div class="input-group">
                        <input type="text" id="order-number" class="form-input" 
                               placeholder="Enter order number (e.g., ORD-20251228-1F1D93)" 
                               value="<?php echo isset($_GET['order']) ? htmlspecialchars($_GET['order']) : ''; ?>">
                    </div>
                    <button class="btn btn-primary" onclick="trackOrder()">
                        <i class="fas fa-search"></i> Track Order
                    </button>
                </div>
                
                <div class="track-result" id="track-result">
                    <div class="track-placeholder">
                        <i class="fas fa-truck-moving" style="font-size: 3rem; color: var(--gray-300); margin-bottom: 1rem;"></i>
                        <h4>Track Your Order</h4>
                        <p style="color: var(--gray-600);">Enter your order number above</p>
                        <p style="color: var(--gray-500); font-size: 0.875rem; margin-top: 0.5rem;">
                            Example: ORD-20251228-1F1D93, POS-20251228-070711-, WA-20251229-ABCDEF
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Menu Section -->
    <section id="menu" class="menu-section">
        <div class="container">
            <h2 class="section-title">Our Menu</h2>
            <p class="text-center" style="color: #6C757D; margin-bottom: 2rem;">Fresh ingredients, authentic flavors</p>
            
            <div class="category-tabs">
                <button class="category-tab active" onclick="filterMenu('all')">All Items</button>
                <?php foreach ($categories as $category): ?>
                <button class="category-tab" onclick="filterMenu('<?php echo strtolower(str_replace(' ', '-', $category)); ?>')">
                    <?php echo htmlspecialchars($category); ?>
                </button>
                <?php endforeach; ?>
            </div>
            
            <div class="menu-grid" id="menu-grid">
                <?php foreach ($menuByCategory as $category => $items): ?>
                    <?php foreach ($items as $item): 
                    $imageUrl = getItemImage($item);
                    $hasImage = $imageUrl !== null;
                    ?>
                    <div class="menu-item-card" data-category="<?php echo strtolower(str_replace(' ', '-', $category)); ?>">
                        <div class="menu-item-image">
                            <?php if ($hasImage): ?>
                            <img src="<?php echo htmlspecialchars($imageUrl); ?>" 
                                 alt="<?php echo htmlspecialchars($item['name']); ?>"
                                 onerror="this.style.display='none'; this.parentElement.innerHTML='<div class=\"menu-item-emoji\"><?php echo getCategoryEmoji($category); ?></div>';">
                            <?php else: ?>
                            <div class="menu-item-emoji"><?php echo getCategoryEmoji($category); ?></div>
                            <?php endif; ?>
                            <div class="item-badge"><?php echo htmlspecialchars($category); ?></div>
                        </div>
                        
                        <div class="menu-item-content">
                            <div class="item-header">
                                <h3 style="margin: 0; font-size: 1.25rem; text-align: left; flex: 1;"><?php echo htmlspecialchars($item['name']); ?></h3>
                                <div class="item-price"><?php echo formatPrice($item['price'], $settings['currency'] ?? 'BHD'); ?></div>
                            </div>
                            
                            <p class="item-description" style="text-align: left;"><?php echo htmlspecialchars($item['description'] ?? 'Delicious dish prepared with fresh ingredients'); ?></p>
                            
                            <?php if (!empty($item['options'])): ?>
                            <div class="item-options">
                                <select class="option-select" id="option-<?php echo $item['id']; ?>">
                                    <option value="">Select Option</option>
                                    <?php foreach ($item['options'] as $option): ?>
                                    <option value="<?php echo htmlspecialchars($option); ?>"><?php echo htmlspecialchars($option); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <?php endif; ?>
                            
                            <div class="item-actions">
                                <div class="quantity-control">
                                    <button class="qty-btn minus" onclick="updateQuantity(<?php echo $item['id']; ?>, -1)" disabled>
                                        <i class="fas fa-minus"></i>
                                    </button>
                                    <span class="qty-display" id="qty-<?php echo $item['id']; ?>">0</span>
                                    <button class="qty-btn plus" onclick="updateQuantity(<?php echo $item['id']; ?>, 1)">
                                        <i class="fas fa-plus"></i>
                                    </button>
                                </div>
                                <button class="btn btn-primary btn-sm" onclick="addToCart(<?php echo $item['id']; ?>)">
                                    <i class="fas fa-cart-plus"></i> Add
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endforeach; ?>
            </div>
        </div>
    </section>

    <!-- Contact Section -->
    <section id="contact" class="contact-section">
        <div class="container">
            <h2 class="section-title">Contact Us</h2>
            
            <div class="contact-grid">
                <!-- Working Hours Card -->
                <div class="contact-card">
                    <div class="contact-icon">
                        <i class="fas fa-clock"></i>
                    </div>
                    <h4>Working Hours</h4>
                    <ul class="hours-list">
                        <?php foreach ($workingHours as $day => $hours): ?>
                            <?php if (isset($hours['enabled']) && !$hours['enabled']) continue; ?>
                        <li>
                            <span class="day-name"><?php echo ucfirst($day); ?>:</span>
                            <span class="day-time"><?php echo $hours['open']; ?> - <?php echo $hours['close']; ?></span>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                
                <!-- Location Card -->
                <div class="contact-card">
                    <div class="contact-icon">
                        <i class="fas fa-map-marker-alt"></i>
                    </div>
                    <h4>Location</h4>
                    <p style="text-align: center; margin: 1rem 0;"><?php echo htmlspecialchars($settings['address'] ?? 'Muharraq, Bahrain'); ?></p>
                </div>
                
                <!-- Contact Info Card -->
                <div class="contact-card">
                    <div class="contact-icon">
                        <i class="fas fa-phone"></i>
                    </div>
                    <h4>Phone & WhatsApp</h4>
                    <p><?php echo htmlspecialchars($settings['contact_number']); ?></p>
                    <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $settings['contact_number']); ?>" 
                       class="btn btn-success btn-sm" style="margin-top: 0.5rem;" target="_blank">
                        <i class="fab fa-whatsapp"></i> Chat on WhatsApp
                    </a>
                </div>
                
                <!-- Fast Delivery Card -->
                <div class="contact-card" style="background: var(--gradient-primary); color: white;">
                    <div class="contact-icon" style="background: rgba(255,255,255,0.2);">
                        <i class="fas fa-bolt"></i>
                    </div>
                    <h4 style="color: white;">Fast Delivery</h4>
                    <ul class="delivery-list">
                        <li>• Inside Muharraq: 0 <?php echo $settings['currency'] ?? 'BD'; ?> delivery</li>
                        <li>• Outside Muharraq: <?php echo formatPrice($settings['delivery_charge'] ?? 40, $settings['currency'] ?? 'BHD'); ?> delivery</li>
                        <li>• 30-45 minutes delivery time</li>
                        <li>• Minimum order: <?php echo formatPrice($settings['min_order_amount'] ?? 100, $settings['currency'] ?? 'BHD'); ?></li>
                        <li>• Country: <?php echo htmlspecialchars($settings['country'] ?? 'Bahrain'); ?></li>
                    </ul>
                </div>
            </div>
        </div>
    </section>

    <!-- Footer -->
    <footer class="footer">
        <div class="container">
            <div class="footer-content">
                <!-- Restaurant Info -->
                <div class="footer-section">
                    <div class="footer-logo">
                        <div class="footer-logo-icon">
                            <?php if (!empty($settings['logo_url'])): ?>
                            <img src="<?php echo htmlspecialchars($settings['logo_url']); ?>" alt="Logo">
                            <?php else: ?>
                            <i class="fas fa-utensils"></i>
                            <?php endif; ?>
                        </div>
                        <div>
                            <h4 style="text-align: center;"><?php echo htmlspecialchars($settings['restaurant_name']); ?></h4>
                            <p style="color: rgba(255,255,255,0.7); font-size: 0.875rem; text-align: center;">
                                Delicious Food • Fast Delivery<br>
                                <?php echo htmlspecialchars($settings['address'] ?? 'Muharraq'); ?> • <?php echo htmlspecialchars($settings['country'] ?? 'Bahrain'); ?>
                            </p>
                        </div>
                    </div>
                </div>
                
                <!-- Quick Links -->
                <div class="footer-section">
                    <h4>Quick Links</h4>
                    <ul class="footer-links">
                        <li><a href="#home"><i class="fas fa-home"></i> Home</a></li>
                        <li><a href="#menu"><i class="fas fa-utensils"></i> Menu</a></li>
                        <li><a href="#track-order"><i class="fas fa-truck"></i> Track Order</a></li>
                        <li><a href="#contact"><i class="fas fa-phone"></i> Contact</a></li>
                    </ul>
                </div>
                
                <!-- Contact Info -->
                <div class="footer-section">
                    <h4>Contact Info</h4>
                    <ul class="footer-links">
                        <li><a href="tel:<?php echo htmlspecialchars($settings['contact_number']); ?>">
                            <i class="fas fa-phone"></i> <?php echo htmlspecialchars($settings['contact_number']); ?>
                        </a></li>
                        <li><a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $settings['contact_number']); ?>" target="_blank">
                            <i class="fab fa-whatsapp"></i> WhatsApp
                        </a></li>
                    </ul>
                </div>
                
                <!-- Opening Hours -->
                <div class="footer-section">
                    <h4>Opening Hours</h4>
                    <ul class="footer-links" style="flex-direction: column; align-items: flex-start;">
                        <?php foreach ($workingHours as $day => $hours): ?>
                            <?php if (isset($hours['enabled']) && !$hours['enabled']) continue; ?>
                        <li style="justify-content: space-between; width: 100%;">
                            <span style="color: rgba(255,255,255,0.7);"><?php echo ucfirst($day); ?>:</span>
                            <span style="color: rgba(255,255,255,0.7);"><?php echo $hours['open']; ?> - <?php echo $hours['close']; ?></span>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
            
            <div class="footer-bottom">
                <p>&copy; <?php echo date('Y'); ?> <?php echo htmlspecialchars($settings['restaurant_name']); ?>. All rights reserved.</p>
                <p>Order via WhatsApp: <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $settings['contact_number']); ?>" 
                   style="color: #25D366;" target="_blank"><?php echo htmlspecialchars($settings['contact_number']); ?></a></p>
                <p>Currency: <?php echo $settings['currency'] ?? 'BHD'; ?> • Country: <?php echo htmlspecialchars($settings['country'] ?? 'Bahrain'); ?></p>
            </div>
        </div>
    </footer>

    <!-- WhatsApp Popup -->
    <div class="whatsapp-popup">
        <div class="whatsapp-content" id="whatsapp-content">
            <div class="whatsapp-header">
                <i class="fab fa-whatsapp" style="color: #25D366; font-size: 1.5rem;"></i>
                <h4 style="margin: 0;">Order via WhatsApp</h4>
            </div>
            <div class="whatsapp-phone">
                <i class="fas fa-phone"></i>
                <span><?php echo htmlspecialchars($settings['contact_number']); ?></span>
            </div>
            <div class="whatsapp-buttons">
                <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $settings['contact_number']); ?>?text=Hello!%20I%20want%20to%20place%20an%20order" 
                   class="btn btn-success btn-block" target="_blank">
                    <i class="fab fa-whatsapp"></i> Start Order
                </a>
                <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $settings['contact_number']); ?>?text=Hello!%20I%20want%20to%20check%20order%20status" 
                   class="btn btn-outline btn-block" target="_blank">
                    <i class="fas fa-truck"></i> Track Order
                </a>
            </div>
        </div>
        <button class="whatsapp-toggle" onclick="toggleWhatsApp()">
            <i class="fab fa-whatsapp"></i>
        </button>
    </div>

    <!-- Order Confirmation Modal -->
    <div id="order-confirm-modal" class="order-confirm-modal" style="display: <?php echo $order_success ? 'flex' : 'none'; ?>;">
        <div class="order-confirm-content">
            <div class="order-confirm-header">
                <i class="fas fa-check-circle" style="font-size: 3rem; margin-bottom: 1rem;"></i>
                <h2 style="margin: 0; color: white;">Order Confirmed!</h2>
                <p style="color: rgba(255,255,255,0.9); margin: 0.5rem 0 0;">Your order has been placed successfully</p>
            </div>
            
            <div class="order-confirm-body">
                <p>Thank you for your order! We're preparing your food now.</p>
                
                <div class="order-number-display" id="confirmed-order-number">
                    Order #<?php echo htmlspecialchars($order_number); ?>
                </div>
                
                <div class="image-upload-container">
                    <h4>Upload Your Photo (Optional)</h4>
                    <div class="image-preview" id="image-preview">
                        <i class="fas fa-user-circle" style="font-size: 4rem; color: #ccc;"></i>
                    </div>
                    <input type="file" id="customer-image" accept="image/*" style="display: none;" onchange="previewImage(event)">
                    <button class="upload-btn" onclick="document.getElementById('customer-image').click()">
                        <i class="fas fa-camera"></i> Upload Photo
                    </button>
                </div>
                
                <p>Estimated delivery time: <strong>30-45 minutes</strong></p>
                
                <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $settings['contact_number']); ?>?text=<?php echo urlencode('Help with order #' . $order_number); ?>" 
                   class="whatsapp-support-btn" target="_blank" id="whatsapp-support-link">
                    <i class="fab fa-whatsapp"></i> WhatsApp Support
                </a>
                
                <button class="receipt-btn" onclick="generateReceiptWithImage()">
                    <i class="fas fa-receipt"></i> Generate Receipt with Photo
                </button>
                
                <button class="continue-btn" onclick="closeOrderConfirm()">
                    Continue Shopping
                </button>
            </div>
        </div>
    </div>

    <!-- Cart Modal -->
    <div id="cart-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 style="margin: 0;"><i class="fas fa-shopping-cart"></i> Your Cart</h3>
                <button class="close-btn" onclick="closeCart()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div id="cart-items">
                    <!-- Cart items will be loaded here -->
                </div>
                <div class="order-summary">
                    <div class="summary-row">
                        <span>Subtotal:</span>
                        <span id="cart-subtotal"><?php echo formatPrice(0, $settings['currency'] ?? 'BHD'); ?></span>
                    </div>
                    <div class="summary-row">
                        <span>Delivery Charge:</span>
                        <span id="cart-delivery"><?php echo formatPrice(0, $settings['currency'] ?? 'BHD'); ?></span>
                    </div>
                    <div class="summary-row total">
                        <span>Total:</span>
                        <span id="cart-total"><?php echo formatPrice(0, $settings['currency'] ?? 'BHD'); ?></span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline btn-block" onclick="closeCart()">
                    <i class="fas fa-arrow-left"></i> Continue Shopping
                </button>
                <button class="btn btn-primary btn-block" onclick="proceedToCheckout()" id="checkout-btn" disabled>
                    <i class="fas fa-check"></i> Proceed to Checkout
                </button>
            </div>
        </div>
    </div>

    <!-- Checkout Modal -->
    <div id="checkout-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 style="margin: 0;"><i class="fas fa-check-circle"></i> Checkout</h3>
                <button class="close-btn" onclick="closeCheckout()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <form id="checkout-form">
                    <div class="form-group">
                        <label class="form-label" for="customer-name">Full Name *</label>
                        <input type="text" id="customer-name" class="form-input" required style="text-align: left;">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="customer-phone">Phone Number *</label>
                        <input type="tel" id="customer-phone" class="form-input" required style="text-align: left;">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="customer-address">Delivery Address *</label>
                        <textarea id="customer-address" class="form-input" required 
                                  placeholder="Building number, street, area, city" style="text-align: left;"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="delivery-area">Delivery Area *</label>
                        <select id="delivery-area" class="form-input" required onchange="updateDeliveryCharge()" style="text-align: left;">
                            <option value="">Select Area</option>
                            <?php foreach ($deliveryAreas as $area): ?>
                            <option value="<?php echo $area['id']; ?>" 
                                    data-charge="<?php echo $area['delivery_charge']; ?>"
                                    data-min="<?php echo $area['min_order_amount']; ?>">
                                <?php echo htmlspecialchars($area['area_name']); ?> - 
                                <?php echo formatPrice($area['delivery_charge'], $settings['currency'] ?? 'BHD'); ?> delivery
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="order-notes">Special Instructions</label>
                        <textarea id="order-notes" class="form-input" 
                                  placeholder="Any allergies, extra sauce, delivery instructions, etc." style="text-align: left;"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="payment-method">Payment Method *</label>
                        <select id="payment-method" class="form-input" required style="text-align: left;">
                            <option value="">Select Payment</option>
                            <?php if ($settings['cash_on_delivery'] ?? 1): ?>
                            <option value="cash_on_delivery">Cash on Delivery</option>
                            <?php endif; ?>
                            <?php if ($settings['card_on_delivery'] ?? 1): ?>
                            <option value="card_on_delivery">Card on Delivery</option>
                            <?php endif; ?>
                            <?php if ($settings['online_payment'] ?? 0): ?>
                            <option value="online_payment">Online Payment</option>
                            <?php endif; ?>
                        </select>
                    </div>
                    
                    <div class="order-summary">
                        <h4 style="margin-bottom: 1rem;">Order Summary</h4>
                        <div id="checkout-items"></div>
                        <div class="summary-row">
                            <span>Subtotal:</span>
                            <span id="checkout-subtotal"><?php echo formatPrice(0, $settings['currency'] ?? 'BHD'); ?></span>
                        </div>
                        <div class="summary-row">
                            <span>Delivery:</span>
                            <span id="checkout-delivery"><?php echo formatPrice(0, $settings['currency'] ?? 'BHD'); ?></span>
                        </div>
                        <div class="summary-row total">
                            <span>Total Amount:</span>
                            <span id="checkout-total"><?php echo formatPrice(0, $settings['currency'] ?? 'BHD'); ?></span>
                        </div>
                    </div>
                    
                    <div class="modal-footer" style="padding: 0; border: none; margin-top: 1.5rem;">
                        <button type="button" class="btn btn-outline" onclick="closeCheckout()">
                            <i class="fas fa-arrow-left"></i> Back to Cart
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-check"></i> Place Order
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Receipt Modal (Hidden) -->
    <div id="receipt-modal" style="display: none; position: fixed; z-index: -1;">
        <div class="receipt-container" id="receipt-content">
            <div class="receipt-header">
                <h2><?php echo htmlspecialchars($settings['restaurant_name']); ?></h2>
                <p><?php echo htmlspecialchars($settings['address'] ?? ''); ?></p>
                <p>Tel: <?php echo htmlspecialchars($settings['contact_number']); ?></p>
            </div>
            
            <div class="receipt-info">
                <div class="receipt-row">
                    <span>Order #:</span>
                    <span id="receipt-order-number">ORD-000000</span>
                </div>
                <div class="receipt-row">
                    <span>Date:</span>
                    <span id="receipt-date"><?php echo date('Y-m-d H:i'); ?></span>
                </div>
                <div class="receipt-row">
                    <span>Customer:</span>
                    <span id="receipt-customer-name">John Doe</span>
                </div>
                <div class="receipt-row">
                    <span>Phone:</span>
                    <span id="receipt-customer-phone">+1234567890</span>
                </div>
                <div class="receipt-row">
                    <span>Address:</span>
                    <span id="receipt-customer-address">123 Street</span>
                </div>
            </div>
            
            <div class="receipt-items" id="receipt-items">
                <!-- Items will be added here -->
            </div>
            
            <div class="receipt-totals">
                <div class="receipt-row">
                    <span>Subtotal:</span>
                    <span id="receipt-subtotal">0.000 BHD</span>
                </div>
                <div class="receipt-row">
                    <span>Delivery:</span>
                    <span id="receipt-delivery">0.000 BHD</span>
                </div>
                <div class="receipt-row" style="font-weight: bold; font-size: 1.1em;">
                    <span>TOTAL:</span>
                    <span id="receipt-total">0.000 BHD</span>
                </div>
            </div>
            
            <div id="receipt-image-container" style="text-align: center; margin: 20px 0;">
                <!-- Customer image will be added here -->
            </div>
            
            <div class="receipt-footer">
                <p>Thank you for your order!</p>
                <p>For any queries, contact: <?php echo htmlspecialchars($settings['contact_number']); ?></p>
                <p>Estimated delivery: 30-45 minutes</p>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // ===== GLOBAL VARIABLES =====
        let cart = JSON.parse(localStorage.getItem('restaurant_cart')) || <?php echo json_encode($_SESSION['cart']); ?>;
        let menuItems = <?php echo json_encode($menuItems); ?>;
        const minOrderAmount = <?php echo $settings['min_order_amount']; ?>;
        const restaurantPhone = '<?php echo $settings['contact_number']; ?>';
        const API_KEY = '<?php echo $api_key; ?>';
        const currency = '<?php echo $settings['currency'] ?? 'BHD'; ?>';
        const deliveryAreas = <?php echo json_encode($deliveryAreas); ?>;
        let customerImage = null;

        // Format price function
        function formatPrice(price) {
            const decimals = ['BHD', 'USD', 'EUR', 'GBP', 'PKR'].includes(currency) ? 2 : 2;
            let symbol = '';
            
            switch(currency) {
                case 'BHD': symbol = '.د.ب'; break;
                case 'USD': symbol = '$'; break;
                case 'EUR': symbol = '€'; break;
                case 'GBP': symbol = '£'; break;
                case 'INR': symbol = '₹'; break;
                case 'SAR': symbol = 'ر.س'; break;
                case 'QAR': symbol = 'ر.ق'; break;
                case 'AED': symbol = 'د.إ'; break;
                case 'PKR': symbol = '₨'; break;
                default: symbol = currency + ' ';
            }
            
            return symbol + parseFloat(price).toFixed(decimals);
        }
        
        // ===== INITIALIZATION =====
        document.addEventListener('DOMContentLoaded', function() {
            updateCartDisplay();
            
            // Check URL for order tracking
            const urlParams = new URLSearchParams(window.location.search);
            const orderParam = urlParams.get('order');
            if (orderParam) {
                document.getElementById('order-number').value = orderParam;
                setTimeout(() => {
                    const trackSection = document.querySelector('#track-order');
                    if (trackSection) {
                        trackSection.scrollIntoView({ behavior: 'smooth' });
                        setTimeout(() => trackOrder(), 500);
                    }
                }, 1000);
            }
            
            // Show order confirmation modal if order was successful
            <?php if ($order_success && $order_number): ?>
            setTimeout(() => {
                document.getElementById('order-confirm-modal').style.display = 'flex';
                document.body.style.overflow = 'hidden';
            }, 1000);
            <?php endif; ?>
        });

        // ===== CART FUNCTIONS =====
        function updateQuantity(itemId, change) {
            const display = document.getElementById(`qty-${itemId}`);
            let current = parseInt(display.textContent) || 0;
            current = Math.max(0, current + change);
            display.textContent = current;
            
            const minusBtn = display.parentElement.querySelector('.minus');
            minusBtn.disabled = current <= 0;
        }

        function addToCart(itemId) {
            const quantity = parseInt(document.getElementById(`qty-${itemId}`).textContent);
            
            if (quantity < 1) {
                showNotification('Please select quantity first', 'warning');
                return;
            }
            
            const menuItem = menuItems.find(item => item.id == itemId);
            if (!menuItem) {
                showNotification('Item not found', 'error');
                return;
            }
            
            const optionSelect = document.getElementById(`option-${itemId}`);
            const selectedOption = optionSelect ? optionSelect.value : '';
            
            const existingIndex = cart.findIndex(item => 
                item.id == itemId && item.option == selectedOption
            );
            
            if (existingIndex > -1) {
                cart[existingIndex].quantity += quantity;
            } else {
                cart.push({
                    id: itemId,
                    name: menuItem.name,
                    price: parseFloat(menuItem.price),
                    quantity: quantity,
                    option: selectedOption,
                    category: menuItem.category
                });
            }
            
            document.getElementById(`qty-${itemId}`).textContent = '0';
            if (optionSelect) optionSelect.value = '';
            
            const minusBtn = document.querySelector(`#qty-${itemId}`).parentElement.querySelector('.minus');
            minusBtn.disabled = true;
            
            saveCart();
            updateCartDisplay();
            showNotification(`Added ${quantity} × ${menuItem.name} to cart`, 'success');
        }

        function removeFromCart(index) {
            const item = cart[index];
            cart.splice(index, 1);
            saveCart();
            updateCartDisplay();
            showNotification(`Removed ${item.name} from cart`, 'info');
        }

        function updateCartItemQuantity(index, change) {
            if (cart[index]) {
                cart[index].quantity += change;
                if (cart[index].quantity < 1) {
                    cart.splice(index, 1);
                }
                saveCart();
                updateCartDisplay();
                if (document.getElementById('cart-modal').classList.contains('active')) {
                    renderCartItems();
                }
            }
        }

        function saveCart() {
            localStorage.setItem('restaurant_cart', JSON.stringify(cart));
        }

        function updateCartDisplay() {
            const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
            document.getElementById('cart-count').textContent = totalItems;
            
            if (document.getElementById('cart-modal').classList.contains('active')) {
                renderCartItems();
            }
            
            const subtotal = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            const checkoutBtn = document.getElementById('checkout-btn');
            checkoutBtn.disabled = subtotal < minOrderAmount;
        }

        function renderCartItems() {
            const cartItemsContainer = document.getElementById('cart-items');
            
            if (cart.length === 0) {
                cartItemsContainer.innerHTML = `
                    <div class="cart-empty">
                        <i class="fas fa-shopping-cart"></i>
                        <h4>Your cart is empty</h4>
                        <p>Add some delicious items from our menu</p>
                    </div>
                `;
                updateCartTotals(0, 0);
                return;
            }
            
            let subtotal = 0;
            let html = '';
            
            cart.forEach((item, index) => {
                const itemTotal = item.price * item.quantity;
                subtotal += itemTotal;
                
                html += `
                    <div class="cart-item">
                        <div class="cart-item-details">
                            <h4>${item.name}</h4>
                            <div class="cart-item-info">
                                <div>${formatPrice(item.price)} × ${item.quantity}</div>
                                ${item.option ? `<div>Option: ${item.option}</div>` : ''}
                            </div>
                        </div>
                        <div class="cart-item-actions">
                            <div class="cart-item-price">${formatPrice(itemTotal)}</div>
                            <div class="cart-item-qty">
                                <button onclick="updateCartItemQuantity(${index}, -1)" 
                                        class="qty-btn" ${item.quantity <= 1 ? 'disabled' : ''}>
                                    <i class="fas fa-minus"></i>
                                </button>
                                <span>${item.quantity}</span>
                                <button onclick="updateCartItemQuantity(${index}, 1)" class="qty-btn">
                                    <i class="fas fa-plus"></i>
                                </button>
                            </div>
                            <button onclick="removeFromCart(${index})" style="background: none; border: none; color: #D63031; cursor: pointer; padding: 0.25rem;">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                `;
            });
            
            cartItemsContainer.innerHTML = html;
            updateCartTotals(subtotal, 0);
        }

        function updateCartTotals(subtotal, deliveryCharge) {
            const total = subtotal + deliveryCharge;
            
            document.getElementById('cart-subtotal').textContent = formatPrice(subtotal);
            document.getElementById('cart-delivery').textContent = formatPrice(deliveryCharge);
            document.getElementById('cart-total').textContent = formatPrice(total);
            
            const checkoutBtn = document.getElementById('checkout-btn');
            checkoutBtn.disabled = subtotal < minOrderAmount;
            if (subtotal < minOrderAmount) {
                checkoutBtn.title = `Minimum order is ${formatPrice(minOrderAmount)}`;
            } else {
                checkoutBtn.title = '';
            }
        }

        // ===== MODAL FUNCTIONS =====
        function openCart() {
            renderCartItems();
            document.getElementById('cart-modal').classList.add('active');
            document.body.style.overflow = 'hidden';
        }

        function closeCart() {
            document.getElementById('cart-modal').classList.remove('active');
            document.body.style.overflow = 'auto';
        }

        function proceedToCheckout() {
            const subtotal = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            
            if (subtotal < minOrderAmount) {
                showNotification(`Minimum order amount is ${formatPrice(minOrderAmount)}`, 'warning');
                return;
            }
            
            closeCart();
            openCheckout();
        }

        function openCheckout() {
            if (cart.length === 0) {
                showNotification('Your cart is empty', 'warning');
                return;
            }
            
            let subtotal = 0;
            let itemsHtml = '';
            
            cart.forEach(item => {
                const itemTotal = item.price * item.quantity;
                subtotal += itemTotal;
                itemsHtml += `
                    <div style="display: flex; justify-content: space-between; padding: 0.5rem 0; border-bottom: 1px solid #E9ECEF; font-size: 0.875rem;">
                        <span>${item.name} × ${item.quantity}</span>
                        <span>${formatPrice(itemTotal)}</span>
                    </div>
                `;
            });
            
            const deliveryAreaSelect = document.getElementById('delivery-area');
            const selectedOption = deliveryAreaSelect.options[deliveryAreaSelect.selectedIndex];
            const deliveryCharge = selectedOption ? parseFloat(selectedOption.dataset.charge) : 0;
            const minAreaOrder = selectedOption ? parseFloat(selectedOption.dataset.min) : 0;
            
            const total = subtotal + deliveryCharge;
            
            document.getElementById('checkout-items').innerHTML = itemsHtml;
            document.getElementById('checkout-subtotal').textContent = formatPrice(subtotal);
            document.getElementById('checkout-delivery').textContent = formatPrice(deliveryCharge);
            document.getElementById('checkout-total').textContent = formatPrice(total);
            
            // Check if subtotal meets minimum for selected area
            if (minAreaOrder > 0 && subtotal < minAreaOrder) {
                document.getElementById('checkout-total').innerHTML = formatPrice(total) + 
                    `<br><small style="color: #D63031;">Minimum order for this area: ${formatPrice(minAreaOrder)}</small>`;
            }
            
            document.getElementById('checkout-modal').classList.add('active');
            document.body.style.overflow = 'hidden';
        }

        function closeCheckout() {
            document.getElementById('checkout-modal').classList.remove('active');
            document.body.style.overflow = 'auto';
            openCart();
        }

        function updateDeliveryCharge() {
            const deliveryAreaSelect = document.getElementById('delivery-area');
            const selectedOption = deliveryAreaSelect.options[deliveryAreaSelect.selectedIndex];
            const subtotal = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            const deliveryCharge = selectedOption ? parseFloat(selectedOption.dataset.charge) : 0;
            const minAreaOrder = selectedOption ? parseFloat(selectedOption.dataset.min) : 0;
            const total = subtotal + deliveryCharge;
            
            document.getElementById('checkout-delivery').textContent = formatPrice(deliveryCharge);
            document.getElementById('checkout-total').textContent = formatPrice(total);
            
            // Check if subtotal meets minimum for selected area
            if (minAreaOrder > 0 && subtotal < minAreaOrder) {
                document.getElementById('checkout-total').innerHTML = formatPrice(total) + 
                    `<br><small style="color: #D63031;">Minimum order for this area: ${formatPrice(minAreaOrder)}</small>`;
            }
        }

        // ===== ORDER CONFIRMATION FUNCTIONS =====
        function showOrderConfirmation(orderNumber, totalAmount) {
            const modal = document.getElementById('order-confirm-modal');
            const orderNumberElement = document.getElementById('confirmed-order-number');
            const whatsappLink = document.getElementById('whatsapp-support-link');
            
            orderNumberElement.textContent = `Order #${orderNumber}`;
            whatsappLink.href = `https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $settings['contact_number']); ?>?text=${encodeURIComponent('Help with order #' + orderNumber)}`;
            
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
            
            // Update URL without reload
            const url = new URL(window.location);
            url.searchParams.set('order_success', 'true');
            url.searchParams.set('order_number', orderNumber);
            window.history.replaceState({}, '', url);
        }

        function closeOrderConfirm() {
            document.getElementById('order-confirm-modal').style.display = 'none';
            document.body.style.overflow = 'auto';
            
            // Clear cart after order
            cart = [];
            saveCart();
            updateCartDisplay();
            customerImage = null;
            document.getElementById('image-preview').innerHTML = '<i class="fas fa-user-circle" style="font-size: 4rem; color: #ccc;"></i>';
        }

        function previewImage(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    customerImage = e.target.result;
                    document.getElementById('image-preview').innerHTML = `<img src="${customerImage}" alt="Customer Image">`;
                };
                reader.readAsDataURL(file);
            }
        }

        // ===== ORDER TRACKING - UPDATED =====
        async function trackOrder() {
            const orderNumber = document.getElementById('order-number').value.trim();
            const resultDiv = document.getElementById('track-result');
            
            if (!orderNumber) {
                showNotification('Please enter order number', 'warning');
                return;
            }
            
            resultDiv.innerHTML = `
                <div style="text-align: center; padding: 3rem;">
                    <div class="spinner" style="width: 40px; height: 40px; border: 4px solid #f3f3f3; border-top: 4px solid var(--primary); border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto 1rem;"></div>
                    <h4 style="margin: 1rem 0 0.5rem;">Tracking Order</h4>
                    <p style="color: #6C757D;">${orderNumber}</p>
                </div>
            `;
            
            try {
                // Try the new API endpoint first
                const response = await fetch(`api/check_order_status.php?order_number=${encodeURIComponent(orderNumber)}`);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.success) {
                    renderOrderStatus(result.data);
                } else {
                    throw new Error(result.message || 'Order not found');
                }
                
            } catch (error) {
                console.error('Track order error:', error);
                resultDiv.innerHTML = `
                    <div style="text-align: center; padding: 2rem; color: #6C757D;">
                        <i class="fas fa-exclamation-triangle" style="font-size: 3rem; color: #FDCB6E; margin-bottom: 1rem;"></i>
                        <h4>Unable to Track Order</h4>
                        <p>${error.message || 'Please check order number'}</p>
                        <p style="font-size: 0.875rem; margin-top: 0.5rem;">Order numbers look like: ORD-20251229-ABCD, POS-20251229-XXXX, or WA-20251229-1234</p>
                        <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $settings['contact_number']); ?>?text=${encodeURIComponent(`Check order status for ${orderNumber}`)}" 
                           class="btn btn-success btn-sm mt-2" target="_blank">
                            <i class="fab fa-whatsapp"></i> WhatsApp Support
                        </a>
                    </div>
                `;
            }
        }

        function renderOrderStatus(orderData) {
            const resultDiv = document.getElementById('track-result');
            const order = orderData.order;
            
            if (!order) {
                resultDiv.innerHTML = `
                    <div style="text-align: center; padding: 2rem; color: #6C757D;">
                        <i class="fas fa-exclamation-triangle" style="font-size: 3rem; color: #FDCB6E; margin-bottom: 1rem;"></i>
                        <h4>No Order Data</h4>
                        <p>Unable to display order details</p>
                    </div>
                `;
                return;
            }
            
            const statusConfig = {
                'pending': { icon: '⏳', label: 'Order Received', color: '#FFC107' },
                'confirmed': { icon: '✅', label: 'Confirmed', color: '#17A2B8' },
                'preparing': { icon: '👨‍🍳', label: 'Preparing Food', color: '#FD7E14' },
                'ready': { icon: '📦', label: 'Ready for Pickup', color: '#28A745' },
                'out_for_delivery': { icon: '🚚', label: 'Out for Delivery', color: '#007BFF' },
                'delivered': { icon: '🏠', label: 'Delivered', color: '#6F42C1' },
                'cancelled': { icon: '❌', label: 'Cancelled', color: '#DC3545' }
            };
            
            const status = statusConfig[order.status] || statusConfig.pending;
            
            // Format date
            let orderDate = 'N/A';
            if (order.created_at) {
                const date = new Date(order.created_at);
                orderDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
            }
            
            resultDiv.innerHTML = `
                <div style="width: 100%;">
                    <div style="text-align: center; margin-bottom: 1.5rem;">
                        <h4 style="margin: 0 0 0.25rem; color: var(--secondary);">Order #${order.order_number}</h4>
                        <p style="color: #6C757D; font-size: 0.875rem; margin: 0.25rem 0;">
                            <i class="fas fa-user"></i> ${order.customer_name || 'N/A'}
                        </p>
                        <p style="color: #6C757D; font-size: 0.875rem; margin: 0.25rem 0;">
                            <i class="fas fa-calendar"></i> ${orderDate}
                        </p>
                        <p style="color: #6C757D; font-size: 0.875rem; margin: 0.25rem 0;">
                            <i class="fas fa-map-marker-alt"></i> ${order.customer_address || 'N/A'}
                        </p>
                        <p style="color: #6C757D; font-size: 0.875rem; margin: 0.25rem 0;">
                            Source: ${order.source_name || order.source || 'Website'}
                        </p>
                    </div>
                    
                    <div style="background: ${status.color}15; padding: 1.5rem; border-radius: 12px; margin-bottom: 1.5rem; border-left: 4px solid ${status.color};">
                        <div style="display: flex; align-items: center; gap: 1rem; justify-content: center;">
                            <div style="width: 50px; height: 50px; border-radius: 50%; background: ${status.color}; 
                                 display: flex; align-items: center; justify-content: center; color: white; font-size: 1.5rem;">
                                ${status.icon}
                            </div>
                            <div style="text-align: left;">
                                <div style="font-weight: 600; color: ${status.color}; font-size: 1.1rem;">${status.label}</div>
                                <div style="font-size: 0.875rem; color: #666;">${order.estimated_time || '30-45 minutes estimated delivery'}</div>
                            </div>
                        </div>
                    </div>
                    
                    <div style="background: #f8f9fa; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
                            <span style="color: #6C757D;">Phone:</span>
                            <span>${order.customer_phone}</span>
                        </div>
                        <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
                            <span style="color: #6C757D;">Delivery Area:</span>
                            <span>${order.delivery_area || 'Not specified'}</span>
                        </div>
                        <div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
                            <span style="color: #6C757D;">Payment:</span>
                            <span>${order.payment_method || 'Not specified'}</span>
                        </div>
                        ${order.notes ? `
                        <div style="margin-top: 0.5rem; padding-top: 0.5rem; border-top: 1px solid #ddd;">
                            <span style="color: #6C757D;">Notes:</span>
                            <p style="margin: 0.25rem 0 0; font-size: 0.875rem;">${order.notes}</p>
                        </div>
                        ` : ''}
                    </div>
                    
                    <div style="text-align: center; font-size: 1.25rem; font-weight: 700; color: var(--primary); margin: 1.5rem 0;">
                        Total: ${order.final_amount ? formatPrice(order.final_amount) : '0.00'}
                    </div>
                    
                    <div style="text-align: center;">
                        <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $settings['contact_number']); ?>?text=${encodeURIComponent(`Query about order #${order.order_number}`)}" 
                           class="btn btn-success" target="_blank" style="display: inline-flex; width: auto;">
                            <i class="fab fa-whatsapp"></i> WhatsApp Support
                        </a>
                    </div>
                </div>
            `;
        }

        // ===== CHECKOUT =====
        document.getElementById('checkout-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const customerName = document.getElementById('customer-name').value.trim();
            const customerPhone = document.getElementById('customer-phone').value.trim();
            const customerAddress = document.getElementById('customer-address').value.trim();
            const deliveryAreaSelect = document.getElementById('delivery-area');
            const deliveryAreaId = deliveryAreaSelect.value;
            const orderNotes = document.getElementById('order-notes').value.trim();
            const paymentMethod = document.getElementById('payment-method').value;
            
            if (!customerName || !customerPhone || !customerAddress || !deliveryAreaId || !paymentMethod) {
                showNotification('Please fill all required fields', 'error');
                return;
            }
            
            const selectedArea = deliveryAreas.find(area => area.id == deliveryAreaId);
            if (!selectedArea) {
                showNotification('Please select a valid delivery area', 'error');
                return;
            }
            
            const subtotal = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            
            // Check minimum order for area
            if (selectedArea.min_order_amount > 0 && subtotal < selectedArea.min_order_amount) {
                showNotification(`Minimum order for ${selectedArea.area_name} is ${formatPrice(selectedArea.min_order_amount)}`, 'error');
                return;
            }
            
            const deliveryCharge = parseFloat(selectedArea.delivery_charge);
            const totalAmount = subtotal + deliveryCharge;
            
            const orderData = {
                customer_name: customerName,
                customer_phone: customerPhone,
                customer_address: customerAddress,
                delivery_area: selectedArea.area_name,
                delivery_area_id: deliveryAreaId,
                notes: orderNotes,
                payment_method: paymentMethod,
                total_amount: subtotal,
                delivery_charge: deliveryCharge,
                final_amount: totalAmount,
                items: cart.map(item => ({
                    item_id: item.id,
                    item_name: item.name,
                    quantity: item.quantity,
                    price: item.price,
                    options: item.option || ''
                })),
                source: 'website'
            };
            
            const submitBtn = e.target.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
            submitBtn.disabled = true;
            
            try {
                const response = await fetch('api/order_simple.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(orderData)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // Save customer info for receipt
                    localStorage.setItem('last_order_customer', JSON.stringify({
                        name: customerName,
                        phone: customerPhone,
                        address: customerAddress,
                        order_number: result.order_number
                    }));
                    
                    // Close checkout modal
                    closeCheckout();
                    
                    // Show confirmation modal
                    setTimeout(() => {
                        showOrderConfirmation(result.order_number, totalAmount);
                        showNotification('Order placed successfully!', 'success');
                    }, 500);
                    
                } else {
                    throw new Error(result.message || 'Order failed');
                }
                
            } catch (error) {
                showNotification('Failed to place order: ' + error.message, 'error');
            } finally {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }
        });

        // ===== RECEIPT GENERATION =====
        function generateReceiptWithImage() {
            const orderNumber = document.querySelector('#confirmed-order-number').textContent.replace('Order #', '');
            const customerInfo = JSON.parse(localStorage.getItem('last_order_customer') || '{}');
            
            // Update receipt content
            document.getElementById('receipt-order-number').textContent = orderNumber;
            document.getElementById('receipt-date').textContent = new Date().toLocaleString();
            document.getElementById('receipt-customer-name').textContent = customerInfo.name || 'Customer';
            document.getElementById('receipt-customer-phone').textContent = customerInfo.phone || 'N/A';
            document.getElementById('receipt-customer-address').textContent = customerInfo.address || 'N/A';
            
            // Update receipt items
            const receiptItems = document.getElementById('receipt-items');
            let itemsHtml = '';
            let subtotal = 0;
            
            cart.forEach(item => {
                const itemTotal = item.price * item.quantity;
                subtotal += itemTotal;
                itemsHtml += `
                    <div class="receipt-item">
                        <div>
                            <div>${item.name} × ${item.quantity}</div>
                            ${item.option ? `<small>${item.option}</small>` : ''}
                        </div>
                        <div>${formatPrice(itemTotal)}</div>
                    </div>
                `;
            });
            
            receiptItems.innerHTML = itemsHtml;
            
            // Update totals (get from last order)
            const deliveryAreaSelect = document.getElementById('delivery-area');
            const selectedOption = deliveryAreaSelect ? deliveryAreaSelect.options[deliveryAreaSelect.selectedIndex] : null;
            const deliveryCharge = selectedOption ? parseFloat(selectedOption.dataset.charge) : 0;
            const total = subtotal + deliveryCharge;
            
            document.getElementById('receipt-subtotal').textContent = formatPrice(subtotal);
            document.getElementById('receipt-delivery').textContent = formatPrice(deliveryCharge);
            document.getElementById('receipt-total').textContent = formatPrice(total);
            
            // Add customer image if available
            const imageContainer = document.getElementById('receipt-image-container');
            if (customerImage) {
                imageContainer.innerHTML = `<img src="${customerImage}" alt="Customer" style="max-width: 150px; max-height: 150px; border-radius: 10px;">`;
            } else {
                imageContainer.innerHTML = '';
            }
            
            // Generate receipt image
            const receiptContent = document.getElementById('receipt-content');
            
            html2canvas(receiptContent).then(canvas => {
                const imgData = canvas.toDataURL('image/png');
                
                // Create download link
                const link = document.createElement('a');
                link.href = imgData;
                link.download = `Receipt-${orderNumber}.png`;
                link.click();
                
                showNotification('Receipt generated successfully!', 'success');
            }).catch(error => {
                console.error('Error generating receipt:', error);
                showNotification('Failed to generate receipt', 'error');
            });
        }

        // ===== UTILITY FUNCTIONS =====
        function showNotification(message, type = 'info') {
            // Remove existing notifications
            document.querySelectorAll('.notification').forEach(n => n.remove());
            
            const notification = document.createElement('div');
            notification.className = `notification ${type} show`;
            notification.innerHTML = `
                <i class="fas ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : type === 'warning' ? 'fa-exclamation-triangle' : 'fa-info-circle'}"></i>
                <span>${message}</span>
                <button onclick="this.parentElement.remove()" style="background: none; border: none; color: #6C757D; cursor: pointer; margin-left: auto;">
                    <i class="fas fa-times"></i>
                </button>
            `;
            
            notification.style.cssText = `
                position: fixed;
                top: 80px;
                right: 1rem;
                background: white;
                border-radius: 8px;
                padding: 1rem;
                box-shadow: 0 4px 16px rgba(0,0,0,0.2);
                display: flex;
                align-items: center;
                gap: 1rem;
                max-width: calc(100% - 2rem);
                z-index: 2001;
                border-left: 4px solid ${type === 'success' ? '#00B894' : type === 'error' ? '#D63031' : type === 'warning' ? '#FDCB6E' : '#0984E3'};
                animation: slideUp 0.3s ease;
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                if (notification.parentElement) {
                    notification.remove();
                }
            }, 5000);
        }

        function filterMenu(category) {
            document.querySelectorAll('.category-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            event.target.classList.add('active');
            
            const items = document.querySelectorAll('.menu-item-card');
            items.forEach(item => {
                if (category === 'all' || item.dataset.category === category) {
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                }
            });
        }

        function toggleWhatsApp() {
            const content = document.getElementById('whatsapp-content');
            const toggle = document.querySelector('.whatsapp-toggle');
            content.classList.toggle('show');
            toggle.classList.toggle('active');
        }

        function toggleMobileMenu() {
            document.querySelector('.nav-menu').classList.toggle('show');
        }

        // Smooth scrolling
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function(e) {
                e.preventDefault();
                const targetId = this.getAttribute('href');
                if (targetId === '#') return;
                
                const targetElement = document.querySelector(targetId);
                if (targetElement) {
                    window.scrollTo({
                        top: targetElement.offsetTop - 70,
                        behavior: 'smooth'
                    });
                }
                
                // Close mobile menu if open
                document.querySelector('.nav-menu').classList.remove('show');
            });
        });
    </script>
</body>
</html>