@extends('backend.layouts.app')
@section('title', @$data['title'])

@section('style')
    <style>
        .nav-pills .nav-link {
            height: 40x !important;
            display: flex !important;
            flex-direction: column !important;
            align-items: center !important;
            justify-content: center !important;
            font-size: 1rem !important;
            font-weight: 500 !important;
        }

        .button {
            height: 40px !important;
            display: flex !important;
            flex-direction: column !important;
            align-items: center !important;
            justify-content: center !important;
            font-size: 1rem !important;
            font-weight: 500 !important;
            padding-inline: 25px !important;
            min-width: 150px;
        }

        .modal {
            --bs-modal-zindex: 123;
            z-index: var(--bs-modal-zindex);
        }
        .modal-backdrop {
            --bs-backdrop-zindex: 1;
            z-index: var(--bs-backdrop-zindex);
        }
    </style>
@endsection

@section('content')
    {!! breadcrumb([
        'title' => @$data['title'],
        route('admin.dashboard') => _trans('common.Dashboard'),
        '#' => @$data['title'],
    ]) !!}

    <form method="POST" action="{{ route('user.store') }}" class="card ot-card" enctype="multipart/form-data" autocomplete="off">
        @csrf

        @if ($errors->any())
            <div class="alert alert-danger">
                <ul class=" mb-0">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <div class="card-header bg-light">
            <nav class="nav nav-pills nav-fill">
                <a class="nav-link tab-pills bg-gradient" href="#">{{ _trans('common.Personal Info') }}</a>
                <a class="nav-link tab-pills bg-gradient" href="#">{{ _trans('common.Official Setup') }}</a>
                <a class="nav-link tab-pills bg-gradient" href="#">{{ _trans('common.Weekend & Holiday') }}</a>
            </nav>
        </div>
        <div class="card-body">
            @include('backend.user.employee.form.personal-step')
            @include('backend.user.employee.form.official-step')
            @include('backend.user.employee.form.weekend-holiday-step')
        </div>
        <div class="card-footer text-end">
            <div class="d-flex bg-light p-2">
                <button type="button" id="back_button" class="button btn btn-secondary bg-gradient border-0" onclick="back()">{{ _trans('common.Previous') }}</button>
                <button type="button" id="next_button" class="button btn btn-primary bg-gradient border-0 ms-auto">{{ _trans('common.Next') }}</button>
            </div>
        </div>

        {{-- Hidden data --}}
        <div id="modal-hidden-fields"></div>
    </form>

    <input type="hidden" id="get_attendance_method_data" value="{{ route('user.getAttendanceMethod') }}">

    {{-- modal::start  --}}
    <div class="modal fade lead-modal" id="exampleModalToggle" aria-labelledby="modalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-xl">
            <div class="modal-content data">
                <div class="modal-header modal-header-image mb-3">
                    <h5 class="modal-title text-white">{{ @$data['title'] }} </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                        <i class="fa fa-times text-white" aria-hidden="true"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group mb-3">
                                <label class="form-label" for="name">{{ _trans('settings.Distance (Meters)') }} <span
                                        class="text-danger">*</span></label>
                                <input type="number" id="distance" class="form-control ot-form-control ot-input"
                                    value="{{ old('distance') }}" required
                                    placeholder="{{ _trans('settings.Enter Distance') }}">
                                <small class="form-label fs-10">
                                    {{ _trans('settings.Distance measure in meters') }}</small>
                                @if ($errors->has('distance'))
                                    <div class="error">{{ $errors->first('distance') }}</div>
                                @endif
                            </div>
                        </div>

                        <div class="col-lg-12">
                            <div class="form-group mb-3">
                                <label class="form-label" for="name">{{ _trans('settings.Location') }}
                                    <span class="text-danger">*</span>
                                </label>
                                <div class="col-md-6 d-none">
                                    <input id="pac-input"
                                        class="form-control ot-form-control ot-input controls location" type="text"
                                        placeholder="{{ _trans('settings.Enter Location') }}" required name="location"
                                        onkeydown="return (event.keyCode!=13);" />
                                </div>
                                <div class="row dataTable-btButtons">
                                    <div class="col-lg-12">
                                        <div class="ltn__map-area">
                                            <div class="ltn__map-inner">
                                                <div id="map" class="mapH_500"></div>
                                                <div class="mt-5" id="directions_panel"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="d-flex align-items-center justify-content-end gap-2">
                        <button type="button" id="cancelButton" class="button btn btn-danger bg-gradient">
                            {{ _trans('common.Cancel') }}
                        </button>
                        <button type="button" id="saveButton" class="button btn btn-primary bg-gradient">
                            {{ _trans('common.Save') }}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {{-- modal::end  --}}
