<?php
// reorder.php - إعادة الطلب إلى السلة مع الأقسام
include 'config.php';
checkCustomerAuth();

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

$order_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$customer_id = $_SESSION['customer_id'];

if ($order_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'طلب غير صالح']);
    exit();
}

// التحقق من ملكية الطلب
$check_sql = "SELECT id FROM orders WHERE id = ? AND customer_id = ?";
$check_stmt = $conn->prepare($check_sql);
$check_stmt->bind_param("ii", $order_id, $customer_id);
$check_stmt->execute();
$check_result = $check_stmt->get_result();

if ($check_result->num_rows == 0) {
    echo json_encode(['success' => false, 'message' => 'لا يمكن الوصول لهذا الطلب']);
    exit();
}

// جلب عناصر الطلب مع الأقسام
$items_sql = "SELECT oi.meal_id, oi.quantity, oi.price, oi.portion_id
              FROM order_items oi
              WHERE oi.order_id = ?";
$items_stmt = $conn->prepare($items_sql);
$items_stmt->bind_param("i", $order_id);
$items_stmt->execute();
$items_result = $items_stmt->get_result();

// بدء الجلسة
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

// إضافة العناصر إلى السلة
$added_count = 0;
while ($item = $items_result->fetch_assoc()) {
    // جلب معلومات الوجبة
    $meal_sql = "SELECT name, image, has_portions FROM meals WHERE id = ?";
    $meal_stmt = $conn->prepare($meal_sql);
    $meal_stmt->bind_param("i", $item['meal_id']);
    $meal_stmt->execute();
    $meal_result = $meal_stmt->get_result();
    $meal = $meal_result->fetch_assoc();
    
    // جلب معلومات القسم إذا وجد
    $portion_name = 'كامل';
    if (!empty($item['portion_id'])) {
        $portion_sql = "SELECT name, price FROM meal_portions WHERE id = ?";
        $portion_stmt = $conn->prepare($portion_sql);
        $portion_stmt->bind_param("i", $item['portion_id']);
        $portion_stmt->execute();
        $portion_result = $portion_stmt->get_result();
        if ($portion = $portion_result->fetch_assoc()) {
            $portion_name = $portion['name'];
        }
    }
    
    // التحقق من وجود العنصر في السلة
    $found = false;
    foreach ($_SESSION['cart'] as $key => $cart_item) {
        if ($cart_item['meal_id'] == $item['meal_id'] && 
            ($cart_item['portion_id'] ?? null) == $item['portion_id']) {
            $_SESSION['cart'][$key]['quantity'] += $item['quantity'];
            $found = true;
            break;
        }
    }
    
    if (!$found) {
        $_SESSION['cart'][] = [
            'meal_id' => $item['meal_id'],
            'meal_name' => $meal['name'],
            'quantity' => $item['quantity'],
            'price' => $item['price'],
            'image' => $meal['image'],
            'has_portions' => $meal['has_portions'],
            'portion_id' => $item['portion_id'],
            'portion_name' => $portion_name,
            'portion_price' => $item['price']
        ];
    }
    
    $added_count++;
}

echo json_encode([
    'success' => true,
    'message' => "تم إضافة $added_count عنصر إلى السلة مع الأقسام"
]);
?>