<!-- Path: app/Views/admin/responder_form.view.php -->
<!-- Include Leaflet CSS and Geocoder CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />

<div class="bg-slate-50 min-h-[calc(100vh-64px)] py-8">
    <div class="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8">
        
        <div class="mb-6">
            <h1 class="text-2xl font-bold text-navy-900">Register Responder Unit</h1>
            <p class="text-slate-500 text-sm">Upgrade a standard user account to a Responder role with base coordinates.</p>
        </div>

        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
            <form id="regForm">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-slate-700 mb-1">Select User Account (Must be registered first)</label>
                    <select name="user_id" required class="w-full px-3 py-2 border rounded-md focus:outline-none focus:border-brandBlue-500">
                        <option value="" disabled selected>-- Select User --</option>
                        @foreach($users as $user)
                            <option value="{{ $user['id'] }}">{{ $user['full_name'] }} ({{ $user['email'] }})</option>
                        @endforeach
                    </select>
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm font-medium text-slate-700 mb-1">Assign Category</label>
                    <select name="category_id" required class="w-full px-3 py-2 border rounded-md focus:outline-none focus:border-brandBlue-500">
                        @foreach($categories as $cat)
                            <option value="{{ $cat['id'] }}">{{ $cat['name'] }}</option>
                        @endforeach
                    </select>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-slate-700 mb-1">Organization Name (e.g., Engine Co. 42)</label>
                    <input type="text" name="organization_name" required class="w-full px-3 py-2 border rounded-md focus:outline-none focus:border-brandBlue-500">
                </div>

                <!-- Map Container -->
                <div class="mb-4">
                    <label class="block text-sm font-medium text-slate-700 mb-1">Pinpoint Base Location</label>
                    <p class="text-xs text-slate-500 mb-2">Use the search icon (🔍) on the map or click/drag the marker to set the location.</p>
                    <div id="osm-map" class="w-full rounded-md border border-slate-300" style="height: 350px; z-index: 1;"></div>
                </div>

                <div class="grid grid-cols-2 gap-4 mb-6">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Base Latitude</label>
                        <input type="text" id="latInput" name="base_latitude" placeholder="e.g. 40.7128" required readonly class="w-full px-3 py-2 border rounded-md bg-slate-50 focus:outline-none focus:border-brandBlue-500 text-slate-600">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Base Longitude</label>
                        <input type="text" id="lngInput" name="base_longitude" placeholder="e.g. -74.0060" required readonly class="w-full px-3 py-2 border rounded-md bg-slate-50 focus:outline-none focus:border-brandBlue-500 text-slate-600">
                    </div>
                </div>

                <button type="submit" id="submitBtn" class="w-full bg-navy-900 hover:bg-navy-800 text-white py-3 rounded-md font-bold transition-colors">Complete Registration</button>
            </form>
        </div>
    </div>
</div>

@addScript
<!-- Include Leaflet JS and Geocoder JS -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>

<script>
$(document).ready(function() {
    
    // --- MAP INITIALIZATION ---
    // Default coordinates set to Port Harcourt, Rivers, Nigeria
    const defaultLat = 4.8156;
    const defaultLng = 7.0498;

    // Initialize map
    const map = L.map('osm-map').setView([defaultLat, defaultLng], 12);

    // Add OpenStreetMap tiles
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    // Add Draggable Marker
    let marker = L.marker([defaultLat, defaultLng], {
        draggable: true
    }).addTo(map);

    // Function to update input fields
    function updateLocationInputs(lat, lng) {
        $('#latInput').val(lat.toFixed(6));
        $('#lngInput').val(lng.toFixed(6));
    }

    // Set initial values
    updateLocationInputs(defaultLat, defaultLng);

    // Event: Dragging the marker
    marker.on('dragend', function (e) {
        const position = marker.getLatLng();
        updateLocationInputs(position.lat, position.lng);
    });

    // Event: Clicking on the map to move marker
    map.on('click', function(e) {
        marker.setLatLng(e.latlng);
        updateLocationInputs(e.latlng.lat, e.latlng.lng);
    });

    // Add Search/Geocoder Control
    L.Control.geocoder({
        defaultMarkGeocode: false
    }).on('markgeocode', function(e) {
        const bbox = e.geocode.bbox;
        const center = e.geocode.center;
        
        // Move map and marker to searched location
        map.fitBounds(bbox);
        marker.setLatLng(center);
        updateLocationInputs(center.lat, center.lng);
    }).addTo(map);


    // --- FORM SUBMISSION ---
    $('#regForm').on('submit', function(e) {
        e.preventDefault();
        let $btn = $('#submitBtn');
        let orig = $btn.html();
        $btn.html('<i class="fas fa-spinner fa-spin"></i> Saving...').prop('disabled', true);

        $.ajax({
            url: '{{APP_URL}}/admin/responders',
            type: 'POST',
            data: $(this).serialize(),
            success: function(res) {
                if(res.status === 'success') window.location.href = res.redirect;
            },
            error: function() {
                // Assuming showNotification is a predefined function in your layout
                if(typeof showNotification === 'function') {
                    showNotification('error', 'Error', 'Failed to register responder.');
                } else {
                    alert('Failed to register responder.');
                }
                $btn.html(orig).prop('disabled', false);
            }
        });
    });
});
</script>
@endAddScript