<?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, total earnings, and their settled amounts for both driver and admin
        $query = "
            SELECT 
                d.id, d.driver_name, d.phone, 
                SUM(t.total_cost) AS total_cost,
                (SELECT IFNULL(SUM(settled_amount), 0) FROM salary_settle WHERE driver_id = d.id AND settlement_type = 'admin_to_driver') AS settled_driver,
                (SELECT IFNULL(SUM(settled_amount), 0) FROM salary_settle WHERE driver_id = d.id AND settlement_type = 'driver_to_admin') AS settled_admin
            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()) {
                $totalEarnings = floatval($row['total_cost']);
                $settledDriver = floatval($row['settled_driver']);
                $settledAdmin = floatval($row['settled_admin']);
                
                // Calculate pending amounts
                $driverEarnings = ($totalEarnings * 0.9); // 90% to driver
                $adminEarnings = ($totalEarnings * 0.1); // 10% to admin

                $pendingDriver = $driverEarnings - $settledDriver;
                $pendingAdmin = $adminEarnings - $settledAdmin;

                $drivers[] = array_merge($row, [
                    'driver_earnings' => $driverEarnings,
                    'admin_earnings' => $adminEarnings,
                    'pending_driver' => $pendingDriver,
                    'pending_admin' => $pendingAdmin
                ]);
            }
            $response['drivers'] = $drivers;
        } else {
            $response['error'] = "Error fetching drivers and earnings.";
        }

    } elseif ($action === 'settle_earnings') {
        // Handle settling earnings
        $data = json_decode(file_get_contents("php://input"), true);
        $driver_id = intval($data['driver_id']);
        $settled_amount = floatval($data['settled_amount']);
        $settled_trips = $data['settled_trips'];
        $settled_by = $data['settled_by'];
        $settlement_type = $data['settlement_type'];

        // Insert settlement data
        $query = "INSERT INTO salary_settle (driver_id, settled_amount, settled_trips, settlement_type, settled_by, settlement_date) 
                  VALUES ('$driver_id', '$settled_amount', '$settled_trips', '$settlement_type', '$settled_by', NOW())";

        if ($conn->query($query)) {
            $response['message'] = "Earnings settled successfully.";
        } else {
            $response['error'] = "Error settling earnings: " . $conn->error;
        }

    } elseif ($action === 'fetch_earnings') {
        // Fetch earnings for a specific driver
        $driver_id = intval($_GET['driver_id']);
        $earnings = [];

        $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'
                  AND t.id NOT IN (SELECT settled_trips FROM salary_settle WHERE driver_id = $driver_id)";
        
        $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();
}

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