<?php
include 'config.php';
checkAdminAuth();

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

$last_id = isset($_GET['last_id']) ? intval($_GET['last_id']) : 0;

// جلب الطلبات الجديدة
$sql = "SELECT o.*, c.name as customer_name, cp.name as captain_name 
        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 > $last_id 
        ORDER BY o.id ASC";

$result = $conn->query($sql);
$new_orders = [];
if ($result && $result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $new_orders[] = $row;
    }
}

// جلب أعلى ID حالي
$max_id_result = $conn->query("SELECT MAX(id) as max_id FROM orders");
$max_order_id = 0;
if ($max_id_result && $max_id_result->num_rows > 0) {
    $max_order_id = $max_id_result->fetch_assoc()['max_id'];
}

// جلب جميع الطلبات (لتحديث الجدول)
$all_orders_result = $conn->query("
    SELECT o.*, c.name as customer_name, cp.name as captain_name 
    FROM orders o 
    JOIN customers c ON o.customer_id = c.id 
    LEFT JOIN captains cp ON o.captain_id = cp.id 
    ORDER BY o.created_at DESC
");

$all_orders = [];
if ($all_orders_result && $all_orders_result->num_rows > 0) {
    while($row = $all_orders_result->fetch_assoc()) {
        // تنسيق التاريخ للعرض
        $row['created_at'] = date('Y-m-d H:i', strtotime($row['created_at']));
        $all_orders[] = $row;
    }
}

echo json_encode([
    'success' => true,
    'new_orders' => $new_orders,
    'max_order_id' => $max_order_id,
    'all_orders' => $all_orders
]);
?>