@extends(ucfirst(activeGuard()) . '.' . layout())
@section('pagetitle', __('trans.branches'))

@section('content')
    <form method="POST" action="{{ route(activeGuard() . '.branches.store') }}" enctype="multipart/form-data">
        @csrf
        <div class="row">

            <div class="form-group col-md-6">
                <label for="title_ar">@lang('trans.title_ar')</label>
                <input type="text" name="title_ar" id="title_ar" class="form-control" required value="">
            </div>
            <div class="form-group col-md-6">
                <label for="title_en">@lang('trans.title_en')</label>
                <input type="text" name="title_en" id="title_en" class="form-control" required value="">
            </div>

            <div class="form-group col-md-6">
                <label for="phone">@lang('trans.phone')</label>
                <input type="hidden" name="country_code" value="{{ country_code() }}">
                <input type="hidden" name="phone_code" value="{{ phone_code() }}">
                <input type="number" maxlength="10" minlength="8" min="0" class="form-control" id="phone" name="phone" required>
            </div>
            <div class="form-group col-md-6">
                <label for="whatsapp">@lang('trans.whatsapp')</label>
                <input type="hidden" name="country_code" value="{{ country_code() }}">
                <input type="hidden" id="whatsapp_code" name="whatsapp_code" value="{{ phone_code() }}">
                <input type="number" maxlength="10" minlength="8" min="0" class="form-control" id="whatsapp" name="whatsapp" required>
            </div>


            <div class="form-group col-md-6">
                <label for="country_id">@lang('trans.country')</label>
                <select class="form-control" required id="country_id" name="country_id">
                    <option disabled hidden selected>@lang('trans.Select')</option>
                    @foreach ($Countries as $Country)
                        <option value="{{ $Country->id }}">{{ $Country->title() }}</option>
                    @endforeach
                </select>
            </div>

            <div class="form-group col-md-6">
                <label for="region_id">@lang('trans.region')</label>
                <select class="form-control select2" required id="region_id" name="region_id">
                    <option disabled hidden selected>@lang('trans.Select')</option>
                    @foreach ($Regions as $Region)
                        <option value="{{ $Region->id }}">{{ $Region->title() }}</option>
                    @endforeach
                </select>
            </div>

            <div class="form-group col-md-6">
                <label for="block">@lang('trans.block')</label>
                <input type="text" name="block" id="block" class="form-control" required value="">
            </div>

            <div class="form-group col-md-6">
                <label for="road">@lang('trans.road')</label>
                <input type="text" name="road" id="road" class="form-control" required value="">
            </div>

            <div class="form-group col-md-6">
                <label for="building">@lang('trans.building')</label>
                <input type="text" name="building" id="building" class="form-control" required value="">
            </div>

            <div class="form-group col-md-6">
                <label for="apartment">@lang('trans.apartment')</label>
                <input type="text" name="apartment" id="apartment" class="form-control" required value="">
            </div>

            <div class="form-group col-md-6">
                <label for="building_no">@lang('trans.building_no')</label>
                <input type="text" name="building_no" id="building_no" class="form-control" required value="">
            </div>


            <input readonly type="hidden" value="{{ 24.7730479 }}" name="lat" id="lat" class="form-control"
                required>
            <input readonly type="hidden" value="{{ 46.7792492 }}" name="long" id="long" class="form-control"
                required>

            <div class="form-group col-12 my-3">
                <div class="col-md-12" id="map" style="height: 500px;width: 100%">

                </div>
            </div>


            <div class="clearfix"></div>
            <div class="col-12 my-4">
                <div class="button-group">
                    <button type="submit" class="main-btn btn-hover w-100 text-center">
                        {{ __('trans.Submit') }}
                    </button>
                </div>
            </div>
        </div>
    </form>

    @include('select2')
    @include('whatsapp')
@endsection



