<?php
// add_to_cart.php - Optimized AJAX cart handler
session_start();
header('Content-Type: application/json');

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

// Check if it's an AJAX request
$is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
           strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';

// Get action
$action = $_POST['action'] ?? '';

switch ($action) {
    case 'add':
        handleAddToCart();
        break;
        
    case 'update':
        handleUpdateCart();
        break;
        
    case 'remove':
        handleRemoveFromCart();
        break;
        
    case 'clear':
        handleClearCart();
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        exit;
}

function handleAddToCart() {
    require_once 'config.php';
    
    $meal_id = (int)($_POST['meal_id'] ?? 0);
    $quantity = (int)($_POST['quantity'] ?? 1);
    $portion_id = isset($_POST['portion_id']) ? (int)$_POST['portion_id'] : null;
    
    if ($meal_id <= 0 || $quantity <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid data']);
        exit;
    }
    
    // Get meal details
    $query = "SELECT id, name, price, has_portions FROM meals WHERE id = ? AND is_active = 1";
    $stmt = mysqli_prepare($GLOBALS['conn'], $query);
    mysqli_stmt_bind_param($stmt, 'i', $meal_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if (mysqli_num_rows($result) === 0) {
        echo json_encode(['success' => false, 'message' => 'Meal not found']);
        exit;
    }
    
    $meal = mysqli_fetch_assoc($result);
    $final_price = $meal['price'];
    $portion_name = 'كامل';
    
    // Get portion details if selected
    if ($portion_id && $meal['has_portions']) {
        $portion_query = "SELECT name, price FROM meal_portions WHERE id = ? AND meal_id = ?";
        $stmt = mysqli_prepare($GLOBALS['conn'], $portion_query);
        mysqli_stmt_bind_param($stmt, 'ii', $portion_id, $meal_id);
        mysqli_stmt_execute($stmt);
        $portion_result = mysqli_stmt_get_result($stmt);
        
        if ($portion = mysqli_fetch_assoc($portion_result)) {
            $final_price = $portion['price'];
            $portion_name = $portion['name'];
        }
    }
    
    // Check if item already exists in cart
    $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;
        }
    }
    
    // Add new item if not found
    if (!$found) {
        $_SESSION['cart'][] = [
            'meal_id' => $meal_id,
            'meal_name' => $meal['name'],
            'quantity' => $quantity,
            'price' => $final_price,
            'portion_id' => $portion_id,
            'portion_name' => $portion_name,
            'image' => $meal['image'] ?? ''
        ];
    }
    
    // Calculate new cart count
    $cart_count = array_sum(array_column($_SESSION['cart'], 'quantity'));
    
    echo json_encode([
        'success' => true,
        'message' => 'تمت الإضافة إلى السلة بنجاح',
        'cart_count' => $cart_count,
        'cart_total' => calculateCartTotal()
    ]);
}

function handleUpdateCart() {
    $item_id = $_POST['item_id'] ?? null;
    $quantity = (int)($_POST['quantity'] ?? 0);
    
    if ($item_id !== null && isset($_SESSION['cart'][$item_id])) {
        if ($quantity > 0) {
            $_SESSION['cart'][$item_id]['quantity'] = $quantity;
        } else {
            unset($_SESSION['cart'][$item_id]);
            $_SESSION['cart'] = array_values($_SESSION['cart']);
        }
    }
    
    $cart_count = array_sum(array_column($_SESSION['cart'], 'quantity'));
    
    echo json_encode([
        'success' => true,
        'cart_count' => $cart_count,
        'cart_total' => calculateCartTotal()
    ]);
}

function handleRemoveFromCart() {
    $item_id = $_POST['item_id'] ?? null;
    
    if ($item_id !== null && isset($_SESSION['cart'][$item_id])) {
        unset($_SESSION['cart'][$item_id]);
        $_SESSION['cart'] = array_values($_SESSION['cart']);
    }
    
    $cart_count = array_sum(array_column($_SESSION['cart'], 'quantity'));
    
    echo json_encode([
        'success' => true,
        'cart_count' => $cart_count,
        'cart_total' => calculateCartTotal()
    ]);
}

function handleClearCart() {
    $_SESSION['cart'] = [];
    
    echo json_encode([
        'success' => true,
        'cart_count' => 0,
        'cart_total' => 0
    ]);
}

function calculateCartTotal() {
    $total = 0;
    foreach ($_SESSION['cart'] as $item) {
        $total += $item['price'] * $item['quantity'];
    }
    return $total;
}
?>