@extends('admin.layouts.app')

@section('title', 'Create Shipment')

@section('head')
<link href="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.css" rel="stylesheet"/>
<style>
    .map-container {
        height: 300px;
        margin-bottom: 15px;
        border-radius: 0.375rem;
        overflow: hidden;
    }
</style>
@endsection

@section('content')
<div class="mb-6">
    <div class="flex items-center justify-between">
        <h1 class="text-2xl font-semibold text-gray-800">Create New Shipment</h1>
        <a href="{{ route('admin.shipments.index') }}" 
           class="flex items-center px-3 py-2 text-sm font-medium rounded-md text-gray-600 bg-white hover:bg-gray-50 border border-gray-300">
            <i class="fas fa-arrow-left mr-2"></i> Back to Shipments
        </a>
    </div>
</div>

<form action="{{ route('admin.shipments.store') }}" method="POST" enctype="multipart/form-data">
    @csrf
    
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Main Content Column -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Sender Information Card -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-5 py-4 border-b border-gray-200 bg-gray-50">
                    <h2 class="text-lg font-medium text-gray-800">
                        <i class="fas fa-user-circle mr-2 text-blue-600"></i> Sender Information
                    </h2>
                </div>
                <div class="p-5">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div>
                            <label for="sender_name" class="block text-sm font-medium text-gray-700 mb-1">Full Name</label>
                            <input type="text" name="sender_name" id="sender_name" 
                                   value="{{ old('sender_name') }}"
                                   class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            @error('sender_name')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label for="sender_email" class="block text-sm font-medium text-gray-700 mb-1">Email Address</label>
                            <input type="email" name="sender_email" id="sender_email" 
                                   value="{{ old('sender_email') }}"
                                   class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            @error('sender_email')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label for="sender_contact" class="block text-sm font-medium text-gray-700 mb-1">Phone Number</label>
                            <input type="text" name="sender_contact" id="sender_contact" 
                                   value="{{ old('sender_contact') }}"
                                   class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            @error('sender_contact')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label for="sender_address" class="block text-sm font-medium text-gray-700 mb-1">Address</label>
                            <input type="text" name="sender_address" id="sender_address" 
                                   value="{{ old('sender_address') }}"
                                   class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            @error('sender_address')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>
                    </div>
                </div>
            </div>

            <!-- Receiver Information Card -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-5 py-4 border-b border-gray-200 bg-gray-50">
                    <h2 class="text-lg font-medium text-gray-800">
                        <i class="fas fa-user mr-2 text-blue-600"></i> Receiver Information
                    </h2>
                </div>
                <div class="p-5">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div>
                            <label for="receiver_name" class="block text-sm font-medium text-gray-700 mb-1">Full Name</label>
                            <input type="text" name="receiver_name" id="receiver_name" 
                                   value="{{ old('receiver_name') }}"
                                   class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            @error('receiver_name')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label for="receiver_email" class="block text-sm font-medium text-gray-700 mb-1">Email Address</label>
                            <input type="email" name="receiver_email" id="receiver_email" 
                                   value="{{ old('receiver_email') }}"
                                   class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            @error('receiver_email')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label for="receiver_contact" class="block text-sm font-medium text-gray-700 mb-1">Phone Number</label>
                            <input type="text" name="receiver_contact" id="receiver_contact" 
                                   value="{{ old('receiver_contact') }}"
                                   class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            @error('receiver_contact')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label for="receiver_address" class="block text-sm font-medium text-gray-700 mb-1">Address</label>
                            <input type="text" name="receiver_address" id="receiver_address" 
                                   value="{{ old('receiver_address') }}"
                                   class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            @error('receiver_address')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>
                    </div>
                </div>
            </div>

            <!-- Origin Location Card -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-5 py-4 border-b border-gray-200 bg-gray-50">
                    <h2 class="text-lg font-medium text-gray-800">
                        <i class="fas fa-map-marker-alt mr-2 text-blue-600"></i> Origin Location
                    </h2>
                </div>
                <div class="p-5">
                    <p class="text-sm text-gray-500 mb-3">Click on the map to set the origin location or use the search feature</p>
                    <div id="origin-map" class="map-container border border-gray-300"></div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5 mt-4">
                        <div>
                            <label for="dispatch_location" class="block text-sm font-medium text-gray-700 mb-1">Dispatch Location</label>
                            <input type="text" name="dispatch_location" id="dispatch_location" 
                                value="{{ old('dispatch_location') }}"
                                class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            @error('dispatch_location')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>
                        
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label for="origin_latitude" class="block text-sm font-medium text-gray-700 mb-1">Latitude</label>
                                <input type="text" name="origin_latitude" id="origin_latitude" 
                                    value="{{ old('origin_latitude') }}"
                                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            </div>
                            <div>
                                <label for="origin_longitude" class="block text-sm font-medium text-gray-700 mb-1">Longitude</label>
                                <input type="text" name="origin_longitude" id="origin_longitude" 
                                    value="{{ old('origin_longitude') }}"
                                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Destination Location Card -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-5 py-4 border-b border-gray-200 bg-gray-50">
                    <h2 class="text-lg font-medium text-gray-800">
                        <i class="fas fa-flag-checkered mr-2 text-blue-600"></i> Destination Location
                    </h2>
                </div>
                <div class="p-5">
                    <p class="text-sm text-gray-500 mb-3">Click on the map to set the destination location or use the search feature</p>
                    <div id="destination-map" class="map-container border border-gray-300"></div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5 mt-4">
                        <div>
                            <label for="destination" class="block text-sm font-medium text-gray-700 mb-1">Destination</label>
                            <input type="text" name="destination" id="destination" 
                                value="{{ old('destination') }}"
                                class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            @error('destination')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>
                        
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label for="destination_latitude" class="block text-sm font-medium text-gray-700 mb-1">Latitude</label>
                                <input type="text" name="destination_latitude" id="destination_latitude" 
                                    value="{{ old('destination_latitude') }}"
                                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            </div>
                            <div>
                                <label for="destination_longitude" class="block text-sm font-medium text-gray-700 mb-1">Longitude</label>
                                <input type="text" name="destination_longitude" id="destination_longitude" 
                                    value="{{ old('destination_longitude') }}"
                                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Package Details Card -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-5 py-4 border-b border-gray-200 bg-gray-50">
                    <h2 class="text-lg font-medium text-gray-800">
                        <i class="fas fa-box mr-2 text-blue-600"></i> Package Details
                    </h2>
                </div>
                <div class="p-5">
                    <div class="space-y-5">
                        <div>
                            <label for="pdesc" class="block text-sm font-medium text-gray-700 mb-1">Package Description</label>
                            <textarea name="pdesc" id="pdesc" rows="3"
                                    class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">{{ old('pdesc') }}</textarea>
                            @error('pdesc')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label for="image" class="block text-sm font-medium text-gray-700 mb-1">Package Image</label>
                            <input type="file" name="image" id="image"
                                class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 
                                      file:text-sm file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                            @error('image')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Sidebar Column -->
        <div class="space-y-6">
            <!-- Status and Dates Card -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-5 py-4 border-b border-gray-200 bg-gray-50">
                    <h2 class="text-lg font-medium text-gray-800">
                        <i class="fas fa-info-circle mr-2 text-blue-600"></i> Shipment Status
                    </h2>
                </div>
                <div class="p-5 space-y-4">
                    <div>
                        <label for="status" class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                        <select name="status" id="status" 
                                class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            <option value="pending" {{ old('status') == 'pending' ? 'selected' : '' }}>Pending</option>
                            <option value="in_transit" {{ old('status') == 'in_transit' ? 'selected' : '' }}>In Transit</option>
                            <option value="delivered" {{ old('status') == 'delivered' ? 'selected' : '' }}>Delivered</option>
                        </select>
                        @error('status')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="dispatch_date" class="block text-sm font-medium text-gray-700 mb-1">Dispatch Date</label>
                        <input type="date" name="dispatch_date" id="dispatch_date" 
                               value="{{ old('dispatch_date') }}"
                               class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                        @error('dispatch_date')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="delivery_date" class="block text-sm font-medium text-gray-700 mb-1">Expected Delivery Date</label>
                        <input type="date" name="delivery_date" id="delivery_date" 
                               value="{{ old('delivery_date') }}"
                               class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                        @error('delivery_date')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="delivery_time" class="block text-sm font-medium text-gray-700 mb-1">Delivery Time</label>
                        <input type="time" name="delivery_time" id="delivery_time" 
                               value="{{ old('delivery_time') }}"
                               class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                        @error('delivery_time')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>
                </div>
            </div>
            
            <!-- Shipping Details Card -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-5 py-4 border-b border-gray-200 bg-gray-50">
                    <h2 class="text-lg font-medium text-gray-800">
                        <i class="fas fa-truck mr-2 text-blue-600"></i> Shipping Details
                    </h2>
                </div>
                <div class="p-5 space-y-4">
                    <div>
                        <label for="carrier" class="block text-sm font-medium text-gray-700 mb-1">Carrier</label>
                        <input type="text" name="carrier" id="carrier" 
                               value="{{ old('carrier') }}"
                               class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                        @error('carrier')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="carrier_ref" class="block text-sm font-medium text-gray-700 mb-1">Carrier Reference</label>
                        <input type="text" name="carrier_ref" id="carrier_ref" 
                               value="{{ old('carrier_ref') }}"
                               class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                        @error('carrier_ref')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="ship_mode" class="block text-sm font-medium text-gray-700 mb-1">Shipping Mode</label>
                        <select name="ship_mode" id="ship_mode" 
                                class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            <option value="air" {{ old('ship_mode') == 'air' ? 'selected' : '' }}>Air</option>
                            <option value="sea" {{ old('ship_mode') == 'sea' ? 'selected' : '' }}>Sea</option>
                            <option value="land" {{ old('ship_mode') == 'land' ? 'selected' : '' }}>Land</option>
                        </select>
                        @error('ship_mode')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="weight" class="block text-sm font-medium text-gray-700 mb-1">Weight (kg)</label>
                        <input type="text" name="weight" id="weight" 
                               value="{{ old('weight') }}"
                               class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                        @error('weight')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="quantity" class="block text-sm font-medium text-gray-700 mb-1">Quantity</label>
                        <input type="number" name="quantity" id="quantity" 
                               value="{{ old('quantity') }}"
                               class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                        @error('quantity')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>
                </div>
            </div>
            
            <!-- Payment Details Card -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-5 py-4 border-b border-gray-200 bg-gray-50">
                    <h2 class="text-lg font-medium text-gray-800">
                        <i class="fas fa-money-bill-wave mr-2 text-blue-600"></i> Payment Details
                    </h2>
                </div>
                <div class="p-5 space-y-4">
                    <div>
                        <label for="payment_mode" class="block text-sm font-medium text-gray-700 mb-1">Payment Mode</label>
                        <select name="payment_mode" id="payment_mode" 
                                class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                            <option value="cash" {{ old('payment_mode') == 'cash' ? 'selected' : '' }}>Cash</option>
                            <option value="credit_card" {{ old('payment_mode') == 'credit_card' ? 'selected' : '' }}>Credit Card</option>
                            <option value="bank_transfer" {{ old('payment_mode') == 'bank_transfer' ? 'selected' : '' }}>Bank Transfer</option>
                            <option value="cashapp" {{ old('payment_mode') == 'cashapp' ? 'selected' : '' }}>Cashapp</option>
                            <option value="bitcoin" {{ old('payment_mode') == 'bitcoin' ? 'selected' : '' }}>Bitcoin</option>
                        </select>
                        @error('payment_mode')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="total_f" class="block text-sm font-medium text-gray-700 mb-1">Total Freight</label>
                        <input type="text" name="total_f" id="total_f" 
                               value="{{ old('total_f') }}"
                               class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
                        @error('total_f')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>
                </div>
            </div>
            
            <!-- Action Buttons -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="p-5">
                    <button type="submit" 
                            class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 flex justify-center items-center">
                        <i class="fas fa-save mr-2"></i> Create Shipment
                    </button>
                    <a href="{{ route('admin.shipments.index') }}" 
                       class="mt-3 w-full bg-gray-100 text-gray-700 py-2 px-4 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 flex justify-center items-center">
                        <i class="fas fa-times mr-2"></i> Cancel
                    </a>
                </div>
            </div>
        </div>
    </div>
