<?php
include 'db.php';  // Include your database connection file

header('Content-Type: application/json');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = $data['user_id'];
    $pickup_latitude = $data['pickup_latitude'];
    $pickup_longitude = $data['pickup_longitude'];
    $dropoff_latitude = $data['dropoff_latitude'];
    $dropoff_longitude = $data['dropoff_longitude'];
    $vehicle_type = $data['vehicle_type'];
    $distance = $data['distance'];
    $estimated_time = $data['estimated_time'];
    $total_cost = $data['total_cost'];
    $payment_method = $data['payment_method'];
    $scheduled_date_time = isset($data['scheduled_date_time']) ? $data['scheduled_date_time'] : null;

    if (!$user_id || !$pickup_latitude || !$pickup_longitude || !$dropoff_latitude || !$dropoff_longitude || !$vehicle_type || !$distance || !$estimated_time || !$total_cost || !$payment_method) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        exit();
    }

    $stmt = $conn->prepare("INSERT INTO new_trip_booking (user_id, pickup_latitude, pickup_longitude, dropoff_latitude, dropoff_longitude, vehicle_type, distance, estimated_time, total_cost, payment_method, scheduled_date_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Error in prepare statement: ' . $conn->error]);
        exit();
    }

    $stmt->bind_param('iddddsssdss', $user_id, $pickup_latitude, $pickup_longitude, $dropoff_latitude, $dropoff_longitude, $vehicle_type, $distance, $estimated_time, $total_cost, $payment_method, $scheduled_date_time);

    if ($stmt->execute()) {
        $booking_id = $stmt->insert_id; // Get the last inserted ID
        echo json_encode(['success' => true, 'message' => 'Trip booked successfully', 'booking_id' => $booking_id]);
        
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to book trip']);
    }

    $stmt->close();
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}

$conn->close();
?>
