<?php
/**
 * get_order_details.php - جلب تفاصيل الطلب مع الأقسام
 */

require_once 'config.php';

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

// التحقق من وجود معرف الطلب
if (!isset($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'معرف الطلب مطلوب']);
    exit;
}

$order_id = (int)$_GET['id'];

// جلب تفاصيل الطلب
$sql = "SELECT o.*, 
               c.name as customer_name, 
               c.phone as customer_phone, 
               c.address as customer_address,
               cp.name as captain_name,
               cp.phone as captain_phone
        FROM orders o
        JOIN customers c ON o.customer_id = c.id
        LEFT JOIN captains cp ON o.captain_id = cp.id
        WHERE o.id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $order_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'الطلب غير موجود']);
    exit;
}

$order = $result->fetch_assoc();

// جلب عناصر الطلب مع أقسام الوجبات
$items_sql = "SELECT oi.*, 
                     m.name as meal_name,
                     m.has_portions,
                     mp.name as portion_name,
                     mp.price as portion_price
              FROM order_items oi
              JOIN meals m ON oi.meal_id = m.id
              LEFT JOIN meal_portions mp ON oi.portion_id = mp.id
              WHERE oi.order_id = ?
              ORDER BY oi.id ASC";

$stmt_items = $conn->prepare($items_sql);
$stmt_items->bind_param("i", $order_id);
$stmt_items->execute();
$items_result = $stmt_items->get_result();

$order['items'] = [];
while ($item = $items_result->fetch_assoc()) {
    // تحديد اسم القسم (portion)
    $portion_display = '';
    if (!empty($item['portion_name'])) {
        $portion_display = $item['portion_name'];
    } elseif (!empty($item['portion_type']) && $item['portion_type'] != 'كامل') {
        $portion_display = $item['portion_type'];
    }
    
    $order['items'][] = [
        'id' => $item['id'],
        'meal_id' => $item['meal_id'],
        'meal_name' => $item['meal_name'],
        'quantity' => $item['quantity'],
        'price' => $item['price'],
        'portion_name' => $portion_display,
        'portion_id' => $item['portion_id'],
        'has_portions' => $item['has_portions']
    ];
}

echo json_encode(['success' => true, 'order' => $order]);
?>