<?php
require_once 'db.php';
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: POST");
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();

try {
    // Retrieve posted data from the client
    $data = json_decode(file_get_contents("php://input"), true);
    $driver_id = intval($data['driver_id']);
    $settled_amount = floatval($data['settled_amount']);
    $settled_trips = $conn->real_escape_string($data['settled_trips']); // Sanitize input
    $settled_by = $conn->real_escape_string($data['settled_by']); // Sanitize input
    $settlement_type = $conn->real_escape_string($data['settlement_type']); // Sanitize input

    // Insert into the settlement table
    $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) === TRUE) {
        $response['message'] = "Earnings settled successfully.";
    } else {
        $response['error'] = "Error settling earnings: " . $conn->error;
    }
} catch (Exception $e) {
    $response['error'] = $e->getMessage();
}

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