<?php

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

$driver_id = filterRequest("driver_id");
$order_id  = filterRequest("order_id");

if ($driver_id != null) {

    // 1. First, get the statistics for the driver
    $stats_sql = "
        SELECT
            COUNT(*) AS total_rides,
            SUM(CASE WHEN status = 'Apply' THEN 1 ELSE 0 END) AS total_applied,
            SUM(CASE WHEN status = 'Refused' THEN 1 ELSE 0 END) AS total_refused
        FROM driver_orders
        WHERE
            driver_id = :driver_id
            AND MONTH(created_at) = MONTH(CURRENT_DATE())
            AND YEAR(created_at) = YEAR(CURRENT_DATE())
    ";
    $stats_stmt = $con->prepare($stats_sql);
    $stats_stmt->execute([':driver_id' => $driver_id]);
    $stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);

    // Calculate the average
    if ($stats && $stats['total_rides'] > 0) {
        $stats['averageApplied'] = $stats['total_applied'] / $stats['total_rides'];
    } else {
        $stats['averageApplied'] = 0;
    }


    // 2. Second, get the actual order history
    $orders_sql = "
        SELECT * FROM driver_orders
        WHERE
            driver_id = :driver_id
            AND MONTH(created_at) = MONTH(CURRENT_DATE())
            AND YEAR(created_at) = YEAR(CURRENT_DATE())
        ORDER BY created_at DESC
    ";
    $orders_stmt = $con->prepare($orders_sql);
    $orders_stmt->execute([':driver_id' => $driver_id]);
    $orders = $orders_stmt->fetchAll(PDO::FETCH_ASSOC);

    // 3. Combine the results into one response
   

    jsonSuccess($orders);


} elseif ($order_id != null) {
    // This part remains the same, but let's ensure it's correct
    $sql = "
        SELECT * FROM driver_orders
        WHERE order_id = :order_id
          AND MONTH(created_at) = MONTH(CURRENT_DATE())
          AND YEAR(created_at) = YEAR(CURRENT_DATE())
    ";
    $stmt = $con->prepare($sql);
    $stmt->execute([':order_id' => $order_id]);
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($stmt->rowCount() > 0) {
        jsonSuccess($result);
    } else {
        jsonError("No driver order data found for this order_id");
    }

} else {
    jsonError("No driver_id or order_id provided");
}

?>