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

// Retrieve query parameters
$selectedType = isset($_GET['selected_type']) ? $_GET['selected_type'] : null;
$current_lat = isset($_GET['current_lat']) ? $_GET['current_lat'] : null;
$current_lng = isset($_GET['current_lng']) ? $_GET['current_lng'] : null;

// Check if parameters are valid
if ($selectedType && $current_lat && $current_lng) {
    // Prepare SQL query
    $sql = "SELECT id, driver_name, phone, vehicle_type, vehicle_current_lat, vehicle_current_lng,
            (6371 * acos(cos(radians(?)) * cos(radians(vehicle_current_lat)) * cos(radians(vehicle_current_lng) - radians(?)) + sin(radians(?)) * sin(radians(vehicle_current_lat)))) AS distance
            FROM registered_vehicles
            WHERE vehicle_type = ?
            HAVING distance < 3
            ORDER BY distance";

    if ($stmt = $conn->prepare($sql)) {
        // Bind parameters
        $stmt->bind_param('ddds', $current_lat, $current_lng, $current_lat, $selectedType);
        $stmt->execute();
        $result = $stmt->get_result();

        $vehicles = array();
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $vehicles[] = $row;
            }
        }
        

        // Return JSON response
        echo json_encode($vehicles);

        $stmt->close();
    } else {
        echo json_encode(['error' => 'Failed to prepare statement']);
    }
} else {
    echo json_encode(['error' => 'Invalid parameters']);
}

$conn->close();
?>
