<!DOCTYPE html>
<html>
<head>
    <title>New Delivery Request</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
          integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
          crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
            integrity="sha512-XQoYM8mATgWsiiTcnS9xvXyYPbyDLHO3eMNB1jyRchQGPXdFI/FnWC9vD1GAKjFfxyy7JtKOG//xnHLdj6yP1AA=="
            crossorigin=""></script>
    <style>
        #pickup_mapid, #dropoff_mapid { height: 200px; width: 100%; margin-bottom: 10px; }
    </style>
</head>
<body>
    <h1>Create a New Delivery Request</h1>
    <form id="deliveryForm">
        <div>
            <label for="branch">Branch:</label><br>
            <select id="branch" name="branch" required>
                <option value="">Select Branch</option>
                <option value="kiambu_rd">KFC Kiambu Rd</option>
                <option value="momo_mall">KFC Momo Mall</option>
            </select><br><br>
        </div>
        <div>
            <label>Pickup Location:</label><br>
            <div id="pickup_mapid"></div>
            <input type="hidden" id="pickup_lat" name="pickup_lat">
            <input type="hidden" id="pickup_lng" name="pickup_lng">
            <p>Selected Pickup Coordinates: <span id="selected_pickup_coords"></span></p>
            <br>
        </div>
        <div>
            <label>Drop-off Location:</label><br>
            <div id="dropoff_mapid"></div>
            <input type="hidden" id="dropoff_lat" name="dropoff_lat">
            <input type="hidden" id="dropoff_lng" name="dropoff_lng">
            <p>Selected Drop-off Coordinates: <span id="selected_dropoff_coords"></span></p>
            <br>
        </div>
        <div>
            <label for="items">Items to Deliver:</label><br>
            <textarea id="items" name="items" rows="4" cols="50" required></textarea><br><br>
        </div>
        <button type="submit">Submit Delivery Request</button>
    </form>

    <script>
        // --- Pickup Map ---
        var pickupMap = L.map('pickup_mapid').setView([-1.2921, 36.8219], 13);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(pickupMap);

        var pickupMarker;
        var pickupLatInput = document.getElementById('pickup_lat');
        var pickupLngInput = document.getElementById('pickup_lng');
        var selectedPickupCoordsSpan = document.getElementById('selected_pickup_coords');

        function updatePickup(latlng) {
            if (pickupMarker) {
                pickupMap.removeLayer(pickupMarker);
            }
            pickupMarker = L.marker(latlng).addTo(pickupMap);
            pickupLatInput.value = latlng.lat;
            pickupLngInput.value = latlng.lng;
            selectedPickupCoordsSpan.textContent = latlng.lat.toFixed(6) + ', ' + latlng.lng.toFixed(6);
        }

        pickupMap.on('click', function(e) {
            updatePickup(e.latlng);
        });

        // --- Drop-off Map ---
        var dropoffMap = L.map('dropoff_mapid').setView([-1.2921, 36.8219], 13);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(dropoffMap);

        var dropoffMarker;
        var dropoffLatInput = document.getElementById('dropoff_lat');
        var dropoffLngInput = document.getElementById('dropoff_lng');
        var selectedDropoffCoordsSpan = document.getElementById('selected_dropoff_coords');

        function updateDropoff(latlng) {
            if (dropoffMarker) {
                dropoffMap.removeLayer(dropoffMarker);
            }
            dropoffMarker = L.marker(latlng).addTo(dropoffMap);
            dropoffLatInput.value = latlng.lat;
            dropoffLngInput.value = latlng.lng;
            selectedDropoffCoordsSpan.textContent = latlng.lat.toFixed(6) + ', ' + latlng.lng.toFixed(6);
        }

        dropoffMap.on('click', function(e) {
            updateDropoff(e.latlng);
        });

        // --- Form Submission ---
        document.getElementById('deliveryForm').addEventListener('submit', function(event) {
            event.preventDefault();

            const branch = document.getElementById('branch').value;
            const pickupLat = document.getElementById('pickup_lat').value;
            const pickupLng = document.getElementById('pickup_lng').value;
            const dropoffLat = document.getElementById('dropoff_lat').value;
            const dropoffLng = document.getElementById('dropoff_lng').value;
            const items = document.getElementById('items').value;

            const deliveryData = {
                branch: branch,
                pickup_latitude: parseFloat(pickupLat),
                pickup_longitude: parseFloat(pickupLng),
                dropoff_latitude: parseFloat(dropoffLat),
                dropoff_longitude: parseFloat(dropoffLng),
                items: items
            };

            fetch('/api/new-delivery', { // Replace with your actual backend API endpoint for new deliveries
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(deliveryData),
            })
            .then(response => response.json())
            .then(data => {
                console.log('Delivery request submitted successfully:', data);
                alert('Delivery request submitted successfully!');
                document.getElementById('deliveryForm').reset(); // Optionally clear the form
                // Optionally redirect the user or update the UI
            })
            .catch((error) => {
                console.error('Error submitting delivery request:', error);
                alert('There was an error submitting your delivery request.');
            });
        });
    </script>
</body>
</html>