@push('js')
    <!-- Leaflet JS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

    <script>
        let map;
        let marker;

        // Initialize map
        function initMap() {
            var initialLat = {{ 24.7730479 }};
            var initialLng = {{ 46.7792492 }};

            // Create map
            map = L.map('map').setView([initialLat, initialLng], 12);

            // Add OpenStreetMap tile layer
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors',
                maxZoom: 19
            }).addTo(map);

            // Add marker
            marker = L.marker([initialLat, initialLng], {
                draggable: true
            }).addTo(map);

            // Update coordinates when marker is dragged
            marker.on('dragend', function(e) {
                var position = marker.getLatLng();
                updateCoordinates(position.lat, position.lng);
            });

            // Update coordinates when map is clicked
            map.on('click', function(e) {
                marker.setLatLng(e.latlng);
                updateCoordinates(e.latlng.lat, e.latlng.lng);
            });

            // Add search control
            addSearchControl();

            // Add locate control
            addLocateControl();
        }

        function updateCoordinates(lat, lng) {
            $("#lat").val(lat);
            $("#long").val(lng);
        }

        function addSearchControl() {
            var searchContainer = L.Control.extend({
                options: {
                    position: 'topleft'
                },
                onAdd: function(map) {
                    var container = L.DomUtil.create('div', 'leaflet-bar leaflet-control');
                    container.style.backgroundColor = 'white';
                    container.style.padding = '5px';

                    var input = L.DomUtil.create('input', '', container);
                    input.type = 'text';
                    input.placeholder = "{{ __('trans.pick_your_location') }}";
                    input.id = 'search-input';
                    input.style.border = 'none';
                    input.style.padding = '5px 10px';
                    input.style.fontSize = '14px';
                    input.style.width = '250px';

                    var button = L.DomUtil.create('button', '', container);
                    button.innerHTML = "{{ __('trans.search') }}";
                    button.style.border = 'none';
                    button.style.padding = '5px 15px';
                    button.style.backgroundColor = '#1a73e8';
                    button.style.color = 'white';
                    button.style.cursor = 'pointer';
                    button.style.marginLeft = '5px';

                    L.DomEvent.disableClickPropagation(container);

                    button.onclick = function() {
                        var address = input.value;
                        if (address) {
                            searchLocation(address);
                        }
                    };

                    input.onkeypress = function(e) {
                        if (e.key === 'Enter') {
                            e.preventDefault();
                            var address = input.value;
                            if (address) {
                                searchLocation(address);
                            }
                        }
                    };

                    return container;
                }
            });

            map.addControl(new searchContainer());
        }

        function addLocateControl() {
            var locateContainer = L.Control.extend({
                options: {
                    position: 'bottomright'
                },
                onAdd: function(map) {
                    var button = L.DomUtil.create('button', 'leaflet-bar leaflet-control');
                    button.innerHTML = '📍';
                    button.title = 'Your Location';
                    button.style.backgroundColor = 'white';
                    button.style.width = '40px';
                    button.style.height = '40px';
                    button.style.border = 'none';
                    button.style.cursor = 'pointer';
                    button.style.fontSize = '20px';

                    L.DomEvent.disableClickPropagation(button);

                    button.onclick = function() {
                        if (navigator.geolocation) {
                            button.innerHTML = '⏳';
                            navigator.geolocation.getCurrentPosition(function(position) {
                                var lat = position.coords.latitude;
                                var lng = position.coords.longitude;

                                map.setView([lat, lng], 15);
                                marker.setLatLng([lat, lng]);
                                updateCoordinates(lat, lng);

                                button.innerHTML = '📍';
                            }, function(error) {
                                alert('Unable to get your location');
                                button.innerHTML = '📍';
                            });
                        } else {
                            alert('Geolocation is not supported by your browser');
                        }
                    };

                    return button;
                }
            });

            map.addControl(new locateContainer());
        }

        function searchLocation(address) {
            // Using Nominatim (OpenStreetMap's geocoding service)
            var url = 'https://nominatim.openstreetmap.org/search?format=json&q=' + encodeURIComponent(address);

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data && data.length > 0) {
                        var lat = parseFloat(data[0].lat);
                        var lng = parseFloat(data[0].lon);

                        map.setView([lat, lng], 15);
                        marker.setLatLng([lat, lng]);
                        updateCoordinates(lat, lng);
                    } else {
                        alert('Location not found');
                    }
                })
                .catch(error => {
                    console.error('Search error:', error);
                    alert('Error searching location');
                });
        }

        // Initialize map when page loads
        document.addEventListener('DOMContentLoaded', function() {
            initMap();
        });
    </script>

    <script>
        const allRegions = @json($Regions);

        $(document).on("change", "#country_id", function() {
            const countryId = $(this).val();

            // Filter regions by selected country
            const filteredRegions = allRegions.filter(r => r.country_id == countryId);

            // Reset region dropdown
            let options = '<option disabled hidden selected>@lang('trans.Select')</option>';

            // Build options list
            filteredRegions.forEach(region => {
                options += `<option value="${region.id}">${region.title_{{ lang() }}}</option>`;
            });

            $('#region_id').html(options).prop('disabled', false);

            // Refresh select2 if used
            if ($('#region_id').hasClass('select2')) {
                $('#region_id').trigger('change');
            }
        });
    </script>
@endpush



@push('css')
    <style>
        #map {
            z-index: 1;
        }

        .leaflet-control {
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
        }

        #search-input:focus {
            outline: none;
        }

        @media (max-width: 575.98px) {
            #search-input {
                width: 150px !important;
            }
        }
    </style>
@endpush
