<?php
// تعطيل عرض الأخطاء تماماً
error_reporting(0);
ini_set('display_errors', 0);

// منع أي مخرجات قبل JSON
ob_clean();

require_once dirname(__DIR__) . '/config.php';

// تعيين header JSON
header('Content-Type: application/json');

// التحقق من الجلسة
if (!isset($_SESSION[CASHIER_SESSION_KEY])) {
    echo json_encode(['success' => false, 'message' => 'يرجى تسجيل الدخول أولاً', 'updated_orders' => []]);
    exit;
}

try {
    $last_check = isset($_GET['last_check']) ? $_GET['last_check'] : date('Y-m-d H:i:s', strtotime('-1 minute'));
    $last_check = $conn->real_escape_string($last_check);
    
    // جلب الطلبات المحدثة
    $sql = "SELECT o.id, o.status, o.captain_id, o.updated_at,
                   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.updated_at > '$last_check'
            ORDER BY o.updated_at DESC";
    
    $result = $conn->query($sql);
    
    $updated_orders = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $updated_orders[] = $row;
        }
    }
    
    echo json_encode([
        'success' => true,
        'updated_orders' => $updated_orders,
        'count' => count($updated_orders),
        'server_time' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'حدث خطأ',
        'updated_orders' => [],
        'count' => 0,
        'server_time' => date('Y-m-d H:i:s')
    ]);
}
?>