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

$driver_id = filterRequest("driver_id");

$current_month = date('m');
$current_year = date('Y');

// Get the first and last days of the current month.
$first_day_of_month = date('Y-m-d', strtotime($current_year . '-' . $current_month . '-01'));
$last_day_of_month = date('Y-m-d', strtotime($current_year . '-' . $current_month . '-' . cal_days_in_month(CAL_GREGORIAN, $current_month, $current_year)));

// Create a SQL query to select the total duration for the driver for each day in the current month.
$sql = "SELECT
  DATE(created_at) AS day,
  SEC_TO_TIME(COUNT(*) * 60) AS total_duration
FROM
  car_tracks
WHERE
  car_tracks.driver_id = :driver_id
  AND car_tracks.created_at >= :first_day_of_month
  AND car_tracks.created_at < :last_day_of_month
GROUP BY
  day
ORDER BY
  day ASC;";

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

$car_locations = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($car_locations) {
  // Print the car location data as JSON
  jsonSuccess($data = $car_locations);
} else {
  // Print a failure message
  jsonError($message = "No car locations found");
}

?>