@endsection

@section('script')
    <script>
        var current = 0;
        var tabs = $(".tab");
        var tabs_pill = $(".tab-pills");

        loadFormData(current);

        function loadFormData(n) {
            tabs_pill.removeClass("active");
            tabs.addClass("d-none");

            $(tabs_pill[n]).addClass("active");
            $(tabs[n]).removeClass("d-none");

            $("#back_button").attr("disabled", n == 0);
            if (n == tabs.length - 1) {
                $("#next_button")
                    .text("Submit")
                    .removeAttr("onclick")
                    .attr("onclick", "submit()");
            } else {
                $("#next_button")
                    .text("Next")
                    .attr("type", "button")
                    .attr("onclick", "next()");
            }
        }

        function next() {
            if (current < tabs.length - 1) {
                current++;
                loadFormData(current);
            }
        }

        function back() {
            if (current > 0) {
                current--;
                loadFormData(current);
            }
        }

        function submit() {}

        $(".tab-pills").on("click", function () {
            var index = $(this).index();
            current = index;
            loadFormData(current);
        });
    </script>

    <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key={{ @settings('google') }}"></script>

    <script>
        $(document).ready(function () {
            // For ip address
            $('#ip_address_div').hide();

            $('#is_free_ip').on('change', function () {
                var selectedValue = $(this).val();

                if (selectedValue == 0) {
                    $('#ip_address_div').show();
                } else {
                    $('#ip_address_div').hide();
                }
            });

            // For location binding
            $('#location_div').hide();

            $('#is_free_location').on('change', function () {
                var selectedLocationValue = $(this).val();

                if (selectedLocationValue == 0) {
                    $('#location_div').show();
                } else {
                    $('#location_div').hide();
                }
            });
        });
    </script>

    <script>
        $(document).ready(function() {
            let latitude = $('#latitude').val() ?? 40.7127753;
            let longitude = $('#longitude').val() ?? -74.0059728;
            let distance = $('#distance').val() ?? 0;
            var map;
            var marker;
            var circle;

            function circleMap(){
                // remove old circle map
                if (circle) {
                circle.setMap(null);
                }

                //  radius_map = parseFloat( parseFloat(3.14159 * (parseFloat(distance) * parseFloat(distance))) / 1000 );
                circle = new google.maps.Circle({
                map: map,
                radius: parseFloat(distance),    // 10 miles in metres
                fillColor: '#36AA4A',
                strokeColor: '#36AA4A',
                strokeOpacity: 0.5,
                strokeWeight: 2,
                fillOpacity: 0.5
                });

                circle.bindTo('center', marker, 'position');
            }

            function mapInit(){
                defaultLatLong = {
                    lat: parseFloat(latitude) ,
                    lng: parseFloat(longitude) 
                };

                map = new google.maps.Map(document.getElementById('map'), {
                    center: defaultLatLong,
                    zoom: distance > 200 ? 12 : 16,
                    mapTypeId: 'roadmap'
                });

                map.setOptions({
                    scrollwheel: true,
                    zoomControl: true,
                    mapTypeControl: true,
                    scaleControl: true,
                    streetViewControl: true,
                    rotateControl: true,
                    fullscreenControl: true,
                });

                var input = document.getElementById('pac-input');
                
                var autocomplete = new google.maps.places.Autocomplete(input);
                
                autocomplete.bindTo('bounds', map);
                map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
                
                marker = new google.maps.Marker({
                    map: map,
                    position: defaultLatLong,
                    draggable: true,
                    clickable: true,
                    animation: google.maps.Animation.DROP
                });

                circleMap();

                google.maps.event.addListener(marker, 'dragend', function(marker) {
                    var latLng = marker.latLng;
                    currentLatitude  = latLng.lat();
                    currentLongitude = latLng.lng();

                    var latlng = {
                        lat: currentLatitude,
                        lng: currentLongitude
                    };

                    latitude = currentLatitude;
                    longitude = currentLongitude;

                    var geocoder = new google.maps.Geocoder;

                    geocoder.geocode({
                        'location': latlng
                    }, function(results, status) {
                        if (status === 'OK') {
                            if (results[0]) {
                                input.value = results[0].formatted_address;
                                circleMap();
                            } else {
                                window.alert('No results found');
                            }
                        } else {
                            window.alert('Geocoder failed due to: ' + status);
                        }
                    });
                });
                
                autocomplete.addListener('place_changed', function() {
                    var place = autocomplete.getPlace();
                    if (!place.geometry) {
                        return;
                    }
                    if (place.geometry.viewport) {
                        map.fitBounds(place.geometry.viewport);
                    } else {
                        map.setCenter(place.geometry.location);
                    }
                
                    marker.setPosition(place.geometry.location);
                    
                    currentLatitude = place.geometry.location.lat();
                    currentLongitude = place.geometry.location.lng();
                    latitude = currentLatitude;
                    longitude = currentLongitude;  

                    $('#latitude').val(latitude);
                    $('#longitude').val(longitude);

                    circleMap();
                });
            }

            locationPicker = (val,ur) => {
                $.get(ur +'?q='+val, function (data) {
                    if (data == 'fail') {
                        setTimeout(function () {
                            toastr.error('Something went wrong!', 'Error!', {
                                timeOut: 2000
                            });
                        }, 500);
                    } else {
                        $(data).appendTo('body').modal({
                            backdrop: 'static',
                            keyboard: false
                        });
                    }
                });
            }

            mapInit();

            let locationIndex = 0;
            $("#saveButton").on('click', function() {
                distance  = $('#distance').val();

                let address  = $('.location').val();

                if (distance == '' || distance == null || distance == undefined || distance == 0) {
                    $('#distance').next('.invalid-feedback').remove();
                    $('#distance').addClass('is-invalid');
                    return false;
                }


                if (address == '') {
                    $('.location').addClass('is-invalid');
                    return false
                }

                // Unique ID for tracking
                const entryId = `location-entry-${locationIndex}`;

                $('#modal-hidden-fields').append(`
                   <div id="${entryId}">
                        <input type="hidden" name="locations[${locationIndex}][distance]" value="${distance}">
                        <input type="hidden" name="locations[${locationIndex}][latitude]" value="${latitude}">
                        <input type="hidden" name="locations[${locationIndex}][longitude]" value="${longitude}">
                        <input type="hidden" name="locations[${locationIndex}][address]" value="${address}">
                    </div>
                `);

                // Append display list
                $('.location_list .tbody').append(`
                    <tr id="item-${entryId}">
                        <td>${++locationIndex}</td>
                        <td>${address}</td>
                        <td>
                            <button type="button" class="btn btn-sm btn-danger" onclick="removeLocation('${entryId}')">
                                <i class="fa fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                `);

                locationIndex++;

                // Optional: reset modal input fields
                $('#distance').val('');
                $('.location').val('');

                // Close modal
                const modal = bootstrap.Modal.getInstance(document.getElementById('exampleModalToggle'));
                modal.hide();
            });

            $("#cancelButton").on('click', function() {
                $('#exampleModalToggle').modal('hide');
            });

            $('#distance').on('keyup', function () {
                if ($(this).val() != '') {
                    $(this).removeClass('is-invalid');
                    $(this).next('.invalid-feedback').remove();
                }

                distance =  $('#distance').val();

                circleMap();
            });

            $('.location').on('keyup', function () {
                if ($(this).val() != '') {
                    $(this).removeClass('is-invalid');
                }
            });
        });

        // Remove function
        function removeLocation(entryId) {
            // Remove display row
            $(`#item-${entryId}`).remove();

            // Remove hidden inputs block
            $(`#${entryId}`).remove();
        }

        function deleteLocation(locationId) {
            var locationDeleteUrl = @json(\Route::has('location.delete_data') ? route('location.delete_data') : '');

            if (!locationDeleteUrl) {
                console.error('Module not active or route not available.');
                return;
            }

            Swal.fire({
                title: 'Are you sure?',
                text: "This location will be permanently deleted.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: locationDeleteUrl,
                        type: 'POST',
                        data: {
                            _token: $('meta[name="csrf-token"]').attr('content'),
                            'ids': [locationId]
                        },
                        success: function(response) {
                            // Remove row from DOM
                            $(`button[onclick="deleteLocation('${locationId}')"]`).closest('tr').remove();

                            Swal.fire(
                                'Deleted!',
                                'Location has been deleted.',
                                'success'
                            );
                        },
                        error: function(xhr) {
                            Swal.fire(
                                'Failed!',
                                'Something went wrong.',
                                'error'
                            );
                        }
                    });
                }
            });
        }
    </script>
@endsection
