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

try {
    $driver_id = filterRequest("driver_id");

    // ✅ أولاً: حساب متوسط السلوك لجميع الرحلات
    $sql_average = "SELECT COALESCE(AVG(behavior_score), 100) AS overall_behavior_score
                    FROM driver_behavior
                    WHERE driver_id = :driver_id";

    $stmt_avg = $con->prepare($sql_average);
    $stmt_avg->bindParam(':driver_id', $driver_id);
    $stmt_avg->execute();
    $average = $stmt_avg->fetch(PDO::FETCH_ASSOC);

    // ✅ ثانياً: جلب آخر 10 رحلات
    $sql_last10 = "SELECT id, trip_id, max_speed, avg_speed, hard_brakes, total_distance, behavior_score, created_at
                   FROM driver_behavior
                   WHERE driver_id = :driver_id
                   ORDER BY id DESC
                   LIMIT 10";

    $stmt_last10 = $con->prepare($sql_last10);
    $stmt_last10->bindParam(':driver_id', $driver_id);
    $stmt_last10->execute();
    $last10 = $stmt_last10->fetchAll(PDO::FETCH_ASSOC);

    // ✅ تجهيز الاستجابة النهائية
    $response = [
        'overall_behavior_score' => $average['overall_behavior_score'],
        'last_10_trips' => $last10
    ];

    jsonSuccess($response);

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