<?php
require_once __DIR__ . '/../connect.php';

// منع الأخطاء النصية وضبط الترويسة
error_reporting(0);
header('Content-Type: application/json');

// 1. استقبال التواريخ
if (isset($_POST['start_date']) && isset($_POST['end_date'])) {
    $start_date = $_POST['start_date'];
    $end_date   = $_POST['end_date'];
} else {
    // Fallback: استخدام الشهر والسنة الحالية أو المرسلة
    $current_month = isset($_POST['month']) ? str_pad($_POST['month'], 2, "0", STR_PAD_LEFT) : date('m');
    $current_year  = isset($_POST['year'])  ? $_POST['year']  : date('Y');
    
    $start_date = date('Y-m-d', strtotime("$current_year-$current_month-01"));
    $end_date   = date('Y-m-t', strtotime($start_date));
}

// 2. جملة SQL المعدلة
$sql = "
WITH RECURSIVE date_series AS (
    SELECT '$start_date' AS date
    UNION ALL
    SELECT DATE_ADD(date, INTERVAL 1 DAY)
    FROM date_series
    WHERE date < '$end_date'
)
SELECT
    date_series.date AS day,
    
    -- (passengers) عدد الركاب اليومي
    COALESCE((SELECT COUNT(id) FROM passengers WHERE DATE(passengers.created_at) = date_series.date), 0) AS totalPassengers,
    
    -- (passengers) الإجمالي للفترة المحددة
    (
        SELECT COUNT(*) 
        FROM passengers 
        WHERE passengers.created_at BETWEEN '$start_date' AND '$end_date 23:59:59'
    ) AS totalMonthly

FROM
    date_series
GROUP BY date_series.date
ORDER BY date_series.date ASC; 
";
// ملاحظة: جعلت الترتيب ASC (تصاعدي) لأن الرسم البياني يحتاج الأيام من البداية للنهاية

try {
    $stmt = $con->prepare($sql);
    $stmt->execute();
    $passenger_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($passenger_data) {
        echo json_encode(array("status" => "success", "message" => $passenger_data));
    } else {
        echo json_encode(array("status" => "success", "message" => []));
    }
} catch (PDOException $e) {
    echo json_encode(array("status" => "failure", "message" => $e->getMessage()));
}
?>