@extends('layouts.theme1')

@section('title', 'Nouveau point de chute')

@section('style')
    <!-- Custom CSS -->
    <link href="{{ asset('theme1/dist/css/style.min.css') }}" rel="stylesheet" />
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- Ajout de Leaflet Geosearch CSS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />
    
    <style>
        #map {
            height: 400px;
            width: 100%;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .coordinates-info {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
        }
        .search-container {
            position: relative;
            margin-bottom: 15px;
        }
        .search-input {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid #ced4da;
            border-radius: 5px;
            font-size: 14px;
        }
        .search-results {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #ced4da;
            border-radius: 5px;
            max-height: 200px;
            overflow-y: auto;
            display: none;
            z-index: 1000;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .search-result-item {
            padding: 10px 15px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }
        .search-result-item:hover {
            background-color: #f8f9fa;
        }
        .search-result-item:last-child {
            border-bottom: none;
        }
        .search-result-item .result-name {
            font-weight: 500;
            color: #333;
        }
        .search-result-item .result-address {
            font-size: 12px;
            color: #666;
        }
        .quick-search-btn {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #007bff;
            cursor: pointer;
        }
        .search-header {
            background-color: #f8f9fa;
            padding: 8px 15px;
            font-size: 12px;
            color: #666;
            border-bottom: 1px solid #dee2e6;
        }
    </style>
@endsection

@section('content')
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="border-bottom title-part-padding">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h4 class="card-title mb-1">Nouveau point de chute</h4>
                            <h5>{{ $user['displayName'] ?? $user['email'] ?? 'Utilisateur' }}</h5>
                        </div>
                        <a href="{{ route('user-profiles.location-points', $userId) }}" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> Retour
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <form action="{{ route('user-profiles.location-points.store', $userId) }}" method="POST" id="locationForm">
                        @csrf

                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label fw-bold">Nom du point <span class="text-danger">*</span></label>
                                <input type="text" class="form-control @error('name') is-invalid @enderror" 
                                    name="name" value="{{ old('name') }}" required>
                                @error('name')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <!-- NOUVEAU : Champ de recherche rapide -->
                            <div class="col-md-12 mb-3">
                                <label class="form-label fw-bold">Recherche rapide de lieu</label>
                                <div class="search-container">
                                    <input type="text" 
                                        class="search-input" 
                                        id="quickSearch" 
                                        placeholder="Tapez le nom d'un lieu, une adresse... (ex: 'Bobo dioulasso', 'Université Nazi boni')"
                                        autocomplete="off">
                                    <div class="search-results" id="searchResults"></div>
                                </div>
                                <small class="text-muted">
                                    <i class="fas fa-search"></i> 
                                    Commencez à taper pour rechercher un lieu instantanément
                                </small>
                            </div>

                            <div class="col-md-12 mb-3">
                                <label class="form-label fw-bold">Adresse</label>
                                <input type="text" class="form-control @error('address') is-invalid @enderror" 
                                    name="address" id="address" value="{{ old('address') }}" placeholder="Adresse complète" readonly>
                                @error('address')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="col-md-12 mb-3">
                                <label class="form-label fw-bold">Description</label>
                                <textarea class="form-control @error('description') is-invalid @enderror" 
                                    name="description" rows="2">{{ old('description') }}</textarea>
                                @error('description')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="col-md-12 mb-3">
                                <label class="form-label fw-bold">Localisation sur la carte</label>
                                <div id="map"></div>
                                
                                <div class="row mt-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Latitude</label>
                                        <input type="number" step="any" class="form-control @error('latitude') is-invalid @enderror" 
                                            name="latitude" id="latitude" value="{{ old('latitude', 5.3167) }}" >
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Longitude</label>
                                        <input type="number" step="any" class="form-control @error('longitude') is-invalid @enderror" 
                                            name="longitude" id="longitude" value="{{ old('longitude', -4.0333) }}" >
                                    </div>
                                </div>

                                <div class="coordinates-info mt-2">
                                    <small class="text-muted">
                                        <i class="fas fa-info-circle"></i> 
                                        Cliquez sur la carte pour positionner le point, ou utilisez la recherche rapide ci-dessus.
                                    </small>
                                </div>
                            </div>
                        </div>

                        <div class="mt-3">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> Enregistrer
                            </button>
                            <a href="{{ route('user-profiles.location-points', $userId) }}" class="btn btn-secondary">
                                <i class="fas fa-times"></i> Annuler
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
 
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <!-- Ajout de la bibliothèque de géocodage -->
    <script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>

    <script>
        $(document).ready(function() {
            // Initialisation de la carte
            var map = L.map('map').setView([5.3167, -4.0333], 13);
            var marker;
            var searchTimeout;

            // Fournisseur de tuiles
            var tileProvider = 'https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}';

            L.tileLayer(tileProvider, {
                attribution: '© OpenStreetMap contributors'
            }).addTo(map);

            // Fonction pour mettre à jour le marqueur et les champs
            function updateLocation(lat, lng, address = '') {
                $('#latitude').val(lat.toFixed(6));
                $('#longitude').val(lng.toFixed(6));
                
                if (address) {
                    $('#address').val(address);
                }

                if (marker) {
                    marker.setLatLng([lat, lng]);
                } else {
                    marker = L.marker([lat, lng], { draggable: true }).addTo(map);
                    
                    marker.on('dragend', function(e) {
                        var pos = e.target.getLatLng();
                        updateLocation(pos.lat, pos.lng);
                        
                        // Reverse geocoding pour obtenir l'adresse
                        reverseGeocode(pos.lat, pos.lng);
                    });
                }
                
                map.setView([lat, lng], 15);
            }

            // Fonction de reverse geocoding (obtenir l'adresse à partir des coordonnées)
            function reverseGeocode(lat, lng) {
                var geocoder = L.Control.Geocoder.nominatim();
                geocoder.reverse({ lat: lat, lng: lng }, map.options.crs, function(results) {
                    if (results && results.length > 0) {
                        $('#address').val(results[0].name);
                    }
                });
            }

            // Fonction de recherche de lieux
            function searchPlaces(query) {
                if (query.length < 3) {
                    $('#searchResults').hide();
                    return;
                }

                // Utilisation de Nominatim (OpenStreetMap) pour la recherche
                var url = 'https://nominatim.openstreetmap.org/search';
                
                $.ajax({
                    url: url,
                    data: {
                        q: query,
                        format: 'json',
                        limit: 8,
                        addressdetails: 1
                    },
                    beforeSend: function() {
                        $('#searchResults').html('<div class="search-result-item">Recherche en cours...</div>').show();
                    },
                    success: function(results) {
                        if (results.length === 0) {
                            $('#searchResults').html('<div class="search-result-item">Aucun résultat trouvé</div>').show();
                            return;
                        }

                        var html = '<div class="search-header">' + results.length + ' résultat(s) trouvé(s)</div>';
                        
                        $.each(results, function(index, result) {
                            var displayName = result.display_name;
                            var shortName = displayName.split(',').slice(0, 3).join(',');
                            
                            html += '<div class="search-result-item" data-lat="' + result.lat + '" data-lng="' + result.lon + '" data-address="' + displayName + '">' +
                                   '<div class="result-name">' + (result.name || shortName) + '</div>' +
                                   '<div class="result-address">' + shortName + '</div>' +
                                   '</div>';
                        });
                        
                        $('#searchResults').html(html).show();
                    },
                    error: function() {
                        $('#searchResults').html('<div class="search-result-item">Erreur lors de la recherche</div>').show();
                    }
                });
            }

            // Recherche en temps réel
            $('#quickSearch').on('input', function() {
                var query = $(this).val();
                
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(function() {
                    searchPlaces(query);
                }, 300); // Délai de 300ms pour éviter trop de requêtes
            });

            // Clic sur un résultat de recherche
            $(document).on('click', '.search-result-item', function() {
                var lat = parseFloat($(this).data('lat'));
                var lng = parseFloat($(this).data('lng'));
                var address = $(this).data('address');
                
                updateLocation(lat, lng, address);
                
                // Remplir automatiquement le nom du point si vide
                var currentName = $('input[name="name"]').val();
                if (!currentName) {
                    var suggestedName = address.split(',').slice(0, 2).join(',');
                    $('input[name="name"]').val(suggestedName);
                }
                
                $('#quickSearch').val('');
                $('#searchResults').hide();
            });

            // Cacher les résultats quand on clique ailleurs
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.search-container').length) {
                    $('#searchResults').hide();
                }
            });

            // Clic sur la carte
            map.on('click', function(e) {
                updateLocation(e.latlng.lat, e.latlng.lng);
                reverseGeocode(e.latlng.lat, e.latlng.lng);
            });

            // Si des coordonnées existent déjà
            var lat = $('#latitude').val();
            var lng = $('#longitude').val();
            if (lat && lng) {
                updateLocation(parseFloat(lat), parseFloat(lng));
            }
        });
    </script>
@endsection