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

include '../db.php';

$latitude = isset($_GET['latitude']) ? floatval($_GET['latitude']) : null;
$longitude = isset($_GET['longitude']) ? floatval($_GET['longitude']) : null;
$vehicle_type = isset($_GET['vehicle_type']) ? $conn->real_escape_string($_GET['vehicle_type']) : null;
$radius = 10000; // 10 kilometers in meters

if (is_null($latitude) || is_null($longitude) || is_null($vehicle_type)) {
    echo json_encode(['error' => 'Missing parameters']);
    exit();
}

$sql = "SELECT ntb.*, u.name, u.phone, u.email, u.profile_picture 
        FROM new_trip_booking ntb
        JOIN users u ON ntb.user_id = u.id
        WHERE ntb.status = 'pending'
        AND ntb.vehicle_type = '$vehicle_type'
        AND (
            6371 * acos(
                cos(radians($latitude)) * cos(radians(ntb.pickup_latitude)) * cos(radians(ntb.pickup_longitude) - radians($longitude))
                + sin(radians($latitude)) * sin(radians(ntb.pickup_latitude))
            )
        ) < ($radius / 1000)
        ORDER BY ntb.id DESC";

$result = $conn->query($sql);

$trips = array();
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $trips[] = $row;
    }
    echo json_encode($trips);
} else {
    echo json_encode(['error' => $conn->error]);
}

$conn->close();
?>
