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

$driverID = filterRequest("driverID");

// Safety check: ensure driverID is not empty to prevent SQL errors
if (!$driverID) {
    jsonError("Driver ID is required");
    exit();
}

$sql = "SELECT 
    DATE(driver_ride_scam.dateCreated) AS date,
    CAST(COUNT(driver_ride_scam.id) AS CHAR) AS count 
FROM 
    driver_ride_scam
LEFT JOIN 
    ride ON ride.id = driver_ride_scam.rideID 
        AND ride.status = 'Cancel'
WHERE 
    driver_ride_scam.driverID = :driverID
    AND driver_ride_scam.dateCreated >= CURDATE()
    AND driver_ride_scam.dateCreated < DATE_ADD(CURDATE(), INTERVAL 1 DAY)
GROUP BY 
    DATE(driver_ride_scam.dateCreated)
ORDER BY 
    date DESC";

try {
    $stmt = $con->prepare($sql);
    $stmt->bindParam(':driverID', $driverID);
    $stmt->execute();
    
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($rows)) {
        // --- FIX IS HERE ---
        // Your Flutter app looks for d['message']. 
        // We manually create the array with the key "message" to match your app.
        echo json_encode(array("status" => "success", "message" => $rows));
    } else {
        jsonError("No ride scam record found");
    }

} catch (PDOException $e) {
    jsonError("Database Error: " . $e->getMessage());
}
?>