<?php
// =============================================
//   check_new_orders.php  (نسخة محدّثة بدون تيليغرام)
//   يتحقق من الطلبات الجديدة فقط - الإشعار يتم في المتصفح
// =============================================
include "session.php";
header('Content-Type: application/json');

require_once __DIR__ . '/../db.php';

$lastId = (int)($_GET['last_id'] ?? 0);
$today  = date('Y-m-d');

// جلب الطلبات الجديدة
$stmt = $pdo->prepare("
    SELECT o.id, o.customer_name, o.phone, o.order_date,
           w.name as wilaya_name,
           (SELECT SUM(oi.quantity * oi.unit_price)
            FROM order_items oi WHERE oi.order_id = o.id) as total_price
    FROM orders o
    LEFT JOIN wilayas w ON o.wilaya_id = w.id
    WHERE o.id > ?
    ORDER BY o.id ASC
");
$stmt->execute([$lastId]);
$newOrders = $stmt->fetchAll();

// عدد طلبات اليوم
$todayStmt = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE DATE(order_date) = ?");
$todayStmt->execute([$today]);
$todayCount = (int)$todayStmt->fetchColumn();

// أحدث ID
$latestId = (int)$pdo->query("SELECT COALESCE(MAX(id), 0) FROM orders")->fetchColumn();

$newCount = count($newOrders);

// بناء تفاصيل الإشعار
$notificationData = null;
if ($newCount > 0) {
    $firstOrder = $newOrders[0];
    $total = floatval($firstOrder['total_price'] ?? 0);

    if ($newCount === 1) {
        $notificationData = [
            'title'   => '🛒 طلب جديد #' . $firstOrder['id'],
            'body'    => '👤 ' . $firstOrder['customer_name']
                       . ' | 📍 ' . ($firstOrder['wilaya_name'] ?? '--')
                       . ' | 💰 ' . number_format($total, 0) . ' دج',
            'orderId' => (int)$firstOrder['id'],
            'url'     => '/admin/orders.php'
        ];
    } else {
        $notificationData = [
            'title'   => '🛒 وصلت ' . $newCount . ' طلبات جديدة!',
            'body'    => 'آخر طلب من: ' . $firstOrder['customer_name']
                       . ' | ' . ($firstOrder['wilaya_name'] ?? '--'),
            'orderId' => $latestId,
            'url'     => '/admin/orders.php'
        ];
    }
}

echo json_encode([
    'new_count'    => $newCount,
    'latest_id'    => $latestId,
    'today_count'  => $todayCount,
    'notification' => $notificationData,
    'new_orders'   => $newOrders,
]);