<?php
include "../../connect.php";
$driverID = filterRequest("driverID");

$sql = "SELECT
    YEAR(`driver_orders`.`created_at`) AS `year`,
    MONTH(`driver_orders`.`created_at`) AS `month`,
    COUNT(*) AS `total_orders`,
    SUM(CASE WHEN `ride`.`status` = 'Finished' THEN 1 ELSE 0 END) AS `completed_orders`,
    SUM(CASE WHEN `ride`.`status` = 'Apply' THEN 1 ELSE 0 END) AS `pending_orders`,
    SUM(CASE WHEN `ride`.`status` = 'Cancel' THEN 1 ELSE 0 END) AS `canceled_orders`,
    ROUND(SUM(CASE WHEN `ride`.`status` = 'Finished' THEN 1 ELSE 0 END) / COUNT(*) * 100, 2) AS `percent_completed`,
    ROUND(SUM(CASE WHEN `ride`.`status` = 'Apply' THEN 1 ELSE 0 END) / COUNT(*) * 100, 2) AS `percent_pending`,
    ROUND(SUM(CASE WHEN `ride`.`status` = 'Cancel' THEN 1 ELSE 0 END) / COUNT(*) * 100, 2) AS `percent_canceled`,
    SUM(CASE WHEN `ride`.`status` = 'Refused' THEN 1 ELSE 0 END) AS `rejected_orders`,
    ROUND(SUM(CASE WHEN `ride`.`status` = 'Refused' THEN 1 ELSE 0 END) / COUNT(*) * 100, 2) AS `percent_rejected`
FROM
    `driver_orders`
LEFT JOIN `ride` ON `ride`.`id` = `driver_orders`.`order_id`
WHERE
    `driver_orders`.`driver_id` = '$driverID'
    AND YEAR(`driver_orders`.`created_at`) = YEAR(CURDATE())
    AND MONTH(`driver_orders`.`created_at`) = MONTH(CURDATE())
GROUP BY
    YEAR(`driver_orders`.`created_at`),
    MONTH(`driver_orders`.`created_at`)
ORDER BY
    `year`,
    `month`;

";
$stmt = $con->prepare($sql);
$stmt->execute();

if ($stmt->rowCount() > 0) {
    // Fetch the record
    $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

    printSuccess( $row);
    
}
    else{
    // Print a failure message
    printFailure($message = "No wallet record found");
}
?>