<?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. الاستعلام: تجميع عدد الملاحظات لكل موظف في كل يوم
// نستخدم DATE(createdAt) لتوحيد التوقيت لليوم فقط
$sql = "
    SELECT 
        DATE(createdAt) as date, 
        editor as NAME, 
        COUNT(*) as count 
    FROM 
        notesForDriverService 
    WHERE 
        createdAt BETWEEN '$start_date' AND '$end_date 23:59:59'
    GROUP BY 
        DATE(createdAt), editor
    ORDER BY 
        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()));
}
?>