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

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

// تهيئة آخر معرف إذا لم يكن موجوداً
if (!isset($_SESSION['last_checked_order_id'])) {
    $result = $conn->query("SELECT MAX(id) as max_id FROM orders");
    if ($result && $result->num_rows > 0) {
        $_SESSION['last_checked_order_id'] = $result->fetch_assoc()['max_id'];
    } else {
        $_SESSION['last_checked_order_id'] = 0;
    }
}

$last_id = $_SESSION['last_checked_order_id'];

// جلب عدد الطلبات الجديدة
$result = $conn->query("SELECT COUNT(*) as count FROM orders WHERE id > $last_id AND status = 'pending'");
$new_orders_count = 0;
if ($result && $result->num_rows > 0) {
    $new_orders_count = $result->fetch_assoc()['count'];
}

// جلب تفاصيل الطلبات الجديدة
$new_orders = [];
if ($new_orders_count > 0) {
    $result = $conn->query("
        SELECT o.*, c.name as customer_name 
        FROM orders o 
        JOIN customers c ON o.customer_id = c.id 
        WHERE o.id > $last_id AND o.status = 'pending'
        ORDER BY o.created_at DESC 
        LIMIT 5
    ");
    
    if ($result && $result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $new_orders[] = $row;
        }
    }
}

echo json_encode([
    'success' => true,
    'new_orders_count' => $new_orders_count,
    'new_orders' => $new_orders,
    'last_checked_id' => $last_id
]);

// لا نقوم بتحديث last_checked_order_id هنا حتى يرى المستخدم الطلبات
?>