let map;

function initMap() {

    map = new google.maps.Map(document.getElementById("map"), {
        zoom: 12,
        center: { lat: 1.3521, lng: 103.8198 }
    });

    loadDrivers();
}

function loadDrivers() {

    fetch("api/get_available_drivers.php")
        .then(res => res.json())
        .then(data => {

            data.drivers.forEach(driver => {

                let position = {
                    lat: parseFloat(driver.current_lat),
                    lng: parseFloat(driver.current_lng)
                };

                let marker = new google.maps.Marker({
                    position: position,
                    map: map,
                    title: driver.full_name
                });

                let info = new google.maps.InfoWindow({
                    content: `
                        <strong>${driver.full_name}</strong><br>
                        <button onclick="assignDriver(${driver.id})"
                        style="margin-top:5px;">
                        Assign Driver
                        </button>
                    `
                });

                marker.addListener("click", () => {
                    info.open(map, marker);
                });
            });
        });
}

function assignDriver(driverId) {

    fetch("api/assign_driver.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            booking_id: bookingId,
            driver_id: driverId
        })
    })
    .then(res => res.json())
    .then(data => {
        alert("Driver Assigned Successfully");
        window.location.href = "dispatch.php";
    });
}

window.onload = initMap;
