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

$driver_id = filterRequest("driver_id");

$sql = "
    SELECT 
        COALESCE(ROUND(AVG(behavior_score), 1), 100) as avg_score,
        COALESCE(SUM(hard_brakes), 0) as total_hard_brakes,
        COALESCE(MAX(max_speed), 0) as max_speed
    FROM `driver_behavior`
    WHERE driver_id = :driver_id
      AND created_at >= DATE(NOW()) - INTERVAL 30 DAY
";

$stmt = $con->prepare($sql);
$stmt->bindParam(':driver_id', $driver_id, PDO::PARAM_INT);
$stmt->execute();

$row = $stmt->fetch(PDO::FETCH_ASSOC);

if ($row && $row['max_speed'] !== null) {
    jsonSuccess([$row]);
} else {
    jsonSuccess([[
        "avg_score" => 100, 
        "total_hard_brakes" => 0, 
        "max_speed" => 0
    ]]);
}
?>
