<?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,
    
    -- [1] إجمالي السائقين (الكلي في النظام)
    (SELECT COUNT(*) FROM driver) AS totalDrivers,

    -- [2] يومي: عدد السائقين المسجلين
    (
        SELECT COUNT(*)
        FROM driver
        WHERE DATE(driver.created_at) = date_series.date
    ) AS dailyTotalDrivers,

    -- [3] يومي: عدد السائقين المتصل بهم (notesForDriverService)
    (
        SELECT COUNT(*)
        FROM notesForDriverService
        WHERE DATE(notesForDriverService.createdAt) = date_series.date
    ) AS dailyTotalCallingDrivers,

    -- [4] يومي: Matching Notes (Join with driver on phone)
    (
        SELECT COUNT(*)
        FROM notesForDriverService n
        JOIN driver d ON n.phone = d.phone
        WHERE DATE(n.createdAt) = date_series.date
    ) AS dailyMatchingNotes,

    -- [5] إجمالي الفترة: سائقين
    (
        SELECT COUNT(*)
        FROM driver
        WHERE driver.created_at BETWEEN '$start_date' AND '$end_date 23:59:59'
    ) AS totalMonthlyDrivers,

    -- [6] إجمالي الفترة: Calling Drivers
    (
        SELECT COUNT(*)
        FROM notesForDriverService
        WHERE notesForDriverService.createdAt BETWEEN '$start_date' AND '$end_date 23:59:59'
    ) AS totalMonthlyCallingDrivers,

    -- [7] إجمالي الفترة: Matching Notes
    (
        SELECT COUNT(*)
        FROM notesForDriverService n
        JOIN driver d ON n.phone = d.phone
        WHERE n.createdAt BETWEEN '$start_date' AND '$end_date 23:59:59'
    ) AS totalMonthlyMatchingNotes

FROM
    date_series
GROUP BY
    date_series.date
ORDER BY
    date_series.date ASC;
";

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

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