<?php
// cart.php - نسخة مع إصلاح أخطاء undefined variables
include 'config.php';
checkCustomerAuth();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// تهيئة السلة
if (!isset($_SESSION['cart']) || !is_array($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// تسجيل محتويات السلة للتصحيح
error_log("=== CART CONTENTS ===");
error_log(print_r($_SESSION['cart'], true));

// معالجة تحديث السلة
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // حذف عنصر من السلة
    if (isset($_POST['remove_item'])) {
        $item_index = (int)$_POST['item_index'];
        if (isset($_SESSION['cart'][$item_index])) {
            unset($_SESSION['cart'][$item_index]);
            $_SESSION['cart'] = array_values($_SESSION['cart']);
            $_SESSION['success_message'] = "✅ تم حذف المنتج من السلة";
        }
        header('Location: cart.php');
        exit();
    }
    
    // تحديث الكميات
    if (isset($_POST['update_cart'])) {
        if (isset($_POST['quantity']) && is_array($_POST['quantity'])) {
            foreach ($_POST['quantity'] as $index => $quantity) {
                $index = (int)$index;
                $quantity = (int)$quantity;
                
                if (isset($_SESSION['cart'][$index])) {
                    if ($quantity <= 0) {
                        unset($_SESSION['cart'][$index]);
                    } else {
                        $_SESSION['cart'][$index]['quantity'] = $quantity;
                    }
                }
            }
            $_SESSION['cart'] = array_values($_SESSION['cart']);
            $_SESSION['success_message'] = "🔄 تم تحديث السلة";
        }
        header('Location: cart.php');
        exit();
    }
    
    // تفريغ السلة
    if (isset($_POST['clear_cart'])) {
        $_SESSION['cart'] = [];
        $_SESSION['success_message'] = "🧹 تم تفريغ السلة";
        header('Location: cart.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;
}

// حساب إجمالي السلة وجلب بيانات المنتجات مع الأقسام
$cart_total = 0;
$cart_items = [];
$delivery_fee = $settings['delivery_fee'] ?? 10.00;

if (!empty($_SESSION['cart'])) {
    foreach ($_SESSION['cart'] as $index => $item) {
        if (isset($item['meal_id']) && $item['meal_id'] > 0) {
            // جلب معلومات المنتج من قاعدة البيانات
            $stmt = $conn->prepare("SELECT id, name, price, image, has_portions FROM meals WHERE id = ?");
            $stmt->bind_param('i', $item['meal_id']);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($meal = $result->fetch_assoc()) {
                $quantity = isset($item['quantity']) ? (int)$item['quantity'] : 1;
                
                // تحديد السعر (من القسم أو السعر الأساسي)
                $price = (float)$meal['price'];
                $portion_id = $item['portion_id'] ?? null;
                $portion_name = $item['portion_name'] ?? 'كامل';
                
                // إذا كان هناك قسم محدد، نجلب سعر القسم
                if ($portion_id && $meal['has_portions']) {
                    $portion_stmt = $conn->prepare("SELECT price, name FROM meal_portions WHERE id = ?");
                    $portion_stmt->bind_param('i', $portion_id);
                    $portion_stmt->execute();
                    $portion_result = $portion_stmt->get_result();
                    if ($portion = $portion_result->fetch_assoc()) {
                        $price = (float)$portion['price'];
                        $portion_name = $portion['name'];
                    }
                    $portion_stmt->close();
                }
                
                $subtotal = $price * $quantity;
                $cart_total += $subtotal;
                
                // جلب جميع أقسام هذه الوجبة للتحديث السريع
                $meal_portions = [];
                if ($meal['has_portions']) {
                    $meal_portions = getMealPortions($conn, $meal['id']);
                }
                
                $cart_items[] = [
                    'index' => $index,
                    'id' => $meal['id'],
                    'name' => $meal['name'],
                    'price' => $price,
                    'base_price' => (float)$meal['price'],
                    'quantity' => $quantity,
                    'subtotal' => $subtotal,
                    'image' => $meal['image'],
                    'has_portions' => $meal['has_portions'],
                    'portion_id' => $portion_id,
                    'portion_name' => $portion_name,
                    'portions' => $meal_portions
                ];
            }
            $stmt->close();
        }
    }
}

$final_total = $cart_total + $delivery_fee;

// معلومات العميل - التأكد من وجود قيم افتراضية
$customer_name = isset($_SESSION['customer_name']) ? $_SESSION['customer_name'] : 'زائر';
$customer_email = isset($_SESSION['customer_email']) ? $_SESSION['customer_email'] : '';
$customer_phone = isset($_SESSION['customer_phone']) ? $_SESSION['customer_phone'] : '';
$customer_address = isset($_SESSION['customer_address']) ? $_SESSION['customer_address'] : '';

$cart_count = count($_SESSION['cart']);
$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">
    <!-- Bootstrap Icons (lightweight) -->
    <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;
        }

        /* ===== باقي التنسيقات ===== */
        .page-container {
            padding: 15px;
            max-width: 500px;
            margin: 0 auto;
        }

        .page-title {
            font-size: 1.5rem;
            font-weight: 800;
            color: var(--primary);
            margin-bottom: 20px;
            text-align: center;
        }

        .cart-item {
            background: white;
            border-radius: var(--radius-md);
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: var(--shadow-sm);
            border: 1px solid var(--primary-light);
        }

        .cart-item-row {
            display: flex;
            gap: 15px;
        }

        .cart-item-image {
            width: 80px;
            height: 80px;
            border-radius: 15px;
            object-fit: cover;
        }

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

        .cart-item-title {
            font-size: 16px;
            font-weight: 700;
            margin-bottom: 5px;
        }

        .cart-item-price {
            color: var(--primary);
            font-weight: 700;
            font-size: 15px;
            margin-bottom: 5px;
        }

        .portion-badge {
            display: inline-flex;
            align-items: center;
            background: var(--primary-soft);
            color: var(--primary);
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 8px;
            border: 1px solid var(--primary-light);
        }

        .portion-badge i {
            font-size: 12px;
            margin-left: 4px;
        }

        .portion-selector {
            margin: 10px 0;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .portion-option {
            padding: 6px 12px;
            background: white;
            border: 2px solid var(--primary-light);
            border-radius: 20px;
            font-size: 13px;
            font-weight: 600;
            color: var(--primary);
            cursor: pointer;
            transition: all 0.2s ease;
        }

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

        .portion-option:active {
            transform: scale(0.95);
        }

        .portion-price {
            font-size: 11px;
            margin-right: 4px;
            color: var(--gray);
        }

        .portion-option.active .portion-price {
            color: rgba(255,255,255,0.9);
        }

        .cart-item-controls {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 10px;
        }

        .quantity-control {
            display: flex;
            align-items: center;
            background: var(--gray-light);
            border-radius: var(--radius-round);
            padding: 2px;
        }

        .quantity-btn {
            width: 36px;
            height: 36px;
            border: none;
            background: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            font-weight: bold;
            color: var(--primary);
            cursor: pointer;
            box-shadow: var(--shadow-sm);
        }

        .quantity-value {
            min-width: 40px;
            text-align: center;
            font-weight: 700;
            font-size: 16px;
        }

        .item-subtotal {
            font-weight: 700;
            color: var(--dark);
            font-size: 15px;
        }

        .btn-remove {
            background: none;
            border: none;
            color: var(--danger);
            font-size: 1.3rem;
            cursor: pointer;
            padding: 5px;
        }

        .summary-card {
            background: white;
            border-radius: var(--radius-md);
            padding: 20px;
            margin: 20px 0;
            box-shadow: var(--shadow-sm);
            border: 1px solid var(--primary-light);
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 12px 0;
            border-bottom: 1px solid var(--gray-light);
        }

        .summary-row:last-child {
            border-bottom: none;
            font-weight: 800;
            font-size: 1.2rem;
            color: var(--primary);
        }

        .checkout-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            font-size: 18px;
            font-weight: 700;
            padding: 16px;
            border: none;
            border-radius: var(--radius-round);
            width: 100%;
            margin: 10px 0;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }

        .btn-outline {
            background: transparent;
            border: 2px solid var(--primary);
            color: var(--primary);
            padding: 12px;
            border-radius: var(--radius-round);
            font-weight: 600;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            cursor: pointer;
            text-decoration: none;
        }

        .empty-state {
            text-align: center;
            padding: 50px 20px;
            background: white;
            border-radius: var(--radius-md);
            box-shadow: var(--shadow-sm);
        }

        .empty-icon {
            font-size: 5rem;
            color: var(--primary-light);
            margin-bottom: 20px;
        }

        .empty-title {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 10px;
        }

        .empty-text {
            color: var(--gray);
            margin-bottom: 30px;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            padding: 15px 30px;
            border: none;
            border-radius: var(--radius-round);
            font-weight: 700;
            font-size: 16px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
        }

        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 2000;
            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-icon {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            font-size: 2.5rem;
        }

        .modal-icon.warning {
            background: rgba(244,67,54,0.1);
            color: var(--danger);
        }

        .modal-icon.info {
            background: rgba(245,124,0,0.1);
            color: var(--primary);
        }

        .modal-title {
            font-size: 1.3rem;
            font-weight: 800;
            margin-bottom: 10px;
        }

        .modal-text {
            color: var(--gray);
            margin-bottom: 25px;
        }

        .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: var(--danger);
            color: white;
        }

        .modal-btn.confirm.clear {
            background: var(--primary);
        }

        .toast-container {
            position: fixed;
            top: 70px;
            left: 15px;
            right: 15px;
            z-index: 3000;
        }

        .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;
        }

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

        .toast-icon {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .toast-icon.success {
            background: rgba(76,175,80,0.1);
            color: var(--success);
        }

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

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

        .action-buttons {
            display: flex;
            gap: 10px;
            margin: 20px 0;
        }

        .action-btn {
            flex: 1;
            padding: 12px;
            border: 2px solid var(--primary-light);
            background: white;
            border-radius: var(--radius-round);
            color: var(--primary);
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
            cursor: pointer;
        }

        .action-btn:active {
            background: var(--primary-soft);
        }
    </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>
                <?php if($cart_count > 0): ?>
                <span class="menu-badge"><?= $cart_count ?></span>
                <?php endif; ?>
            </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="confirmModal">
        <div class="modal-content">
            <div class="modal-icon warning" id="modalIcon">
                <i class="bi bi-exclamation-triangle"></i>
            </div>
            <h3 class="modal-title" id="modalTitle">تأكيد الحذف</h3>
            <p class="modal-text" id="modalMessage">هل أنت متأكد من حذف هذا المنتج؟</p>
            <div class="modal-buttons">
                <button class="modal-btn cancel" onclick="closeModal()">إلغاء</button>
                <button class="modal-btn confirm" id="confirmBtn">تأكيد</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"><?= htmlspecialchars($success_message) ?></div>
        </div>
        <script>
            setTimeout(() => {
                document.querySelector('.toast-message')?.remove();
            }, 3000);
        </script>
        <?php endif; ?>
    </div>

    <div class="page-container">
        <h1 class="page-title">سلة التسوق</h1>
        
        <?php if (empty($cart_items)): ?>
            <!-- السلة فارغة -->
            <div class="empty-state">
                <i class="bi bi-cart-x empty-icon"></i>
                <h3 class="empty-title">السلة فارغة</h3>
                <p class="empty-text">لم تقم بإضافة أي منتجات بعد</p>
                <a href="home.php" class="btn-primary">
                    <i class="bi bi-shop"></i> تصفح المنتجات
                </a>
            </div>
        <?php else: ?>
            <!-- عرض المنتجات في السلة -->
            <form method="POST" id="cart-form">
                <?php foreach ($cart_items as $item): ?>
                <div class="cart-item" data-index="<?= $item['index'] ?>">
                    <div class="cart-item-row">
                        <img src="<?= !empty($item['image']) ? '../../admin/uploads/'.$item['image'] : $default_image ?>" 
                             class="cart-item-image" alt="<?= htmlspecialchars($item['name'] ?? '') ?>">
                        
                        <div class="cart-item-details">
                            <h3 class="cart-item-title"><?= htmlspecialchars($item['name'] ?? '') ?></h3>
                            <div class="cart-item-price"><?= number_format($item['price'] ?? 0, 2) ?> ريال</div>
                            
                            <!-- عرض القسم المحدد -->
                            <?php if (!empty($item['has_portions']) && !empty($item['portion_name']) && $item['portion_name'] != 'كامل'): ?>
                            <div class="portion-badge">
                                <i class="bi bi-tag"></i> <?= htmlspecialchars($item['portion_name']) ?>
                            </div>
                            <?php endif; ?>
                            
                            <!-- اختيار الأقسام (يظهر عند النقر) -->
                            <?php if (!empty($item['has_portions']) && !empty($item['portions'])): ?>
                            <div class="portion-selector" id="portion-selector-<?= $item['index'] ?>" style="display: none;">
                                <?php foreach ($item['portions'] as $portion): ?>
                                <button type="button" 
                                        class="portion-option <?= ($portion['id'] == $item['portion_id']) ? 'active' : '' ?>"
                                        onclick="changePortion(<?= $item['index'] ?>, <?= $portion['id'] ?>, '<?= htmlspecialchars($portion['name']) ?>', <?= $portion['price'] ?>)">
                                    <?= htmlspecialchars($portion['name']) ?>
                                    <span class="portion-price">(<?= number_format($portion['price'], 2) ?> ر.ي)</span>
                                </button>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                            
                            <div class="cart-item-controls">
                                <div class="quantity-control">
                                    <button type="button" class="quantity-btn" onclick="changeQuantity(<?= $item['index'] ?>, -1)">−</button>
                                    <span class="quantity-value" id="qty-<?= $item['index'] ?>"><?= (int)($item['quantity'] ?? 1) ?></span>
                                    <button type="button" class="quantity-btn" onclick="changeQuantity(<?= $item['index'] ?>, 1)">+</button>
                                </div>
                                
                                <span class="item-subtotal" id="subtotal-<?= $item['index'] ?>">
                                    <?= number_format($item['subtotal'] ?? 0, 2) ?> ريال
                                </span>
                                
                                <button type="button" class="btn-remove" onclick="showDeleteModal(<?= $item['index'] ?>, '<?= htmlspecialchars($item['name'] ?? '') ?>')">
                                    <i class="bi bi-trash3"></i>
                                </button>
                            </div>
                            
                            <!-- زر تغيير القسم (يظهر فقط إذا كان للوجبة أقسام) -->
                            <?php if (!empty($item['has_portions']) && !empty($item['portions'])): ?>
                            <button type="button" class="btn-outline btn-sm" style="margin-top: 10px; width: 100%;" 
                                    onclick="togglePortionSelector(<?= $item['index'] ?>)">
                                <i class="bi bi-arrow-repeat"></i> تغيير القسم
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- حقول مخفية للتحديث -->
                    <input type="hidden" name="quantity[<?= $item['index'] ?>]" id="input-<?= $item['index'] ?>" value="<?= (int)($item['quantity'] ?? 1) ?>">
                    <input type="hidden" name="portion_id[<?= $item['index'] ?>]" id="portion-id-<?= $item['index'] ?>" value="<?= $item['portion_id'] ?? '' ?>">
                    <input type="hidden" name="portion_name[<?= $item['index'] ?>]" id="portion-name-<?= $item['index'] ?>" value="<?= htmlspecialchars($item['portion_name'] ?? 'كامل') ?>">
                    <input type="hidden" name="portion_price[<?= $item['index'] ?>]" id="portion-price-<?= $item['index'] ?>" value="<?= $item['price'] ?? 0 ?>">
                </div>
                <?php endforeach; ?>
                
                <!-- أزرار الإجراءات -->
                <div class="action-buttons">
                    <button type="button" class="action-btn" onclick="showClearModal()">
                        <i class="bi bi-trash"></i> تفريغ
                    </button>
                </div>
                
                <!-- حقول للنماذج -->
                <input type="hidden" name="update_cart" id="update-cart-input" value="">
                <input type="hidden" name="clear_cart" id="clear-cart-input" value="">
                <input type="hidden" name="remove_item" id="remove-item-input" value="">
                <input type="hidden" name="item_index" id="remove-index-input" value="">
            </form>
            
            <!-- ملخص الطلب -->
            <div class="summary-card">
                <div class="summary-row">
                    <span>مجموع المنتجات</span>
                    <span id="cart-total-display"><?= number_format($cart_total, 2) ?> ريال</span>
                </div>
                <div class="summary-row">
                    <span>رسوم التوصيل</span>
                    <span><?= number_format($delivery_fee, 2) ?> ريال</span>
                </div>
                <div class="summary-row">
                    <strong>الإجمالي الكلي</strong>
                    <strong id="final-total-display"><?= number_format($final_total, 2) ?> ريال</strong>
                </div>
                
                <a href="checkout.php" class="checkout-btn">
                    <i class="bi bi-bag-check"></i> متابعة الطلب
                </a>
            </div>
        <?php endif; ?>
    </div>

    <script>
    // مصفوفة المنتجات للتحديث الفوري
    const cartItems = <?= json_encode($cart_items) ?>;
    const deliveryFee = <?= $delivery_fee ?>;
    
    // متغيرات الموديل
    let currentAction = null;
    let currentIndex = null;
    
    // ===== دوال القائمة الجانبية =====
    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 togglePortionSelector(index) {
        const selector = document.getElementById(`portion-selector-${index}`);
        if (selector) {
            if (selector.style.display === 'none' || selector.style.display === '') {
                selector.style.display = 'flex';
            } else {
                selector.style.display = 'none';
            }
        }
    }
    
    function changePortion(index, portionId, portionName, portionPrice) {
        // تحديث الواجهة
        document.getElementById(`portion-id-${index}`).value = portionId;
        document.getElementById(`portion-name-${index}`).value = portionName;
        document.getElementById(`portion-price-${index}`).value = portionPrice;
        
        // تحديث عرض القسم
        const badge = document.querySelector(`[data-index="${index}"] .portion-badge`);
        if (badge) {
            badge.innerHTML = `<i class="bi bi-tag"></i> ${portionName}`;
        } else {
            // إذا لم يكن هناك badge، نضيف واحداً
            const detailsDiv = document.querySelector(`[data-index="${index}"] .cart-item-details`);
            const newBadge = document.createElement('div');
            newBadge.className = 'portion-badge';
            newBadge.innerHTML = `<i class="bi bi-tag"></i> ${portionName}`;
            detailsDiv.insertBefore(newBadge, detailsDiv.querySelector('.cart-item-controls'));
        }
        
        // تحديث السعر
        const qty = parseInt(document.getElementById(`qty-${index}`).textContent);
        const subtotal = portionPrice * qty;
        document.getElementById(`subtotal-${index}`).textContent = subtotal.toFixed(2) + ' ريال';
        
        // تحديث سعر المنتج في الواجهة
        const priceSpan = document.querySelector(`[data-index="${index}"] .cart-item-price`);
        if (priceSpan) {
            priceSpan.textContent = portionPrice.toFixed(2) + ' ريال';
        }
        
        // تحديث حالة الأزرار
        document.querySelectorAll(`#portion-selector-${index} .portion-option`).forEach(btn => {
            btn.classList.remove('active');
        });
        if (event && event.target) {
            event.target.classList.add('active');
        }
        
        // إخفاء المحدد بعد الاختيار
        const selector = document.getElementById(`portion-selector-${index}`);
        if (selector) {
            selector.style.display = 'none';
        }
        
        // تحديث المجموع الكلي
        updateTotals();
    }
    
    // تغيير الكمية
    function changeQuantity(index, change) {
        const qtySpan = document.getElementById(`qty-${index}`);
        const hiddenInput = document.getElementById(`input-${index}`);
        let qty = parseInt(qtySpan.textContent) + change;
        
        if (qty < 1) qty = 1;
        if (qty > 99) qty = 99;
        
        // تحديث الواجهة
        qtySpan.textContent = qty;
        hiddenInput.value = qty;
        
        // تحديث المجموع الفرعي
        const priceInput = document.getElementById(`portion-price-${index}`);
        const price = parseFloat(priceInput ? priceInput.value : 0) || 0;
        const subtotal = price * qty;
        document.getElementById(`subtotal-${index}`).textContent = subtotal.toFixed(2) + ' ريال';
        
        // تحديث المجموع الكلي
        updateTotals();
    }
    
    // تحديث المجاميع
    function updateTotals() {
        let total = 0;
        
        document.querySelectorAll('[id^="subtotal-"]').forEach(el => {
            const subtotalText = el.textContent.replace(' ريال', '');
            const subtotal = parseFloat(subtotalText) || 0;
            total += subtotal;
        });
        
        document.getElementById('cart-total-display').textContent = total.toFixed(2) + ' ريال';
        document.getElementById('final-total-display').textContent = (total + deliveryFee).toFixed(2) + ' ريال';
    }
    
    // تحديث السلة (إرسال النموذج)
    function updateCart() {
        document.getElementById('update-cart-input').value = '1';
        document.getElementById('cart-form').submit();
    }
    
    // ===== دوال الموديل =====
    function showModal(title, message, icon, confirmText, confirmClass, onConfirm) {
        document.getElementById('modalTitle').textContent = title;
        document.getElementById('modalMessage').textContent = message;
        document.getElementById('modalIcon').innerHTML = `<i class="bi ${icon}"></i>`;
        
        const confirmBtn = document.getElementById('confirmBtn');
        confirmBtn.textContent = confirmText;
        confirmBtn.className = `modal-btn confirm ${confirmClass}`;
        
        // إزالة المستمع القديم وإضافة الجديد
        const newConfirmBtn = confirmBtn.cloneNode(true);
        confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
        
        newConfirmBtn.addEventListener('click', () => {
            onConfirm();
            closeModal();
        });
        
        document.getElementById('confirmModal').classList.add('active');
    }
    
    function closeModal() {
        document.getElementById('confirmModal').classList.remove('active');
    }
    
    // حذف عنصر مع موديل
    function showDeleteModal(index, name) {
        currentIndex = index;
        showModal(
            'تأكيد الحذف',
            `هل أنت متأكد من حذف "${name}" من السلة؟`,
            'bi-trash3',
            'حذف',
            'delete',
            () => {
                document.getElementById('remove-item-input').value = '1';
                document.getElementById('remove-index-input').value = index;
                document.getElementById('cart-form').submit();
            }
        );
    }
    
    // تفريغ السلة مع موديل
    function showClearModal() {
        showModal(
            'تفريغ السلة',
            'هل أنت متأكد من تفريغ السلة بالكامل؟',
            'bi-exclamation-triangle',
            'تفريغ',
            'clear',
            () => {
                document.getElementById('clear-cart-input').value = '1';
                document.getElementById('cart-form').submit();
            }
        );
    }
    
    // إغلاق الموديل عند الضغط خارج المحتوى
    document.getElementById('confirmModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeModal();
        }
    });
    
    // إغلاق الموديل بالضغط على ESC
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeModal();
            closeSidebar();
        }
    });
    
    // إغلاق القائمة الجانبية عند النقر على الروابط
    document.querySelectorAll('.menu-item').forEach(item => {
        item.addEventListener('click', closeSidebar);
    });
    
    // حذف الرسالة بعد 3 ثواني
    setTimeout(() => {
        const toast = document.querySelector('.toast-message');
        if (toast) toast.remove();
    }, 3000);
    </script>
</body>
</html>