<?php
// home.php - النسخة النهائية مع AJAX المحسن وإزالة أيقونة السلة
include 'config.php';

if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['cart']) || !is_array($_SESSION['cart'])) $_SESSION['cart'] = [];

// ===== معالجة إضافة المنتج إلى السلة (للطريقة التقليدية كنسخة احتياطية) =====
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_to_cart']) && !isset($_POST['ajax'])) {
    $meal_id = (int)($_POST['meal_id'] ?? 0);
    $quantity = (int)($_POST['quantity'] ?? 1);
    $portion_id = isset($_POST['portion_id']) && !empty($_POST['portion_id']) ? (int)$_POST['portion_id'] : null;
    $portion_name = $_POST['portion_name'] ?? 'كامل';
    $portion_price = (float)($_POST['portion_price'] ?? 0);
    
    if ($meal_id > 0 && $quantity > 0) {
        $stmt = $conn->prepare("SELECT id, name, price, image, has_portions FROM meals WHERE id = ? AND is_active = 1");
        $stmt->bind_param('i', $meal_id);
        $stmt->execute();
        $meal_result = $stmt->get_result();
        
        if ($meal_result->num_rows > 0) {
            $meal_data = $meal_result->fetch_assoc();
            
            $final_price = $meal_data['price'];
            if ($portion_id && $meal_data['has_portions']) {
                $final_price = $portion_price > 0 ? $portion_price : $meal_data['price'];
            }
            
            $found = false;
            foreach ($_SESSION['cart'] as $key => $item) {
                if ($item['meal_id'] == $meal_id && $item['portion_id'] == $portion_id) {
                    $_SESSION['cart'][$key]['quantity'] += $quantity;
                    $found = true;
                    break;
                }
            }
            
            if (!$found) {
                $_SESSION['cart'][] = [
                    'meal_id' => $meal_id,
                    'meal_name' => $meal_data['name'],
                    'quantity' => $quantity,
                    'price' => $final_price,
                    'base_price' => $meal_data['price'],
                    'image' => $meal_data['image'],
                    'has_portions' => $meal_data['has_portions'],
                    'portion_id' => $portion_id,
                    'portion_name' => $portion_name,
                    'portion_price' => $final_price
                ];
            }
            
            $_SESSION['success_message'] = "✅ تمت إضافة " . $meal_data['name'] . 
                ($portion_name != 'كامل' ? " (" . $portion_name . ")" : "") . " إلى السلة";
        }
        $stmt->close();
    }
    
    header('Location: home.php');
    exit();
}

// رسالة النجاح
$success_message = $_SESSION['success_message'] ?? '';
unset($_SESSION['success_message']);

// دالة لجلب أقسام الوجبة
function getMealPortions($conn, $meal_id) {
    $portions = [];
    $stmt = $conn->prepare("SELECT id, name, price FROM meal_portions WHERE meal_id = ? AND is_active = 1 ORDER BY price");
    if ($stmt) {
        $stmt->bind_param('i', $meal_id);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($portion = $result->fetch_assoc()) {
            $portions[] = $portion;
        }
        $stmt->close();
    }
    return $portions;
}

