<?php
/**
 * API: Get Captain Orders
 */

require_once 'config.php';
checkCaptainAuth();

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

$captain_id = $_SESSION['captain_id'];
$tab = isset($_GET['tab']) ? $_GET['tab'] : 'current';

if ($tab === 'current') {
    // الطلبات الحالية
    $sql = "SELECT o.*, c.name as customer_name, c.phone as customer_phone, c.address as customer_address
            FROM orders o 
            JOIN customers c ON o.customer_id = c.id 
            WHERE o.captain_id = '$captain_id' AND o.status != 'delivered'
            ORDER BY 
                CASE o.status
                    WHEN 'accepted' THEN 1
                    WHEN 'on_the_way' THEN 2
                    ELSE 3
                END,
                o.created_at ASC";
} else {
    // الطلبات المكتملة
    $sql = "SELECT o.*, c.name as customer_name
            FROM orders o 
            JOIN customers c ON o.customer_id = c.id 
            WHERE o.captain_id = '$captain_id' AND o.status = 'delivered'
            ORDER BY o.updated_at DESC
            LIMIT 20";
}

$result = $conn->query($sql);
$orders = [];

while ($row = $result->fetch_assoc()) {
    $orders[] = $row;
}

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