<?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 and driver_id are provided
if (!isset($data['trip_id']) || !isset($data['driver_id'])) {
    echo json_encode(['success' => false, 'message' => 'Trip ID or Driver ID missing']);
    exit;
}

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

// Sanitize input
$trip_id = intval($trip_id);
$driver_id = intval($driver_id);

// Check if the driver has any ongoing trips that are not completed
$check_sql = "SELECT * FROM new_trip_booking WHERE driver = $driver_id AND status != 'completed'";
$check_result = $conn->query($check_sql);

if ($check_result->num_rows > 0) {
    echo json_encode(['success' => false, 'message' => 'You have an incompleted trip. Please complete it before accepting a new one.']);
    $conn->close();
    exit;
}

// Update the trip status to 'accepted' and assign the driver
$update_sql = "UPDATE new_trip_booking SET status = 'accepted', driver = $driver_id WHERE id = $trip_id AND status = 'pending'";

if ($conn->query($update_sql) === TRUE) {
    echo json_encode(['success' => true, 'message' => 'Trip accepted successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to accept trip: ' . $conn->error]);
}

$conn->close();
?>
