<?php
// ajax_handler.php - معالج طلبات AJAX
include 'config.php';

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

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

header('Content-Type: application/json');

if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    echo json_encode(['success' => false, 'message' => 'طلب غير صالح']);
    exit();
}

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

switch ($action) {
    case 'add_to_cart':
        handleAddToCart($conn);
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'عملية غير معروفة']);
        break;
}

function handleAddToCart($conn) {
    $meal_id = (int)($_POST['meal_id'] ?? 0);
    $quantity = (int)($_POST['quantity'] ?? 1);
    $portion_id = isset($_POST['portion_id']) && !empty($_POST['portion_id']) ? (int)$_POST['portion_id'] : null;
    $portion_name = $_POST['portion_name'] ?? 'كامل';
    $portion_price = (float)($_POST['portion_price'] ?? 0);
    
    if ($meal_id <= 0 || $quantity <= 0) {
        echo json_encode(['success' => false, 'message' => 'بيانات غير صالحة']);
        return;
    }
    
    $stmt = $conn->prepare("SELECT id, name, price, image, has_portions FROM meals WHERE id = ? AND is_active = 1");
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'خطأ في قاعدة البيانات']);
        return;
    }
    
    $stmt->bind_param('i', $meal_id);
    $stmt->execute();
    $meal_result = $stmt->get_result();
    
    if ($meal_result->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'الوجبة غير موجودة']);
        $stmt->close();
        return;
    }
    
    $meal_data = $meal_result->fetch_assoc();
    
    $final_price = $meal_data['price'];
    if ($portion_id && $meal_data['has_portions']) {
        $final_price = $portion_price > 0 ? $portion_price : $meal_data['price'];
    }
    
    $found = false;
    foreach ($_SESSION['cart'] as $key => $item) {
        if ($item['meal_id'] == $meal_id && $item['portion_id'] == $portion_id) {
            $_SESSION['cart'][$key]['quantity'] += $quantity;
            $found = true;
            break;
        }
    }
    
    if (!$found) {
        $_SESSION['cart'][] = [
            'meal_id' => $meal_id,
            'meal_name' => $meal_data['name'],
            'quantity' => $quantity,
            'price' => $final_price,
            'base_price' => $meal_data['price'],
            'image' => $meal_data['image'],
            'has_portions' => $meal_data['has_portions'],
            'portion_id' => $portion_id,
            'portion_name' => $portion_name,
            'portion_price' => $final_price
        ];
    }
    
    $cart_count = 0;
    foreach ($_SESSION['cart'] as $item) {
        $cart_count += $item['quantity'];
    }
    
    $stmt->close();
    
    echo json_encode([
        'success' => true,
        'message' => "✅ تمت إضافة " . $meal_data['name'] . 
            ($portion_name != 'كامل' ? " (" . $portion_name . ")" : "") . " إلى السلة",
        'cart_count' => $cart_count
    ]);
}