<?php
/**
 * cart.php - صفحة سلة التسوق
 * الإصدار: 6.4 - إصلاح مشكلة index
 */

// تعريف الأمان
define('SECURE_ACCESS', true);

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/config.php';

// التحقق من وجود دالة getMealPortions
if (!function_exists('getMealPortions')) {
    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;
    }
}

// التحقق من تسجيل الدخول
if (!isLoggedIn()) {
    $_SESSION['redirect_url'] = 'cart.php';
    $_SESSION['success_message'] = 'الرجاء تسجيل الدخول أولاً';
    header('Location: home.php');
    exit;
}

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

// =============================================
// معالجة طلبات POST
// =============================================
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // حذف عنصر من السلة
    if (isset($_POST['remove_item']) && $_POST['remove_item'] == '1') {
        $item_index = (int)($_POST['item_index'] ?? -1);
        if ($item_index >= 0 && isset($_SESSION['cart'][$item_index])) {
            unset($_SESSION['cart'][$item_index]);
            $_SESSION['cart'] = array_values($_SESSION['cart']);
            $_SESSION['success_message'] = "✅ تم حذف المنتج من السلة";
        }
        header('Location: cart.php');
        exit();
    }
    
    // تحديث القسم (AJAX)
    if (isset($_POST['update_portion']) && $_POST['update_portion'] == '1') {
        header('Content-Type: application/json');
        
        $item_index = (int)($_POST['item_index'] ?? -1);
        $portion_id = (int)($_POST['portion_id'] ?? 0);
        $portion_name = $_POST['portion_name'] ?? 'كامل';
        $portion_price = (float)($_POST['portion_price'] ?? 0);
        
        $success = false;
        $cart_total = 0;
        $cart_count = 0;
        
        if ($item_index >= 0 && isset($_SESSION['cart'][$item_index])) {
            $_SESSION['cart'][$item_index]['portion_id'] = $portion_id;
            $_SESSION['cart'][$item_index]['portion_name'] = $portion_name;
            $_SESSION['cart'][$item_index]['price'] = $portion_price;
            $success = true;
            
            // حساب المجاميع الجديدة
            $delivery_fee = isset($settings['delivery_fee']) ? (float)$settings['delivery_fee'] : 10.00;
            
            foreach ($_SESSION['cart'] as $item) {
                $price = isset($item['price']) ? (float)$item['price'] : 0;
                $quantity = isset($item['quantity']) ? (int)$item['quantity'] : 1;
                $cart_total += $price * $quantity;
                $cart_count += $quantity;
            }
        }
        
        echo json_encode([
            'success' => $success,
            'cart_total' => $cart_total,
            'final_total' => $cart_total + (isset($settings['delivery_fee']) ? (float)$settings['delivery_fee'] : 10.00),
            'cart_count' => $cart_count,
            'new_price' => $portion_price,
            'new_subtotal' => $portion_price * ($_SESSION['cart'][$item_index]['quantity'] ?? 1)
        ]);
        exit();
    }
    
    // تحديث الكمية (AJAX)
    if (isset($_POST['ajax_update']) && $_POST['ajax_update'] == '1') {
        header('Content-Type: application/json');
        
        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']);
            
            $cart_total = 0;
            $cart_count = 0;
            $delivery_fee = isset($settings['delivery_fee']) ? (float)$settings['delivery_fee'] : 10.00;
            $items_data = [];
            
            foreach ($_SESSION['cart'] as $index => $item) {
                $price = isset($item['price']) ? (float)$item['price'] : 0;
                $quantity = isset($item['quantity']) ? (int)$item['quantity'] : 1;
                $subtotal = $price * $quantity;
                $cart_total += $subtotal;
                $cart_count += $quantity;
                
                $items_data[$index] = [
                    'quantity' => $quantity,
                    'subtotal' => $subtotal
                ];
            }
            
            echo json_encode([
                'success' => true,
                'cart_total' => $cart_total,
                'final_total' => $cart_total + $delivery_fee,
                'cart_count' => $cart_count,
                'items' => $items_data
            ]);
        } else {
            echo json_encode(['success' => false]);
        }
        exit();
    }
    
    // تفريغ السلة
    if (isset($_POST['clear_cart']) && $_POST['clear_cart'] == '1') {
        $_SESSION['cart'] = [];
        $_SESSION['success_message'] = "🧹 تم تفريغ السلة";
        header('Location: cart.php');
        exit();
    }
}

