<?php
include("../cn.php");
$driver = $_REQUEST["id"];
$bookingno = $_REQUEST["BookingNo"];

// STEP 1: Verify driver exists in driver table
$find_driver_sql = "SELECT driver_id FROM driver WHERE driver_id = '$driver'";
$find_driver_result = mysqli_query($connect, $find_driver_sql);

// Check if driver was found
if ($find_driver_result && mysqli_num_rows($find_driver_result) > 0) {
    
    // STEP 2: Update rentedcars with the driver_id
    $sql = "UPDATE rentedcars 
            SET `status`='Pending', 
                `last_canceler_id` = '$driver', 
                `driver_id`=NULL 
            WHERE `BookingNumber`='$bookingno' 
            AND `driver_id`='$driver' 
            AND `StartTime` IS NULL";
    
    $result = mysqli_query($connect, $sql);
    
    // STEP 3: Update driver availability
    $query = "UPDATE driver 
              SET driver_availability = 'yes' 
              WHERE driver_id = '$driver'";
    
    $result1 = mysqli_query($connect, $query);
    
    // Check if both updates succeeded
    if ($result && $result1) {
        $response["code"] = "200";
        $response["msg"] = "Ride Cancelled Successfully";
    } else {
        $response["code"] = "202";
        $response["msg"] = "Trip Started, Ride cannot be cancelled.";
    }
    
} else {
    // Driver not found in driver table
    $response["code"] = "202";
    $response["msg"] = "Cancellation Failed: Driver not found";
}

echo json_encode($response);
?>