<?php
require_once 'db.php';
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, PUT, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, access-control-allow-origin");
header("Content-Type: application/json; charset=UTF-8");

$response = array();
$action = $_GET['action'];

try {
    if ($action === 'fetch_drivers_with_earnings') {
        $drivers = [];

        // Fetch drivers and their total earnings
        $query = "SELECT d.id, d.driver_name, d.phone, SUM(t.total_cost) AS total_cost
                  FROM registered_vehicles d
                  LEFT JOIN new_trip_booking t ON d.id = t.driver
                  WHERE t.status = 'completed'
                  GROUP BY d.id";
        
        $result = $conn->query($query);

        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $drivers[] = $row;
            }
            $response['drivers'] = $drivers;
        } else {
            $response['error'] = "Error fetching drivers and earnings.";
        }
    } elseif ($action === 'fetch_earnings') {
        $driver_id = intval($_GET['driver_id']);
        $earnings = [];

        // Fetch earnings for a specific driver
        $query = "SELECT t.id AS trip_id, t.total_cost, t.payment_method, t.status
                  FROM new_trip_booking t
                  WHERE t.driver = $driver_id AND t.status = 'completed'";
        
        $result = $conn->query($query);

        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $earnings[] = $row;
            }
            $response['earnings'] = $earnings;
        } else {
            $response['error'] = "Error fetching earnings.";
        }
    } else {
        $response['error'] = 'Invalid action';
    }
} catch (Exception $e) {
    $response['error'] = $e->getMessage();
}

echo json_encode($response);
$conn->close();
?>