// =============================================
// عرض السلة
// =============================================

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

// حساب إجمالي السلة
$cart_total = 0;
$cart_items = [];
$delivery_fee = isset($settings['delivery_fee']) ? (float)$settings['delivery_fee'] : 10.00;

if (!empty($_SESSION['cart'])) {
    // إعادة فهرسة السلة للتأكد من أن الأرقام متسلسلة
    $_SESSION['cart'] = array_values($_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 = ? AND is_active = 1");
            $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 = isset($item['price']) ? (float)$item['price'] : (float)$meal['price'];
                $portion_id = $item['portion_id'] ?? null;
                $portion_name = $item['portion_name'] ?? 'كامل';
                $subtotal = $price * $quantity;
                $cart_total += $subtotal;
                
                $meal_portions = [];
                if ($meal['has_portions']) {
                    $meal_portions = getMealPortions($conn, $meal['id']);
                }
                
                $cart_items[] = [
                    'index' => $index,  // هذا هو فهرس السلة الفعلي (0,1,2...)
                    'cart_key' => $index, // نفس القيمة للتأكيد
                    'id' => $meal['id'],
                    'name' => $meal['name'],
                    'price' => $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 = $_SESSION['customer_name'] ?? 'زائر';
$customer_email = $_SESSION['customer_email'] ?? '';
$customer_id = $_SESSION['customer_id'] ?? 0;
$is_logged_in = isLoggedIn();

$cart_count = 0;
foreach ($_SESSION['cart'] as $item) {
    $cart_count += $item['quantity'] ?? 0;
}

$default_image = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZmNmY2ZjIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGRvbWluYW50LWJhc2VsaW5lPSJtaWRkbGUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZpbGw9IiNjY2NjY2MiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxNCI+Tm8gSW1hZ2U8L3RleHQ+PC9zdmc+';
?>
<!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>
        /* جميع الـ CSS السابق */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

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

        .page-container { 
            padding: 15px; 
            max-width: 500px; 
            margin: 0 auto; 
        }
        
        .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-selector {
            margin: 10px 0;
            display: none;
            flex-wrap: wrap;
            gap: 8px;
            background: var(--gray-light);
            padding: 10px;
            border-radius: 15px;
        }
        
        .portion-selector.show {
            display: flex !important;
        }
        
        .portion-option {
            padding: 8px 15px;
            background: white;
            border: 2px solid var(--primary-light);
            border-radius: 25px;
            font-size: 13px;
            font-weight: 600;
            color: var(--primary);
            cursor: pointer;
            transition: all 0.2s ease;
            flex: 1;
            text-align: center;
            min-width: 80px;
        }
        
        .portion-option.active {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border-color: transparent;
        }
        
        .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;
            transition: all 0.2s ease;
        }
        
        .quantity-btn:active { transform: scale(0.95); }
        .quantity-btn:disabled { opacity: 0.5; cursor: not-allowed; }
        .quantity-value { min-width: 40px; text-align: center; font-weight: 700; }
        .item-subtotal { font-weight: 700; color: var(--dark); }
        
        .btn-remove {
            background: none;
            border: none;
            color: var(--danger);
            font-size: 1.3rem;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .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;
            cursor: pointer;
            text-align: center;
            transition: all 0.2s ease;
        }
        
        .btn-sm { padding: 8px 12px; font-size: 12px; margin-top: 10px; width: 100%; }
        
        .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;
        }
        
        .empty-state {
            text-align: center;
            padding: 50px 20px;
            background: white;
            border-radius: var(--radius-md);
        }
        
        .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;
            text-decoration: none;
            display: inline-block;
        }
        
        .toast-container {
            position: fixed;
            top: 70px;
            left: 15px;
            right: 15px;
            z-index: 4000;
        }
        
        .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;
        }
        
        @keyframes slideDown {
            from { transform: translateY(-20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        
        .update-indicator {
            font-size: 11px;
            color: var(--primary);
            margin-top: 8px;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .update-indicator.visible { opacity: 1; }
        
        .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;
        }
        
        .modal-buttons { display: flex; gap: 10px; margin-top: 20px; }
        
        .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; }
        
        .sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 2000;
            display: none;
        }
        .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;
            display: flex;
            flex-direction: column;
        }
        .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;
            cursor: pointer;
        }
        
        .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;
        }
        
        .menu-item {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            color: var(--dark);
            text-decoration: none;
            border-bottom: 1px solid var(--gray-light);
        }
        
        .menu-item i { width: 30px; color: var(--primary); }
        .menu-badge {
            background: var(--danger);
            color: white;
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 11px;
        }
        
        .page-title {
            font-size: 1.5rem;
            font-weight: 800;
            color: var(--primary);
            margin-bottom: 20px;
            text-align: center;
        }
        
        .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;
        }
        
        .menu-toggle {
            background: rgba(255,255,255,0.2);
            border: none;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            color: white;
            font-size: 1.5rem;
            cursor: pointer;
        }
        
        .restaurant-name {
            color: white;
            font-size: 1.3rem;
            font-weight: 800;
        }
        
        .header-left, .header-right { display: flex; align-items: center; gap: 8px; }
        .header-center { flex: 1; text-align: center; }
    </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-cart3"></i> سلة التسوق
                </span>
            </div>
            <div class="header-right">
                <a href="profile.php" class="icon-btn">
                    <i class="bi bi-person-circle"></i>
                </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>
        </div>
        <div class="sidebar-menu">
            <a href="home.php" class="menu-item"><i class="bi bi-house-door"></i> الرئيسية</a>
            <a href="cart.php" class="menu-item"><i class="bi bi-cart3"></i> السلة</a>
            <a href="orders.php" class="menu-item"><i class="bi bi-receipt"></i> طلباتي</a>
            <a href="profile.php" class="menu-item"><i class="bi bi-person"></i> حسابي</a>
            <a href="logout.php" class="menu-item" style="color: var(--danger);"><i class="bi bi-box-arrow-left"></i> تسجيل الخروج</a>
        </div>
    </div>

    <!-- حاوية الرسائل -->
    <div class="toast-container" id="toastContainer">
        <?php if (!empty($success_message)): ?>
        <div class="toast-message">
            <i class="bi bi-check-lg"></i>
            <span><?= htmlspecialchars($success_message) ?></span>
        </div>
        <?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" style="font-size: 5rem; color: var(--primary-light);"></i>
                <h3 style="margin: 20px 0;">السلة فارغة</h3>
                <a href="home.php" class="btn-primary">تصفح المنتجات</a>
            </div>
        <?php else: ?>
            <div id="cart-items-container">
                <?php foreach ($cart_items as $item): ?>
                <div class="cart-item" data-index="<?= $item['index'] ?>" data-price="<?= $item['price'] ?>">
                    <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" id="price-<?= $item['index'] ?>">
                                <?= number_format($item['price'], 2) ?> ريال
                            </div>
                            
                            <?php if ($item['portion_name'] != 'كامل'): ?>
                            <div class="portion-badge" id="badge-<?= $item['index'] ?>">
                                <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="selector-<?= $item['index'] ?>">
                                <?php foreach ($item['portions'] as $portion): ?>
                                <button type="button" class="portion-option <?= ($portion['id'] == $item['portion_id']) ? 'active' : '' ?>" 
                                        data-portion-id="<?= $portion['id'] ?>"
                                        data-portion-name="<?= htmlspecialchars($portion['name']) ?>"
                                        data-portion-price="<?= $portion['price'] ?>"
                                        onclick="updatePortion(<?= $item['index'] ?>, this)">
                                    <?= htmlspecialchars($portion['name']) ?> (<?= number_format($portion['price'], 2) ?> ر.ي)
                                </button>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                            
                            <div class="cart-item-controls">
                                <div class="quantity-control">
                                    <button type="button" class="quantity-btn" onclick="updateQuantity(<?= $item['index'] ?>, -1)">−</button>
                                    <span class="quantity-value" id="qty-<?= $item['index'] ?>"><?= $item['quantity'] ?></span>
                                    <button type="button" class="quantity-btn" onclick="updateQuantity(<?= $item['index'] ?>, 1)">+</button>
                                </div>
                                <span class="item-subtotal" id="subtotal-<?= $item['index'] ?>">
                                    <?= number_format($item['subtotal'], 2) ?> ريال
                                </span>
                                <button type="button" class="btn-remove" onclick="removeItem(<?= $item['index'] ?>, '<?= addslashes($item['name']) ?>')">
                                    <i class="bi bi-trash3"></i>
                                </button>
                            </div>
                            
                            <div class="update-indicator" id="indicator-<?= $item['index'] ?>">
                                <i class="bi bi-arrow-repeat"></i> جاري التحديث...
                            </div>
                            
                            <?php if (!empty($item['has_portions']) && !empty($item['portions'])): ?>
                            <button type="button" class="action-btn btn-sm" onclick="togglePortionSelector(<?= $item['index'] ?>)">
                                <i class="bi bi-arrow-repeat"></i> تغيير القسم
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                    <input type="hidden" id="input-<?= $item['index'] ?>" value="<?= $item['quantity'] ?>">
                </div>
                <?php endforeach; ?>
            </div>
            
            <div class="action-buttons">
                <button type="button" class="action-btn" onclick="clearCart()">
                    <i class="bi bi-trash"></i> تفريغ السلة
                </button>
            </div>
            
            <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>
            
            <form method="POST" id="cart-form" style="display: none;">
                <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>
        <?php endif; ?>
    </div>

    <!-- مودال التأكيد -->
    <div class="modal-overlay" id="confirmModal">
        <div class="modal-content">
            <h3 id="modalTitle">تأكيد</h3>
            <p 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>

    <script>
    const deliveryFee = <?= $delivery_fee ?>;
    let updateTimeouts = {};
    
    // عرض معلومات السلة للتأكد من صحة البيانات
    console.log('Cart items count:', <?= count($cart_items) ?>);
    <?php foreach ($cart_items as $item): ?>
    console.log('Item index: <?= $item['index'] ?>, name: <?= addslashes($item['name']) ?>, quantity: <?= $item['quantity'] ?>');
    <?php endforeach; ?>
    
    // =============================================
    // دوال القائمة الجانبية
    // =============================================
    function openSidebar() {
        document.getElementById('sidebar').classList.add('active');
        document.getElementById('sidebarOverlay').classList.add('active');
    }

    function closeSidebar() {
        document.getElementById('sidebar').classList.remove('active');
        document.getElementById('sidebarOverlay').classList.remove('active');
    }
    
    // =============================================
    // دوال تحديث القسم
    // =============================================
    function togglePortionSelector(index) {
        console.log('Toggle portion selector for index:', index);
        const selector = document.getElementById(`selector-${index}`);
        if (selector) {
            // إخفاء جميع المحددات أولاً
            document.querySelectorAll('.portion-selector').forEach(sel => {
                sel.classList.remove('show');
            });
            // إظهار المحدد المطلوب
            selector.classList.add('show');
        } else {
            console.log('Selector not found for index:', index);
        }
    }
    
    function updatePortion(index, button) {
        console.log('updatePortion called for index:', index);
        
        const portionId = button.getAttribute('data-portion-id');
        const portionName = button.getAttribute('data-portion-name');
        const portionPrice = parseFloat(button.getAttribute('data-portion-price'));
        
        console.log('Portion data:', {portionId, portionName, portionPrice});
        
        showIndicator(index);
        
        const formData = new FormData();
        formData.append('update_portion', '1');
        formData.append('item_index', index);
        formData.append('portion_id', portionId);
        formData.append('portion_name', portionName);
        formData.append('portion_price', portionPrice);
        
        fetch(window.location.href, { 
            method: 'POST', 
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            console.log('Portion update response:', data);
            
            if (data.success) {
                // تحديث السعر المعروض
                const priceElement = document.getElementById(`price-${index}`);
                if (priceElement) {
                    priceElement.textContent = portionPrice.toFixed(2) + ' ريال';
                }
                
                // تحديث data-price للعنصر
                const cartItem = document.querySelector(`.cart-item[data-index="${index}"]`);
                if (cartItem) {
                    cartItem.dataset.price = portionPrice;
                }
                
                // تحديث المجموع الفرعي
                const qtySpan = document.getElementById(`qty-${index}`);
                if (qtySpan) {
                    const qty = parseInt(qtySpan.textContent);
                    const subtotalElement = document.getElementById(`subtotal-${index}`);
                    if (subtotalElement) {
                        subtotalElement.textContent = (portionPrice * qty).toFixed(2) + ' ريال';
                    }
                }
                
                // تحديث شارة القسم
                let badge = document.getElementById(`badge-${index}`);
                if (portionName !== 'كامل') {
                    if (badge) {
                        badge.innerHTML = `<i class="bi bi-tag"></i> ${portionName}`;
                        badge.style.display = 'inline-flex';
                    } else {
                        const details = cartItem.querySelector('.cart-item-details');
                        const newBadge = document.createElement('div');
                        newBadge.className = 'portion-badge';
                        newBadge.id = `badge-${index}`;
                        newBadge.innerHTML = `<i class="bi bi-tag"></i> ${portionName}`;
                        const priceDiv = details.querySelector('.cart-item-price');
                        if (priceDiv && priceDiv.nextSibling) {
                            details.insertBefore(newBadge, priceDiv.nextSibling);
                        } else {
                            details.appendChild(newBadge);
                        }
                    }
                } else if (badge) {
                    badge.style.display = 'none';
                }
                
                // تحديث الأزرار النشطة
                const selector = document.getElementById(`selector-${index}`);
                if (selector) {
                    selector.querySelectorAll('.portion-option').forEach(btn => {
                        btn.classList.remove('active');
                        if (btn.getAttribute('data-portion-id') == portionId) {
                            btn.classList.add('active');
                        }
                    });
                    selector.classList.remove('show');
                }
                
                updateTotals();
                showToast('✅ تم تغيير القسم بنجاح');
            } else {
                showToast('❌ حدث خطأ في تحديث القسم', 'error');
            }
            hideIndicator(index);
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('❌ حدث خطأ في الاتصال', 'error');
            hideIndicator(index);
        });
    }
    
    // =============================================
    // دوال تحديث الكمية
    // =============================================
    function updateQuantity(index, change) {
        console.log('updateQuantity called for index:', index, 'change:', change);
        
        const qtySpan = document.getElementById(`qty-${index}`);
        const hiddenInput = document.getElementById(`input-${index}`);
        const cartItem = document.querySelector(`.cart-item[data-index="${index}"]`);
        
        console.log('Elements found:', {
            qtySpan: !!qtySpan,
            hiddenInput: !!hiddenInput,
            cartItem: !!cartItem
        });
        
        if (!qtySpan || !cartItem) {
            console.error('Required elements not found for index:', index);
            return;
        }
        
        let qty = parseInt(qtySpan.textContent) + change;
        if (qty < 1) qty = 1;
        if (qty > 99) qty = 99;
        
        console.log('New quantity:', qty);
        
        qtySpan.textContent = qty;
        if (hiddenInput) hiddenInput.value = qty;
        
        const price = parseFloat(cartItem.dataset.price);
        const subtotalElement = document.getElementById(`subtotal-${index}`);
        if (subtotalElement) {
            subtotalElement.textContent = (price * qty).toFixed(2) + ' ريال';
            console.log('New subtotal:', (price * qty).toFixed(2));
        }
        
        updateTotals();
        showIndicator(index);
        
        if (updateTimeouts[index]) clearTimeout(updateTimeouts[index]);
        updateTimeouts[index] = setTimeout(() => syncQuantities(), 500);
    }
    
    function syncQuantities() {
        const quantities = {};
        
        document.querySelectorAll('.cart-item').forEach(item => {
            const index = item.dataset.index;
            const qtySpan = document.getElementById(`qty-${index}`);
            if (qtySpan) {
                quantities[index] = parseInt(qtySpan.textContent);
            }
        });
        
        console.log('Syncing quantities:', quantities);
        
        if (Object.keys(quantities).length === 0) {
            document.querySelectorAll('.update-indicator').forEach(ind => {
                ind.classList.remove('visible');
            });
            return;
        }
        
        const formData = new FormData();
        formData.append('ajax_update', '1');
        for (let index in quantities) {
            formData.append(`quantity[${index}]`, quantities[index]);
        }
        
        fetch(window.location.href, { 
            method: 'POST', 
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            console.log('Quantity sync response:', data);
            
            if (data.success) {
                if (data.cart_count === 0) {
                    location.reload();
                } else {
                    // تحديث القيم المخفية
                    for (let index in data.items) {
                        const input = document.getElementById(`input-${index}`);
                        if (input) {
                            input.value = data.items[index].quantity;
                        }
                    }
                    updateTotals();
                    showToast('✅ تم تحديث الكميات بنجاح');
                }
            } else {
                showToast('❌ حدث خطأ في تحديث الكميات', 'error');
            }
            document.querySelectorAll('.update-indicator').forEach(ind => {
                ind.classList.remove('visible');
            });
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('❌ حدث خطأ في الاتصال', 'error');
            document.querySelectorAll('.update-indicator').forEach(ind => {
                ind.classList.remove('visible');
            });
        });
    }
    
    // =============================================
    // دوال حساب المجاميع
    // =============================================
    function updateTotals() {
        let total = 0;
        document.querySelectorAll('[id^="subtotal-"]').forEach(el => {
            const text = el.textContent.replace(' ريال', '').trim();
            const value = parseFloat(text);
            if (!isNaN(value)) {
                total += value;
            }
        });
        
        console.log('Updated total:', total);
        
        const cartTotalDisplay = document.getElementById('cart-total-display');
        const finalTotalDisplay = document.getElementById('final-total-display');
        
        if (cartTotalDisplay) {
            cartTotalDisplay.textContent = total.toFixed(2) + ' ريال';
        }
        if (finalTotalDisplay) {
            finalTotalDisplay.textContent = (total + deliveryFee).toFixed(2) + ' ريال';
        }
    }
    
    // =============================================
    // دوال حذف وتفريغ السلة
    // =============================================
    let pendingAction = null;
    
    function removeItem(index, name) {
        document.getElementById('modalTitle').textContent = 'تأكيد الحذف';
        document.getElementById('modalMessage').textContent = `هل أنت متأكد من حذف "${name}" من السلة؟`;
        
        pendingAction = () => {
            document.getElementById('remove-item-input').value = '1';
            document.getElementById('remove-index-input').value = index;
            document.getElementById('cart-form').submit();
        };
        
        document.getElementById('confirmModal').classList.add('active');
    }
    
    function clearCart() {
        document.getElementById('modalTitle').textContent = 'تفريغ السلة';
        document.getElementById('modalMessage').textContent = 'هل أنت متأكد من تفريغ السلة بالكامل؟';
        
        pendingAction = () => {
            document.getElementById('clear-cart-input').value = '1';
            document.getElementById('cart-form').submit();
        };
        
        document.getElementById('confirmModal').classList.add('active');
    }
    
    function closeModal() {
        document.getElementById('confirmModal').classList.remove('active');
        pendingAction = null;
    }
    
    document.getElementById('confirmBtn').onclick = function() {
        if (pendingAction) {
            pendingAction();
        }
        closeModal();
    };
    
    // =============================================
    // دوال مساعدة
    // =============================================
    function showIndicator(index) {
        const ind = document.getElementById(`indicator-${index}`);
        if (ind) ind.classList.add('visible');
    }
    
    function hideIndicator(index) {
        const ind = document.getElementById(`indicator-${index}`);
        if (ind) ind.classList.remove('visible');
    }
    
    function showToast(message, type = 'success') {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = 'toast-message';
        const icon = type === 'success' ? 'bi-check-lg' : 'bi-exclamation-triangle';
        toast.innerHTML = `<i class="bi ${icon}"></i><span>${message}</span>`;
        container.appendChild(toast);
        
        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }
    
    // =============================================
    // أحداث الصفحة
    // =============================================
    document.addEventListener('click', function(event) {
        if (!event.target.closest('.portion-selector') && !event.target.closest('.btn-sm')) {
            document.querySelectorAll('.portion-selector').forEach(selector => {
                selector.classList.remove('show');
            });
        }
    });
    
    document.getElementById('confirmModal').addEventListener('click', function(e) {
        if (e.target === this) closeModal();
    });
    
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeModal();
            closeSidebar();
        }
    });
    
    document.querySelectorAll('.menu-item').forEach(item => {
        item.addEventListener('click', closeSidebar);
    });
    
    setTimeout(() => {
        const toasts = document.querySelectorAll('.toast-message');
        toasts.forEach(toast => toast.remove());
    }, 3000);
    
    console.log('Cart page loaded successfully');
    </script>
</body>
</html>