<?php
header('Content-Type: application/json');
include '../db.php'; // Include your database connection file

// Retrieve JSON input
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// Check if trip_id, driver_id, and earnings are provided
if (!isset($data['trip_id']) || !isset($data['driver_id']) || !isset($data['earnings'])) {
    echo json_encode(['success' => false, 'message' => 'Trip ID, Driver ID or Earnings missing']);
    exit;
}

$trip_id = $data['trip_id'];
$driver_id = $data['driver_id'];
$earnings = $data['earnings'];

// Update the trip status to 'completed' and insert earnings
$sql = "UPDATE new_trip_booking SET status = 'completed' WHERE id = $trip_id";
$insertEarningsSql = "INSERT INTO earnings (driver_id, amount) VALUES ($driver_id, $earnings)";

if ($conn->query($sql) === TRUE && $conn->query($insertEarningsSql) === TRUE) {
    echo json_encode(['success' => true, 'message' => 'Trip completed successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to complete trip']);
}

$conn->close();
?>