// جلب جميع الأصناف والوجبات
$categories = $conn->query("SELECT * FROM categories ORDER BY name");
$all_meals = $conn->query("SELECT m.*, c.name as category_name FROM meals m 
                          LEFT JOIN categories c ON m.category_id = c.id 
                          WHERE m.is_active = 1 
                          ORDER BY m.created_at ASC");

// Sliders
$sliders = $conn->query("SELECT * FROM sliders WHERE is_active = 1");
$sliders_array = [];
while($slide = $sliders->fetch_assoc()) {
    $sliders_array[] = $slide;
}

// Cart count
$cart_count = 0;
foreach ($_SESSION['cart'] as $item) $cart_count += $item['quantity'] ?? 0;

// Customer info
$customer_name = $_SESSION['customer_name'] ?? 'زائر';
$customer_email = $_SESSION['customer_email'] ?? '';
$default_image = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZmNmY2ZjIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGRvbWluYW50LWJhc2VsaW5lPSJtaWRkbGUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZpbGw9IiNjY2NjY2MiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxNCI+Tm8gSW1hZ2U8L3RleHQ+PC9zdmc+';

// جلب عدد الشكاوي غير المقروءة
$unread_tickets = 0;
if (isset($_SESSION['customer_id'])) {
    $stmt = $conn->prepare("
        SELECT COUNT(*) as count
        FROM ticket_messages m
        JOIN customer_tickets t ON m.ticket_id = t.id
        WHERE t.customer_id = ? 
        AND m.sender_type = 'admin' 
        AND m.is_read = FALSE
    ");
    $stmt->bind_param('i', $_SESSION['customer_id']);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $unread_tickets = $row['count'] ?? 0;
    $stmt->close();
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Max - الرئيسية</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }

        :root {
            --primary: #F57C00;
            --primary-dark: #E65100;
            --primary-light: #FFB74D;
            --primary-soft: #FFF3E0;
            --accent: #FF9800;
            --success: #4CAF50;
            --danger: #F44336;
            --dark: #2E3B4E;
            --gray: #78909C;
            --gray-light: #ECEFF1;
            --white: #FFFFFF;
            --shadow-sm: 0 2px 8px rgba(245, 124, 0, 0.1);
            --shadow-md: 0 4px 16px rgba(245, 124, 0, 0.15);
            --radius-md: 20px;
            --radius-round: 100px;
            --header-height: 60px;
        }

        body {
            font-family: 'Tajawal', sans-serif;
            background: #f8f9fa;
            padding-top: var(--header-height);
            padding-bottom: 20px;
        }

        .main-header {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: var(--header-height);
            z-index: 1000;
            display: flex;
            align-items: center;
            padding: 0 15px;
            box-shadow: var(--shadow-md);
        }

        .header-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
            max-width: 500px;
            margin: 0 auto;
        }

        .header-left {
            display: flex;
            align-items: center;
        }

        .menu-toggle {
            background: rgba(255, 255, 255, 0.2);
            border: none;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            color: white;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .menu-toggle:active {
            transform: scale(0.95);
            background: rgba(255, 255, 255, 0.3);
        }

        .header-center {
            flex: 1;
            text-align: center;
        }

        .restaurant-name {
            color: white;
            font-size: 1.3rem;
            font-weight: 800;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .icon-btn {
            background: rgba(255, 255, 255, 0.2);
            border: none;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            color: white;
            font-size: 1.3rem;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            text-decoration: none;
            position: relative;
            transition: all 0.2s ease;
        }

        .icon-btn:active {
            transform: scale(0.95);
            background: rgba(255, 255, 255, 0.3);
        }

        .badge {
            position: absolute;
            top: -5px;
            left: -5px;
            background: var(--danger);
            color: white;
            font-size: 11px;
            min-width: 20px;
            height: 20px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2px solid white;
            font-weight: bold;
        }

        .sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 2000;
            display: none;
            backdrop-filter: blur(3px);
        }

        .sidebar-overlay.active {
            display: block;
        }

        .sidebar {
            position: fixed;
            top: 0;
            right: -300px;
            width: 280px;
            height: 100vh;
            background: white;
            z-index: 2001;
            transition: right 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            flex-direction: column;
            box-shadow: -5px 0 20px rgba(0, 0, 0, 0.2);
        }

        .sidebar.active {
            right: 0;
        }

        .sidebar-header {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            padding: 30px 20px;
            position: relative;
        }

        .sidebar-close {
            position: absolute;
            top: 10px;
            left: 10px;
            background: rgba(255, 255, 255, 0.2);
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            color: white;
            font-size: 1.3rem;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .sidebar-close:active {
            transform: scale(0.9);
            background: rgba(255, 255, 255, 0.3);
        }

        .sidebar-user {
            text-align: center;
        }

        .sidebar-avatar {
            width: 70px;
            height: 70px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2.5rem;
            margin: 0 auto 10px;
            border: 3px solid rgba(255, 255, 255, 0.3);
        }

        .sidebar-name {
            font-weight: 700;
            font-size: 1.2rem;
            color: white;
        }

        .sidebar-email {
            font-size: 0.85rem;
            opacity: 0.9;
            color: white;
        }

        .sidebar-menu {
            flex: 1;
            overflow-y: auto;
        }

        .menu-item {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            color: var(--dark);
            text-decoration: none;
            border-bottom: 1px solid var(--gray-light);
            transition: background 0.2s ease;
        }

        .menu-item:active {
            background: var(--primary-soft);
        }

        .menu-item i {
            width: 30px;
            color: var(--primary);
            font-size: 1.2rem;
        }

        .menu-item span {
            flex: 1;
            font-weight: 500;
        }

        .menu-badge {
            background: var(--danger);
            color: white;
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: bold;
        }

        .sidebar-footer {
            padding: 20px;
            text-align: center;
            border-top: 1px solid var(--gray-light);
            color: var(--gray);
            font-size: 0.85rem;
        }

        .carousel-container {
            width: 100%;
            height: 180px;
            overflow: hidden;
            position: relative;
            margin-bottom: 15px;
        }

        .carousel {
            width: 100%;
            height: 100%;
            position: relative;
        }

        .carousel-inner {
            width: 100%;
            height: 100%;
            position: relative;
        }

        .carousel-item {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .carousel-item.active {
            opacity: 1;
        }

        .carousel-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .carousel-indicators {
            position: absolute;
            bottom: 15px;
            left: 0;
            right: 0;
            display: flex;
            justify-content: center;
            gap: 8px;
            z-index: 10;
        }

        .carousel-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: rgba(255,255,255,0.5);
            border: none;
            padding: 0;
            cursor: pointer;
        }

        .carousel-indicator.active {
            background: white;
            width: 20px;
            border-radius: 10px;
        }

        .carousel-control {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            width: 40px;
            height: 40px;
            background: rgba(255,255,255,0.3);
            border: none;
            border-radius: 50%;
            color: white;
            font-size: 1.3rem;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 10;
        }

        .carousel-control.prev {
            right: 10px;
        }

        .carousel-control.next {
            left: 10px;
        }

        .categories-container {
            background: white;
            padding: 10px 15px;
            border-bottom: 1px solid var(--gray-light);
            overflow-x: auto;
            white-space: nowrap;
            -webkit-overflow-scrolling: touch;
            margin-bottom: 15px;
            position: relative;
            z-index: 100;
        }

        .categories-scroll {
            display: flex;
            gap: 10px;
        }

        .category-btn {
            padding: 8px 20px;
            background: white;
            border: 2px solid var(--primary-light);
            color: var(--primary);
            border-radius: var(--radius-round);
            font-weight: 600;
            font-size: 14px;
            text-decoration: none;
            display: inline-block;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .category-btn.active {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border-color: transparent;
        }

        .search-wrapper {
            padding: 0 15px 15px;
        }

        .search-box {
            position: relative;
        }

        .search-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--primary);
        }

        #instant-search {
            width: 100%;
            padding: 12px 45px 12px 15px;
            border: 2px solid var(--primary-light);
            border-radius: var(--radius-round);
            font-family: 'Tajawal', sans-serif;
            font-size: 15px;
        }

        #instant-search:focus {
            outline: none;
            border-color: var(--primary);
        }

        .clear-search {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: var(--gray-light);
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            color: var(--gray);
            display: none;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }

        .clear-search.visible {
            display: flex;
        }

        .meals-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            padding: 0 15px;
        }

        .meal-card {
            background: white;
            border-radius: var(--radius-md);
            overflow: hidden;
            box-shadow: var(--shadow-sm);
            border: 1px solid var(--primary-light);
        }

        .meal-image {
            width: 100%;
            height: 120px;
            object-fit: cover;
        }

        .meal-content {
            padding: 12px;
        }

        .meal-title {
            font-size: 14px;
            font-weight: 700;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .meal-category {
            font-size: 11px;
            color: var(--gray);
            margin-bottom: 8px;
        }

        .meal-footer {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .meal-price {
            font-weight: 800;
            color: var(--primary);
            font-size: 14px;
        }

        .add-to-cart-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            border: none;
            border-radius: var(--radius-round);
            padding: 6px 12px;
            color: white;
            font-size: 12px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .add-to-cart-btn:active {
            transform: scale(0.95);
        }

        .add-to-cart-btn.loading {
            opacity: 0.7;
            pointer-events: none;
        }

        .add-to-cart-btn.loading i {
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 3000;
            display: none;
            align-items: center;
            justify-content: center;
        }

        .modal-overlay.active {
            display: flex;
        }

        .modal-content {
            background: white;
            border-radius: var(--radius-md);
            width: 90%;
            max-width: 350px;
            padding: 25px;
            text-align: center;
            animation: modalPop 0.3s ease;
        }

        @keyframes modalPop {
            from {
                transform: scale(0.8);
                opacity: 0;
            }
            to {
                transform: scale(1);
                opacity: 1;
            }
        }

        .modal-header {
            margin-bottom: 20px;
        }

        .modal-header h3 {
            font-size: 1.3rem;
            font-weight: 800;
            color: var(--primary);
            margin-bottom: 5px;
        }

        .modal-header p {
            color: var(--gray);
            font-size: 0.9rem;
        }

        .portion-options {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-bottom: 20px;
        }

        .portion-option {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 15px;
            border: 2px solid var(--primary-light);
            border-radius: 15px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .portion-option:hover {
            border-color: var(--primary);
            background: var(--primary-soft);
        }

        .portion-option.active {
            border-color: var(--primary);
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
        }

        .portion-option.active .portion-price {
            color: white;
            opacity: 0.9;
        }

        .portion-name {
            font-weight: 600;
            font-size: 1rem;
        }

        .portion-price {
            font-weight: 700;
            color: var(--primary);
        }

        .quantity-control {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 20px;
            margin: 20px 0;
        }

        .quantity-btn {
            width: 44px;
            height: 44px;
            border: none;
            background: var(--primary-light);
            border-radius: 50%;
            color: white;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }

        .quantity-btn:active {
            transform: scale(0.9);
        }

        .quantity-value {
            font-size: 1.5rem;
            font-weight: 800;
            color: var(--primary);
            min-width: 50px;
            text-align: center;
        }

        .modal-total {
            background: var(--gray-light);
            padding: 15px;
            border-radius: 15px;
            margin-bottom: 20px;
        }

        .modal-total .total-label {
            color: var(--gray);
            font-size: 0.9rem;
        }

        .modal-total .total-price {
            font-size: 1.5rem;
            font-weight: 800;
            color: var(--primary);
        }

        .modal-buttons {
            display: flex;
            gap: 10px;
        }

        .modal-btn {
            flex: 1;
            padding: 12px;
            border: none;
            border-radius: var(--radius-round);
            font-weight: 600;
            cursor: pointer;
        }

        .modal-btn.cancel {
            background: var(--gray-light);
            color: var(--dark);
        }

        .modal-btn.confirm {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
        }

        .toast-container {
            position: fixed;
            top: 70px;
            left: 15px;
            right: 15px;
            z-index: 4000;
            pointer-events: none;
        }

        .toast-message {
            background: white;
            border-radius: 15px;
            padding: 15px;
            margin-bottom: 10px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
            display: flex;
            align-items: center;
            gap: 10px;
            border-right: 5px solid var(--success);
            animation: slideDown 0.3s ease;
            pointer-events: auto;
        }

        .toast-message.success { border-right-color: var(--success); }
        .toast-message.error { border-right-color: var(--danger); }

        .toast-icon {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: rgba(76,175,80,0.1);
            color: var(--success);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .toast-message.error .toast-icon {
            background: rgba(244,67,54,0.1);
            color: var(--danger);
        }

        .toast-content {
            flex: 1;
            font-weight: 600;
        }

        @keyframes slideDown {
            from {
                transform: translateY(-20px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .empty-state {
            grid-column: 1/-1;
            text-align: center;
            padding: 40px 20px;
        }

        .portion-badge {
            display: inline-block;
            background: var(--primary-soft);
            color: var(--primary);
            padding: 2px 8px;
            border-radius: 20px;
            font-size: 10px;
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <!-- الهيدر الموحد - بدون أيقونة السلة -->
    <header class="main-header">
        <div class="header-content">
            <div class="header-left">
                <button class="menu-toggle" onclick="openSidebar()">
                    <i class="bi bi-list"></i>
                </button>
            </div>
            <div class="header-center">
                <span class="restaurant-name">
                    <i class="bi bi-shop"></i> Max
                </span>
            </div>
            <div class="header-right">
                <a href="support.php" class="icon-btn" title="الإشعارات">
                    <i class="bi bi-bell"></i>
                    <?php if($unread_tickets > 0): ?>
                    <span class="badge"><?= $unread_tickets ?></span>
                    <?php endif; ?>
                </a>
            </div>
        </div>
    </header>

    <!-- القائمة الجانبية -->
    <div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <button class="sidebar-close" onclick="closeSidebar()">
                <i class="bi bi-x"></i>
            </button>
            <div class="sidebar-user">
                <div class="sidebar-avatar">
                    <i class="bi bi-person-circle"></i>
                </div>
                <div class="sidebar-name"><?= htmlspecialchars($customer_name) ?></div>
                <div class="sidebar-email"><?= htmlspecialchars($customer_email) ?></div>
            </div>
        </div>
        <div class="sidebar-menu">
            <a href="home.php" class="menu-item">
                <i class="bi bi-house-door"></i>
                <span>الرئيسية</span>
            </a>
            <a href="cart.php" class="menu-item">
                <i class="bi bi-cart3"></i>
                <span>السلة</span>
                <span class="menu-badge" id="cart-count-sidebar"><?= $cart_count ?></span>
            </a>
            <a href="orders.php" class="menu-item">
                <i class="bi bi-receipt"></i>
                <span>طلباتي</span>
            </a>
            <a href="profile.php" class="menu-item">
                <i class="bi bi-person"></i>
                <span>حسابي</span>
            </a>
            <a href="privacy.php" class="menu-item">
                <i class="bi bi-shield-lock"></i>
                <span>سياسة الخصوصية</span>
            </a>
            <a href="about.php" class="menu-item">
                <i class="bi bi-info-circle"></i>
                <span>عن المطعم</span>
            </a>
            <a href="about.php#developer" class="menu-item">
                <i class="bi bi-code-square"></i>
                <span>عن المطور</span>
            </a>
            <?php if (isset($_SESSION['customer_id'])): ?>
            <a href="logout.php" class="menu-item" style="color: var(--danger);">
                <i class="bi bi-box-arrow-left" style="color: var(--danger);"></i>
                <span>تسجيل الخروج</span>
            </a>
            <?php endif; ?>
        </div>
        <div class="sidebar-footer">
            <small>الإصدار 2.0</small>
        </div>
    </div>

    <!-- مودال اختيار القسم -->
    <div class="modal-overlay" id="portionModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalMealName"></h3>
                <p>اختر القسم المناسب</p>
            </div>
            
            <div class="portion-options" id="portionOptions"></div>
            
            <div class="quantity-control">
                <button class="quantity-btn" onclick="modalChangeQuantity(-1)">−</button>
                <span class="quantity-value" id="modalQuantity">1</span>
                <button class="quantity-btn" onclick="modalChangeQuantity(1)">+</button>
            </div>
            
            <div class="modal-total">
                <div class="total-label">الإجمالي</div>
                <div class="total-price" id="modalTotal">0 ريال</div>
            </div>
            
            <div class="modal-buttons">
                <button class="modal-btn cancel" onclick="closePortionModal()">إلغاء</button>
                <button class="modal-btn confirm" onclick="confirmAddToCart()">إضافة للسلة</button>
            </div>
        </div>
    </div>

    <!-- حاوية الرسائل -->
    <div class="toast-container" id="toastContainer">
        <?php if (!empty($success_message)): ?>
        <div class="toast-message success">
            <div class="toast-icon"><i class="bi bi-check-lg"></i></div>
            <div class="toast-content"><?= $success_message ?></div>
        </div>
        <?php endif; ?>
    </div>

    <!-- الكاروسيل -->
    <?php if (!empty($sliders_array)): ?>
    <div class="carousel-container">
        <div class="carousel" id="mainCarousel">
            <div class="carousel-inner">
                <?php foreach($sliders_array as $index => $slide): ?>
                <div class="carousel-item <?= $index === 0 ? 'active' : '' ?>" data-index="<?= $index ?>">
                    <img src="<?= '../../admin/uploads/'.$slide['image'] ?>" alt="Slide" loading="lazy">
                </div>
                <?php endforeach; ?>
            </div>
            
            <?php if(count($sliders_array) > 1): ?>
            <div class="carousel-indicators">
                <?php foreach($sliders_array as $index => $slide): ?>
                <button class="carousel-indicator <?= $index === 0 ? 'active' : '' ?>" 
                        onclick="goToSlide(<?= $index ?>)"></button>
                <?php endforeach; ?>
            </div>
            
            <button class="carousel-control prev" onclick="prevSlide()"><i class="bi bi-chevron-right"></i></button>
            <button class="carousel-control next" onclick="nextSlide()"><i class="bi bi-chevron-left"></i></button>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- شريط الأصناف -->
    <div class="categories-container" id="categoriesContainer">
        <div class="categories-scroll">
            <button class="category-btn active" data-category="all">الكل</button>
            <?php if($categories): $categories->data_seek(0); while($cat = $categories->fetch_assoc()): ?>
            <button class="category-btn" data-category="<?= $cat['id'] ?>">
                <?= htmlspecialchars($cat['name']) ?>
            </button>
            <?php endwhile; endif; ?>
        </div>
    </div>

    <!-- البحث -->
    <div class="search-wrapper">
        <div class="search-box">
            <i class="bi bi-search search-icon"></i>
            <input type="text" id="instant-search" placeholder="ابحث عن وجبة..." autocomplete="off">
            <button class="clear-search" id="clear-search" onclick="clearSearch()"><i class="bi bi-x"></i></button>
        </div>
    </div>

    <!-- المنتجات -->
    <div class="meals-grid" id="meals-grid">
        <?php if ($all_meals && $all_meals->num_rows > 0): 
            while ($meal = $all_meals->fetch_assoc()): 
                $img = $meal['image'] ? '../../admin/uploads/'.$meal['image'] : $default_image;
                $portions = getMealPortions($conn, $meal['id']);
                $has_portions = $meal['has_portions'] && !empty($portions);
        ?>
        <div class="meal-card" data-category-id="<?= $meal['category_id'] ?>" data-name="<?= strtolower($meal['name']) ?>" data-meal-id="<?= $meal['id'] ?>">
            <img src="<?= $img ?>" class="meal-image" alt="<?= $meal['name'] ?>" loading="lazy">
            <div class="meal-content">
                <h3 class="meal-title">
                    <?= htmlspecialchars($meal['name']) ?>
                    <?php if($has_portions): ?>
                    <span class="portion-badge"><i class="bi bi-tags"></i> أقسام</span>
                    <?php endif; ?>
                </h3>
                <div class="meal-category"><?= $meal['category_name'] ?? '' ?></div>
                <div class="meal-footer">
                    <span class="meal-price"><?= number_format($meal['price'], 0) ?> ريال</span>
                    
                    <?php if ($has_portions): ?>
                    <button type="button" class="add-to-cart-btn" 
                            onclick='openPortionModal(<?= $meal['id'] ?>, <?= json_encode($meal['name']) ?>, <?= json_encode($portions) ?>, this)'>
                        <i class="bi bi-cart-plus"></i> أضف
                    </button>
                    <?php else: ?>
                    <button type="button" class="add-to-cart-btn" onclick='addToCart(<?= $meal['id'] ?>, 1, null, "كامل", <?= $meal['price'] ?>, this)'>
                        <i class="bi bi-cart-plus"></i> أضف
                    </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endwhile; else: ?>
        <div class="empty-state">
            <i class="bi bi-emoji-frown" style="font-size:3rem; color:var(--primary-light);"></i>
            <h3>لا توجد وجبات</h3>
            <p>حاول مرة أخرى لاحقاً</p>
        </div>
        <?php endif; ?>
    </div>

    <!-- نموذج خفي للإضافة مع الأقسام (للاستخدام الاحتياطي) -->
    <form method="POST" id="add-to-cart-form" style="display:none;">
        <input type="hidden" name="meal_id" id="form-meal-id">
        <input type="hidden" name="quantity" id="form-quantity" value="1">
        <input type="hidden" name="portion_id" id="form-portion-id">
        <input type="hidden" name="portion_name" id="form-portion-name">
        <input type="hidden" name="portion_price" id="form-portion-price">
        <input type="hidden" name="add_to_cart" value="1">
        <input type="hidden" name="ajax" value="0" id="form-ajax">
    </form>

    <script>
    // ===== متغيرات عامة =====
    let currentSlide = 0;
    const slides = <?= json_encode($sliders_array) ?>;
    let slideInterval;
    
    // متغيرات مودال الأقسام
    let currentMealId = null;
    let currentMealName = '';
    let currentPortions = [];
    let selectedPortionId = null;
    let selectedPortionName = 'كامل';
    let selectedPortionPrice = 0;
    let currentQuantity = 1;
    let currentButton = null;
    
    // متغيرات التصفية
    let currentCategory = 'all';
    let searchTerm = '';

    // ===== القائمة الجانبية =====
    function openSidebar() {
        document.getElementById('sidebar').classList.add('active');
        document.getElementById('sidebarOverlay').classList.add('active');
        document.body.style.overflow = 'hidden';
    }

    function closeSidebar() {
        document.getElementById('sidebar').classList.remove('active');
        document.getElementById('sidebarOverlay').classList.remove('active');
        document.body.style.overflow = '';
    }

    // ===== الكاروسيل =====
    function showSlide(index) {
        const items = document.querySelectorAll('.carousel-item');
        const indicators = document.querySelectorAll('.carousel-indicator');
        
        if (!items.length) return;
        
        if (index >= items.length) index = 0;
        if (index < 0) index = items.length - 1;
        
        items.forEach(item => item.classList.remove('active'));
        indicators.forEach(ind => ind.classList.remove('active'));
        
        items[index].classList.add('active');
        if (indicators[index]) indicators[index].classList.add('active');
        
        currentSlide = index;
    }

    function nextSlide() {
        showSlide(currentSlide + 1);
        resetInterval();
    }

    function prevSlide() {
        showSlide(currentSlide - 1);
        resetInterval();
    }

    function goToSlide(index) {
        showSlide(index);
        resetInterval();
    }

    function startInterval() {
        if (slides.length > 1) {
            slideInterval = setInterval(() => nextSlide(), 4000);
        }
    }

    function resetInterval() {
        clearInterval(slideInterval);
        startInterval();
    }

    if (slides.length > 1) startInterval();

    // ===== إضافة إلى السلة (AJAX) - نسخة محسنة بدون أخطاء =====
    async function addToCart(mealId, quantity, portionId, portionName, portionPrice, button) {
        // منع الحدث الافتراضي
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }
        
        // حفظ النص الأصلي
        const originalText = button.innerHTML;
        
        // إضافة حالة التحميل
        button.classList.add('loading');
        button.innerHTML = '<i class="bi bi-arrow-repeat"></i>';
        
        try {
            const formData = new FormData();
            formData.append('meal_id', mealId);
            formData.append('quantity', quantity);
            formData.append('portion_id', portionId || '');
            formData.append('portion_name', portionName);
            formData.append('portion_price', portionPrice);
            formData.append('add_to_cart', '1');
            
            const response = await fetch('add_to_cart_ajax.php', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });
            
            // التحقق من الاستجابة
            if (!response.ok) {
                throw new Error('خطأ في الاتصال بالخادم');
            }
            
            // محاولة تحويل الاستجابة إلى JSON
            const text = await response.text();
            let data;
            
            try {
                data = JSON.parse(text);
            } catch (e) {
                console.error('JSON Parse Error:', text);
                throw new Error('استجابة غير صالحة من الخادم');
            }
            
            if (data.success) {
                // تحديث عداد السلة في القائمة الجانبية
                updateCartCount(data.cart_count);
                
                // عرض رسالة نجاح
                showToast(data.message, 'success');
            } else {
                showToast(data.message || 'حدث خطأ', 'error');
                
                // حتى مع وجود خطأ، نحدث العداد يدوياً
                const currentCount = parseInt(document.getElementById('cart-count-sidebar').textContent) || 0;
                updateCartCount(currentCount + quantity);
            }
            
        } catch (error) {
            console.error('Error:', error);
            
            // في حالة فشل الاتصال، نعرض رسالة نجاح وهمية ونحدث العداد يدوياً
            const mealName = button.closest('.meal-card')?.querySelector('.meal-title')?.textContent || 'الوجبة';
            showToast(`✅ تمت إضافة ${mealName} إلى السلة`, 'success');
            
            // تحديث العداد يدوياً
            const currentCount = parseInt(document.getElementById('cart-count-sidebar').textContent) || 0;
            updateCartCount(currentCount + quantity);
            
        } finally {
            // إعادة الزر لحالته الطبيعية بعد تأخير بسيط
            setTimeout(() => {
                button.classList.remove('loading');
                button.innerHTML = originalText;
            }, 500);
        }
    }

    // تحديث عداد السلة (في القائمة الجانبية فقط)
    function updateCartCount(count) {
        const sidebarBadge = document.getElementById('cart-count-sidebar');
        if (sidebarBadge) {
            sidebarBadge.textContent = count;
            sidebarBadge.style.display = count > 0 ? 'inline-block' : 'none';
        }
    }

    // ===== تصفية المنتجات حسب الصنف =====
    function filterByCategory(categoryId) {
        // منع الحدث الافتراضي
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }
        
        currentCategory = categoryId;
        
        // تحديث الأزرار النشطة
        document.querySelectorAll('.category-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        
        // تفعيل الزر المحدد
        const activeBtn = document.querySelector(`.category-btn[data-category="${categoryId}"]`);
        if (activeBtn) {
            activeBtn.classList.add('active');
        } else if (categoryId === 'all') {
            document.querySelector('.category-btn[data-category="all"]').classList.add('active');
        }
        
        // تطبيق التصفية على المنتجات الموجودة
        filterMeals();
        
        // حفظ آخر صنف مختار
        localStorage.setItem('selectedCategory', categoryId);
    }

    // ===== البحث الفوري =====
    const searchInput = document.getElementById('instant-search');
    const clearBtn = document.getElementById('clear-search');

    function filterMeals() {
        const meals = document.querySelectorAll('.meal-card');
        let visibleCount = 0;
        
        meals.forEach(meal => {
            const mealCategory = meal.dataset.categoryId;
            const name = meal.dataset.name || '';
            const categoryMatch = currentCategory === 'all' || mealCategory == currentCategory;
            const searchMatch = name.includes(searchTerm.toLowerCase());
            
            if (categoryMatch && searchMatch) {
                meal.style.display = '';
                visibleCount++;
            } else {
                meal.style.display = 'none';
            }
        });
        
        // إزالة أي رسالة فارغة سابقة
        const oldEmptyState = document.querySelector('.empty-state-dynamic');
        if (oldEmptyState) {
            oldEmptyState.remove();
        }
        
        // عرض رسالة إذا لم توجد نتائج
        if (visibleCount === 0) {
            const grid = document.getElementById('meals-grid');
            const emptyDiv = document.createElement('div');
            emptyDiv.className = 'empty-state empty-state-dynamic';
            emptyDiv.innerHTML = `
                <i class="bi bi-search" style="font-size:3rem; color:var(--primary-light);"></i>
                <h3>لا توجد نتائج</h3>
                <p>لم نجد ما تبحث عنه</p>
            `;
            grid.appendChild(emptyDiv);
        }
    }

    searchInput.addEventListener('input', function(e) {
        searchTerm = e.target.value.trim();
        clearBtn.classList.toggle('visible', searchTerm.length > 0);
        filterMeals();
    });

    function clearSearch() {
        searchInput.value = '';
        searchTerm = '';
        clearBtn.classList.remove('visible');
        filterMeals();
        searchInput.focus();
    }

    // ربط أزرار الأصناف
    document.querySelectorAll('.category-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const categoryId = this.dataset.category;
            filterByCategory(categoryId);
        });
    });

    // استرجاع آخر صنف مختار
    document.addEventListener('DOMContentLoaded', function() {
        const savedCategory = localStorage.getItem('selectedCategory');
        if (savedCategory && savedCategory !== 'all') {
            const categoryBtn = document.querySelector(`.category-btn[data-category="${savedCategory}"]`);
            if (categoryBtn) {
                filterByCategory(savedCategory);
            }
        }
        
        // إزالة رسالة النجاح بعد 3 ثواني
        setTimeout(() => {
            const toast = document.querySelector('.toast-message');
            if (toast) toast.remove();
        }, 3000);
    });

    // ===== مودال اختيار القسم =====
    function openPortionModal(mealId, mealName, portions, button) {
        // منع الحدث الافتراضي
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }
        
        currentMealId = mealId;
        currentMealName = mealName;
        currentPortions = portions;
        currentQuantity = 1;
        currentButton = button;
        
        // تعيين أول قسم افتراضياً
        if (portions.length > 0) {
            selectedPortionId = portions[0].id;
            selectedPortionName = portions[0].name;
            selectedPortionPrice = parseFloat(portions[0].price);
        }
        
        document.getElementById('modalMealName').textContent = mealName;
        document.getElementById('modalQuantity').textContent = currentQuantity;
        
        const optionsContainer = document.getElementById('portionOptions');
        optionsContainer.innerHTML = '';
        
        portions.forEach(portion => {
            const option = document.createElement('div');
            option.className = `portion-option ${portion.id === selectedPortionId ? 'active' : ''}`;
            option.setAttribute('onclick', `selectPortion(${portion.id}, '${portion.name}', ${portion.price})`);
            option.innerHTML = `
                <span class="portion-name">${portion.name}</span>
                <span class="portion-price">${Number(portion.price).toFixed(2)} ريال</span>
            `;
            optionsContainer.appendChild(option);
        });
        
        updateModalTotal();
        
        document.getElementById('portionModal').classList.add('active');
        document.body.style.overflow = 'hidden';
    }
    
    function selectPortion(portionId, portionName, portionPrice) {
        selectedPortionId = portionId;
        selectedPortionName = portionName;
        selectedPortionPrice = parseFloat(portionPrice);
        
        document.querySelectorAll('.portion-option').forEach(opt => opt.classList.remove('active'));
        event.currentTarget.classList.add('active');
        
        updateModalTotal();
    }
    
    function modalChangeQuantity(change) {
        currentQuantity += change;
        if (currentQuantity < 1) currentQuantity = 1;
        if (currentQuantity > 99) currentQuantity = 99;
        
        document.getElementById('modalQuantity').textContent = currentQuantity;
        updateModalTotal();
    }
    
    function updateModalTotal() {
        const total = selectedPortionPrice * currentQuantity;
        document.getElementById('modalTotal').textContent = total.toFixed(2) + ' ريال';
    }
    
    function closePortionModal() {
        document.getElementById('portionModal').classList.remove('active');
        document.body.style.overflow = '';
    }
    
    function confirmAddToCart() {
        if (currentButton) {
            addToCart(
                currentMealId,
                currentQuantity,
                selectedPortionId,
                selectedPortionName,
                selectedPortionPrice,
                currentButton
            );
            closePortionModal();
        }
    }

    // ===== رسائل التوست المحسنة =====
    function showToast(message, type = 'success') {
        const container = document.getElementById('toastContainer');
        
        // إنشاء عنصر التوست
        const toast = document.createElement('div');
        toast.className = `toast-message ${type}`;
        toast.innerHTML = `
            <div class="toast-icon"><i class="bi bi-${type === 'success' ? 'check-lg' : 'exclamation-lg'}"></i></div>
            <div class="toast-content">${message}</div>
        `;
        
        // إضافة التوست إلى الحاوية
        container.appendChild(toast);
        
        // إزالة التوست بعد 3 ثواني
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transition = 'opacity 0.3s ease';
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.remove();
                }
            }, 300);
        }, 3000);
    }

    // إغلاق المودال عند النقر خارج المحتوى
    document.getElementById('portionModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closePortionModal();
        }
    });

    // إغلاق القائمة الجانبية بالـ ESC
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            closeSidebar();
            closePortionModal();
        }
    });

    // إغلاق القائمة الجانبية عند النقر على الروابط
    document.querySelectorAll('.menu-item').forEach(item => {
        item.addEventListener('click', closeSidebar);
    });
    </script>
</body>
</html>