</form>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet-control-geocoder@2.4.0/dist/Control.Geocoder.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Default coordinates
        const defaultLat = 40.7128;
        const defaultLng = -74.0060;
        
        // Initialize origin map
        const originMap = initMap('origin-map', defaultLat, defaultLng);
        
        // Initialize destination map
        const destinationMap = initMap('destination-map', defaultLat, defaultLng);
        
        // Set up location handling for origin
        setupLocationHandling(
            originMap, 
            'dispatch_location', 
            'origin_latitude', 
            'origin_longitude'
        );
        
        // Set up location handling for destination
        setupLocationHandling(
            destinationMap, 
            'destination', 
            'destination_latitude', 
            'destination_longitude'
        );
        
        /**
         * Initialize a map
         */
        function initMap(containerId, defaultLat, defaultLng) {
            // Check if container exists
            const container = document.getElementById(containerId);
            if (!container) {
                console.error(`Map container ${containerId} not found`);
                return null;
            }
            
            try {
                // Create map instance
                const map = L.map(containerId, {
                    scrollWheelZoom: false,
                    zoomControl: true,
                    attributionControl: true
                }).setView([defaultLat, defaultLng], 2);
                
                // Add tile layer
                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
                    maxZoom: 19,
                    errorTileUrl: 'https://cdn.jsdelivr.net/gh/leaflet/Leaflet@1.9.4/dist/images/marker-icon.png'
                }).addTo(map);
                
                // Add geocoding control if available
                try {
                    const geocoder = L.Control.geocoder({
                        defaultMarkGeocode: false,
                        position: 'topleft',
                        placeholder: 'Search for location...',
                        errorMessage: 'Nothing found.'
                    }).addTo(map);
                    
                    // Store geocoder instance on the map
                    map.geocoder = geocoder;
                } catch (error) {
                    console.warn('Geocoder could not be initialized:', error.message);
                }
                
                // Ensure map is properly displayed
                setTimeout(() => {
                    map.invalidateSize();
                }, 100);
                
                return map;
            } catch (error) {
                console.error('Error initializing map:', error);
                container.innerHTML = '<div class="p-4 bg-red-50 text-red-700 text-center">Failed to load map. Please check your internet connection.</div>';
                return null;
            }
        }
        
        /**
         * Setup location handling for a map
         */
        function setupLocationHandling(map, locationInputId, latInputId, lngInputId) {
            if (!map) return;
            
            // Get input elements
            const locationInput = document.getElementById(locationInputId);
            const latInput = document.getElementById(latInputId);
            const lngInput = document.getElementById(lngInputId);
            
            // Check if inputs exist
            if (!locationInput || !latInput || !lngInput) {
                console.error('Input fields not found');
                return;
            }
            
            // Current marker
            let currentMarker = null;
            
            // Try to restore marker from form values if they exist
            if (latInput.value && lngInput.value) {
                const lat = parseFloat(latInput.value);
                const lng = parseFloat(lngInput.value);
                
                if (!isNaN(lat) && !isNaN(lng)) {
                    setMarker(map, L.latLng(lat, lng), locationInput.value);
                    map.setView([lat, lng], 10);
                }
            }
            
            // Function to set a marker
            function setMarker(map, latlng, locationName = '') {
                // Remove existing marker
                if (currentMarker) {
                    map.removeLayer(currentMarker);
                }
                
                // Create a new marker
                currentMarker = L.marker(latlng, {
                    draggable: true
                }).addTo(map);
                
                // Create popup content
                const coords = `${latlng.lat.toFixed(6)}, ${latlng.lng.toFixed(6)}`;
                let popupContent = `<b>${locationName || 'Selected Location'}</b><br>${coords}`;
                currentMarker.bindPopup(popupContent).openPopup();
                
                // Update form fields
                latInput.value = latlng.lat.toFixed(6);
                lngInput.value = latlng.lng.toFixed(6);
                
                // Handle marker drag end
                currentMarker.on('dragend', function(e) {
                    const position = e.target.getLatLng();
                    latInput.value = position.lat.toFixed(6);
                    lngInput.value = position.lng.toFixed(6);
                    
                    // Update popup content
                    const coords = `${position.lat.toFixed(6)}, ${position.lng.toFixed(6)}`;
                    let popupContent = `<b>${locationInput.value || 'Selected Location'}</b><br>${coords}`;
                    currentMarker.setPopupContent(popupContent);
                    
                    // Reverse geocode if geocoder is available
                    if (map.geocoder) {
                        try {
                            map.geocoder.options.geocoder.reverse(position, map.options.crs.scale(map.getZoom()), results => {
                                if (results && results.length > 0) {
                                    locationInput.value = results[0].name;
                                    
                                    // Update popup with the location name
                                    const popupContent = `<b>${results[0].name}</b><br>${coords}`;
                                    currentMarker.setPopupContent(popupContent);
                                }
                            });
                        } catch (error) {
                            console.warn('Reverse geocoding failed:', error.message);
                        }
                    }
                });
            }
            
            // Handle map click
            map.on('click', function(e) {
                setMarker(map, e.latlng);
                
                // Reverse geocode if geocoder is available
                if (map.geocoder) {
                    try {
                        map.geocoder.options.geocoder.reverse(e.latlng, map.options.crs.scale(map.getZoom()), results => {
                            if (results && results.length > 0) {
                                locationInput.value = results[0].name;
                                
                                // Update popup with the location name
                                const coords = `${e.latlng.lat.toFixed(6)}, ${e.latlng.lng.toFixed(6)}`;
                                const popupContent = `<b>${results[0].name}</b><br>${coords}`;
                                if (currentMarker) {
                                    currentMarker.setPopupContent(popupContent);
                                }
                            }
                        });
                    } catch (error) {
                        console.warn('Reverse geocoding failed:', error.message);
                    }
                }
            });
            
            // Handle geocoder results if available
            if (map.geocoder) {
                map.geocoder.on('markgeocode', function(e) {
                    const latlng = e.geocode.center;
                    setMarker(map, latlng, e.geocode.name);
                    locationInput.value = e.geocode.name;
                    map.fitBounds(e.geocode.bbox);
                });
            }
            
            // Update lat/lng when location input changes (if geocoder is available)
            locationInput.addEventListener('change', function(e) {
                if (map.geocoder && e.target.value.trim() !== '') {
                    try {
                        // Forward geocode the location name
                        map.geocoder.options.geocoder.geocode(e.target.value, results => {
                            if (results && results.length > 0) {
                                const result = results[0];
                                setMarker(map, result.center, result.name);
                                map.fitBounds(result.bbox);
                            }
                        });
                    } catch (error) {
                        console.warn('Forward geocoding failed:', error.message);
                    }
                }
            });
        }
    });
</script>
@endsection