@extends('web.layouts.container')
@section('css')
        <link href="https://api.mapbox.com/mapbox-gl-js/v2.8.2/mapbox-gl.css" rel="stylesheet">
{{--    <link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v4.1.0/mapbox-gl-directions.css" type="text/css">--}}
{{--    <link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/mapbox-gl-geocoder.css" type="text/css">--}}


{{--    <link href="{{asset('assets/web/css/lib/mapbox-gl.css')}}" rel="stylesheet">--}}
{{--    <link href="{{asset('assets/web/css/lib/mapbox-gl-directions.css')}}" rel="stylesheet">--}}
{{--    <link href="{{asset('assets/web/css/lib/mapbox-gl-geocoder.css')}}" rel="stylesheet">--}}

    <style>
        #lang_buttons {
            width: 90%;
            margin: 0 auto;
        }
        .button {
            display: inline-block;
            position: relative;
            cursor: pointer;
            width: 20%;
            padding: 8px;
            border-radius: 3px;
            margin-top: 10px;
            font-size: 12px;
            text-align: center;
            color: #fff;
            background: #ee8a65;
            font-family: sans-serif;
            font-weight: bold;
        }
    </style>
@endsection
@section('content')
    <section class="inner_header">
        <img src="{{asset('assets/web/images/icons/inner.svg')}}" alt="" class="inner_shap">
        <div class="container">
            <ul class="links">
                <li>
                    <a href="{{LaravelLocalization::getLocalizedURL($lang, route('home'), [], true)}}">{{__('main.home')}}</a>
                </li>
                <li>
                    <a href="#"> {{__('documentations.documentation_request')}} </a>
                </li>
            </ul>
            <h4>{{__('documentations.documentation_request')}}</h4>
        </div>
    </section>

    <section class="consultation-pg section_padding">
        <div class="container">
            <div class="form-container">
                <form action="{{route('documentation.documentationRequest')}}" method="post" class="documentation_request_form">
                    <div class="doc-wrapper">
                        <div class="row justify-content-center">
                            <div class="col-md-8">
                                <div class="documentation_slider">
                                    <div class="swiper-container">
                                        <div class="swiper-wrapper">
                                            <div class="swiper-slide p-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="type" id="inside_office" value="inside_office">
                                                    <label class="form-check-label color1" for="inside_office">
                                                        <div class="icon-outer">
                                                            <img src="{{asset('assets/web/images/icons/workplace.svg')}}" alt="" class="icon"/>
                                                        </div>
                                                        <h5 class="title mb-0">{{__('documentationRequests.inside_office')}}</h5>
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="swiper-slide p-2">
                                                <div class="form-check">
                                                    <input checked class="form-check-input" type="radio" name="type" id="outside_office" value="outside_office">
                                                    <label class="form-check-label color2" for="outside_office">
                                                        <div class="icon-outer">
                                                            <img src="{{asset('assets/web/images/icons/workplace.svg')}}" alt="" class="icon"/>
                                                        </div>
                                                        <h5 class="title mb-0">{{__('documentationRequests.outside_office')}}</h5>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row justify-content-between mt-5 pt-3 form_cont_scroll">
                        <div class="col show_in_outside_office">
                            <div class="form-group">
                                <select name="city_id" class="form-select">
                                    <option selected value="">{{__('documentationRequests.city')}}</option>
                                    @if(count($cities))
                                        @foreach($cities as $city)
                                            <option value="{{$city->id}}">{{$city->name}}</option>
                                        @endforeach
                                    @endif
                                </select>
                            </div>
                        </div>
                        <div class="col">
                            <div class="form-group">
                                <select name="documentation_type_id" class="form-select">
                                    <option selected value="">{{__('documentationRequests.documentation_type_id')}}</option>
                                    @if(count($documentationTypes))
                                        @foreach($documentationTypes as $documentationType)
                                            <option value="{{$documentationType->id}}">{{$documentationType->name}}</option>
                                        @endforeach
                                    @endif
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row mt-5 pt-3">
                        <div class="col">
                            <h5 class="title text-dark mb-4"><b>{{__('documentationRequests.notes')}}</b></h5>
                            <textarea name="notes" class="form-control" rows="12"></textarea>
                        </div>
                        <div class="col-lg-6 show_in_outside_office">
                            <h5 class="title text-dark mb-4"><b>{{__('documentationRequests.detect_location')}}</b></h5>
                            <div class="map-box">
                                <div style="border:0; height: 400px; width: 100%" class="map" id="map"></div>
                                <ul id="lang_buttons">
                                    <li id="button-ar" class="button">{{__('main.arabic')}}</li>
{{--                                    <li id="button-en" class="button">{{__('main.english')}}</li>--}}
{{--                                    <li id="button-ru" class="button">Russian</li>--}}
{{--                                    <li id="button-de" class="button">German</li>--}}
{{--                                    <li id="button-es" class="button">Spanish</li>--}}
                                </ul>
                                <pre id="coordinates" class="coordinates"></pre>
                            </div>
                        </div>
                        <div class="col-md-12 mt-5 show_in_outside_office">
                            <input type="hidden" name="lat">
                            <input type="hidden" name="lng">
                            <input type="text" name="address" autocomplete="address-line1" placeholder="{{__('documentations.address_placeholder')}}" class="form-control">
                        </div>
                    </div>
                    {{-- Date block--}}
                    <div class="date-outer mt-5">
                        <h5 class="title text-dark mb-4"><b><i class="bi bi-calendar3 me-2"></i>{{__('documentationRequests.documentation_date')}}</b></h5>
                        <div class="swiper-container date-inner d-block">
                            <div class="swiper-wrapper documentation_container">
                                @if(count($documentations))
                                    @foreach($documentations as $documentationDate => $documentation)
                                        <div class="swiper-slide">
                                            <div class="form-check">
                                                <input data-documentation-date="{{$documentationDate}}" class="form-check-input documentation_date" type="radio" name="documentation_date" id="documentation_date_{{$loop->iteration}}" value="{{$documentationDate}}">
                                                <label class="form-check-label" for="documentation_date_{{$loop->iteration}}">
                                                    {{date('d/m/Y', strtotime($documentationDate))}}
                                                </label>
                                            </div>
                                        </div>
                                    @endforeach
                                @else
                                    <div class="alert alert-secondary text-danger text-center">{{__('documentations.no_data')}}</div>
                                @endif
                            </div>
                        </div>
                    </div>

                    {{-- Time block--}}
                    <div class="date-outer mt-5">
                        <h5 class="title text-dark mb-4"><b><i class="bi bi-clock me-2"></i>{{__('documentationRequests.documentation_time')}}</b></h5>
                        <div class="swiper-container date-inner d-block">
                            <div class="swiper-wrapper documentation_time_container"></div>
                        </div>
                    </div>
                    <p class="note mt-5">
                        <i class="bi bi-exclamation-circle"></i>
                        {{__('documentationRequests.documentation_hint')}}
                    </p>
                    <div class="payment_methods mt-5">
                        <h5 class="title text-dark mb-4"><b>{{__('documentationRequests.pay_way')}}</b></h5>
                        <div class="row">
                            <div class="col-md-6 mb-2">
                                <div class="form-check color3">
                                    <input class="form-check-input" type="radio" name="pay_way" id="visa_master" value="2">
                                    <label class="form-check-label" for="visa_master">
                                        {{__('documentationRequests.visa_master')}}
                                        <img src="{{asset('assets/web/images/icons/payment-3.svg')}}" alt="" class="icon">
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-6 mb-2">
                                <div class="form-check color1">
                                    <input class="form-check-input" type="radio" name="pay_way" id="mada" value="6">
                                    <label class="form-check-label" for="mada">
                                        {{__('documentationRequests.mada')}}
                                        <img src="{{asset('assets/web/images/icons/payment-1.svg')}}" alt="" class="icon">
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check color2">
                                    <input class="form-check-input" type="radio" name="pay_way" id="stc_pay" value="14">
                                    <label class="form-check-label" for="stc_pay">
                                        {{__('documentationRequests.stc_pay')}}
                                        <img src="{{asset('assets/web/images/icons/payment-2.svg')}}" alt="" class="icon">
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check color2">
                                    <input class="form-check-input" type="radio" name="pay_way" id="apple_pay" value="11">
                                    <label class="form-check-label" for="apple_pay">
                                        {{__('documentationRequests.apple_pay')}}
                                        <img src="{{asset('assets/web/images/icons/payment-2.svg')}}" alt="" class="icon">
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row mt-5 mb-5">
                        <div class="col-md-6">
                            <h5 class="title text-dark mb-4"><b> {{__('documentationRequests.coupon_id')}} </b></h5>
                            <div class="form-group copun-group">
                                <input name="coupon_code" class="form-control" placeholder="{{__('documentationRequests.coupon_id')}}"/>
                                <a href="#" class="butn sub_butn check_coupon"><span> {{__('documentationRequests.apply_coupon')}} </span></a>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h5 class="title text-dark mb-4 discount_title"><b> {{__('documentationRequests.discount_percentage')}} </b></h5>
                            <div class="form-group">
                                <input class="form-control discount_value" placeholder="%" disabled/>
                            </div>
                        </div>
                    </div>
                    <div class="total_box text-center col-md-5 m-auto">
                        <h5 class="title main_color"><b>{{__('documentationRequests.total')}}</b></h5>
                        <h1 class="price text-dark mt-3"><b class="total">0</b> <small>{{__('main.sar')}}</small></h1>
                    </div>
                    <p class="note mt-3 col-md-4 m-auto">
                        <i class="bi bi-exclamation-circle"></i>
                        {{__('documentationRequests.price_inclusive_added_value')}}
                    </p>

                    @if(auth()->check() && auth()->user()->role == 'user')
                        <button class="submit-butn butn mt-5 m-auto d-block documentation_request_button" type="button" data-bs-target="#confirmConsult"><span><b>{{__('documentationRequests.complete_request')}}</b></span></button>
                    @else
                        <a href="{{route('user.login')}}" class="submit-butn butn mt-5 m-auto d-block login_url"><span><b>{{__('documentationRequests.complete_request')}}</b></span></a>
                    @endif

                </form>
            </div>
        </div>
    </section>
@endsection

@section('inner_js')

    <script>

        let getDocumentationDateTimeRoute = "{{route('documentation.getDocumentationDateAndTime')}}",
            checkCouponRoute = "{{route('checkCoupon')}}",
            documentationDateAlert = "{{__('documentations.select_documentation_date')}}",
            documentationTypeAlert = "{{__('documentations.select_documentation_type')}}",
            discountTitlePercentage = "{{__('coupons.discount_percentage')}}",
            discountTitleValue = "{{__('coupons.discount_amount')}}",
            documentationFees = "{{$documentationFees}}",
            noData = "{{__('documentations.no_data')}}";
        //     latitude = localStorage.getItem('lat'),
        //     longitude = localStorage.getItem('lng');
        //
        // $('input[name="lat"]').val(latitude);
        // $('input[name="lng"]').val(longitude);

        $('.documentation_request_button').click(async function (e) {
            e.preventDefault();
            // $(this).attr('disabled', true);
            let form = $('.documentation_request_form'),
                data = new FormData(form[0]),
                url = form.attr('action'),
                method = form.attr('method');

            data.append('documentation_id', $('input[name="documentation_time"]:checked').data('documentation-id'));
            data.append('coupon_code', $('input[name="coupon_code"]').val());
            data.append('service_type', 'documentation');

            const response=await ajax({
                url,
                data,
                dataType: 'json',
                method,
                contentType: false,
                processData: false,
            });

            if (response.errors) {
                $(this).attr('disabled', false);
                toasterError(response.errors);
            }
            if (response.url) {
                localStorage.setItem('type', '');
                localStorage.setItem('city_id', '');
                localStorage.setItem('documentation_type_id', '');
                localStorage.setItem('notes', '');
                localStorage.setItem('address', '');
                localStorage.setItem('pay_way', '');
                window.location.href = response.url;
            }
        });

        $(document).ready(function () {
            let type = localStorage.getItem('type'),
                city_id = localStorage.getItem('city_id'),
                documentation_type_id = localStorage.getItem('documentation_type_id'),
                notes = localStorage.getItem('notes'),
                address = localStorage.getItem('address'),
                pay_way = localStorage.getItem('pay_way');

            $('input[name="type"]').each(function () {
                if($(this).val() === type){
                    $(this).prop('checked', true);
                    $(this).trigger('click');
                }
            });

            $('select[name="city_id"]').val(city_id);
            $('select[name="documentation_type_id"]').val(documentation_type_id);
            $('textarea[name="notes"]').val(notes);
            $('input[name="address"]').val(address);
            $('input[name="pay_way"]').each(function () {
                if($(this).val() === pay_way){
                    $(this).prop('checked', true);
                }
            });
        });


        $('.login_url').hover(function () {
            localStorage.setItem('type',  $('input[name="type"]:checked').val());
            localStorage.setItem('city_id',  $('select[name="city_id"]').val());
            localStorage.setItem('documentation_type_id',  $('select[name="documentation_type_id"]').val());
            localStorage.setItem('notes',  $('textarea[name="notes"]').val());
            localStorage.setItem('address', $('input[name="address"]').val());
            localStorage.setItem('pay_way', $('input[name="pay_way"]:checked').val());
        });

        let oldPrice = 0;
        $('input[name="type"]').click(async function () {
            let data = {type: $(this).val()},
                url = getDocumentationDateTimeRoute,
                method = 'get';

            $('.documentation_time_container').html('');

            if($(this).val() === 'inside_office'){
                $('.total').html(documentationFees);
                oldPrice = documentationFees;
                $('select[name="city_id"]').val('');

                // To calc coupon if not empty
                if($('input[name="coupon_code"]').val() !== ''){
                    $('.check_coupon').trigger('click');
                }

                $('.show_in_outside_office').addClass('d-none');
                $('input[name="address"], input[name="lat"], input[name="lng"]').val('')
            }
            if($(this).val() === 'outside_office'){
                // $('.total').html(0);
                // $('.discount_value').html(0);
                if($('input[name="coupon_code"]').val() !== '' && $('select[name="city_id"]').val() !== ''){
                    $('.check_coupon').trigger('click');
                }
                $('.show_in_outside_office').removeClass('d-none');
                $('input[name="lat"]').val(latitude);
                $('input[name="lng"]').val(longitude);

            }

            const response=await ajax({
                url,
                data,
                dataType: 'html',
                method,
                contentType: false,
                processData: false,
            });

            if (response.documentations_dates) {
                $('.documentation_container').html('');
                for(let doc of response.documentations_dates){
                    $('.documentation_container').append(`
                    <div class="swiper-slide">
                        <div class="form-check">
                            <input data-documentation-date="${doc.date}" class="form-check-input documentation_date" type="radio" name="documentation_date" id="documentation_date_${doc.id}" value="${doc.date}">
                            <label class="form-check-label" for="documentation_date_${doc.id}">${doc.label}</label>
                        </div>
                    </div>`);
                }
            } else {
                $('.documentation_container').html(`<div class="alert alert-secondary text-danger text-center">${noData}</div>`)
            }
        });

        $(document).on('click', 'input[name="documentation_date"]', async function () {
            let data = {
                documentation_type: $('input[name="type"]:checked').val(),
                    documentation_date: $(this).data('documentation-date')
                },
                url = getDocumentationDateTimeRoute,
                method = 'get';

            const response=await ajax({
                url,
                data,
                dataType: 'json',
                method,
                contentType: false,
                processData: false,
            });

            if (response.errors) {
                $(this).attr('disabled', false);
                toasterError(response.errors);
            }

            if(response.documentations_times){
                $('.documentation_time_container').html('');
                for(let documentations of response.documentations_times){
                    $('.documentation_time_container').append(`
                    <div class="swiper-slide">
                        <div class="form-check">
                            <input data-documentation-id="${documentations.id}" class="form-check-input" type="radio" name="documentation_time" id="documentation_time_${documentations.id}" value="${documentations.time}">
                            <label class="form-check-label" for="documentation_time_${documentations.id}">${documentations.label}</label>
                        </div>
                    </div>`);
                }
            } else {
                $('.documentation_time_container').html(`<div class="alert alert-secondary text-danger text-center">${noData}</div>`)
            }

        });

        $('select[name="city_id"]').change(async function () {
           if($(this).val() === ''){
               $('.discount_value').val(0);
               $('.total').html(0);
               return false;
           }

            let data = {city_id: $(this).val()},
                url = getDocumentationDateTimeRoute,
                method = 'get';

            const response=await ajax({
                url,
                data,
                dataType: 'json',
                method,
                contentType: false,
                processData: false,
            });

            if (response.errors) {
                $(this).attr('disabled', false);
                toasterError(response.errors);
            }

            if(response.price){
                oldPrice = response.price;
                $('.total').html(response.price);
                // To calc coupon if not empty
                if($('input[name="coupon_code"]').val() !== ''){
                    $('.check_coupon').trigger('click');
                }
            }
        });


        $('input[name="coupon_code"]').focus(function () {
            $(this).css({
                borderColor: '#E1E1E1'
            })
        }).blur(function () {
            if($(this).val() === ''){
                $('.discount_value').val(0);
                $('.total').html(oldPrice);
            }
        });

        $('.check_coupon').click(async function (e) {
            e.preventDefault();
            let couponCode = $('input[name="coupon_code"]');
            if(couponCode.val() === ''){
                couponCode.css({
                    borderColor: 'red'
                });
                return false;
            }
            let data = {
                    type: $('input[name="type"]:checked').val(),
                    coupon_code: couponCode.val(),
                    documentation_id: $('input[name="documentation_time"]:checked').data('documentation-id'),
                    city_id: $('select[name="city_id"]').val(),
                    service_type : 'documentation'
                },
                url = checkCouponRoute,
                method = 'get';

            if(data.type === undefined){
                alert(documentationTypeAlert);
                return false;
            }

            $(this).attr('disabled', true);
            const response=await ajax({
                url,
                data,
                dataType: 'json',
                method,
                contentType: false,
                processData: false,
            });
            if (response.errors) {
                $(this).attr('disabled', false);
                toasterError(response.errors);
            }
            if (!response.errors) {
                $(this).attr('disabled', true);
                let discountTitle = response.discount_type === 'percentage' ? discountTitlePercentage : discountTitleValue;
                $('.discount_title').html(discountTitle);
                $('.discount_value').val(response.coupon_discount);
                $('.total').html(response.total);

            }
        })
    </script>

        <script src='https://api.mapbox.com/mapbox-gl-js/v2.8.2/mapbox-gl.js'></script>
    {{--    <script src="https://unpkg.com/@mapbox/mapbox-sdk/umd/mapbox-sdk.min.js"></script>--}}
    {{--    <script id="search-js" defer src="https://api.mapbox.com/search-js/v1.0.0-beta.9/web.js"></script>--}}
{{--    <script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v4.1.0/mapbox-gl-directions.js"></script>--}}
    <script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/mapbox-gl-geocoder.min.js"></script>

{{--    <script src='{{asset('assets/web/js/lib/mapbox-gl.js')}}'></script>--}}
{{--    <script src="{{asset('assets/web/js/lib/mapbox-sdk.min.js')}}"></script>--}}
{{--    <script id="search-js" defer src="{{asset('assets/web/js/lib/web.js')}}"></script>--}}
{{--    <script src="{{asset('assets/web/js/lib/mapbox-gl-directions.js')}}"></script>--}}
{{--    <script src="{{asset('assets/web/js/lib/mapbox-gl-geocoder.min.js')}}"></script>--}}


    <script>
        mapboxgl.accessToken = 'pk.eyJ1IjoibGVnYWxvZ2FpbCIsImEiOiJjbDM3NXF2Nm8xdXBoM2JwOWMyZ2Zua3o2In0.MVzxl1JEKwb-V9z5unrOwQ';
        const coordinates = document.getElementById('coordinates'),
            latitude = localStorage.getItem('lat'),
            longitude = localStorage.getItem('lng');

        const map = new mapboxgl.Map({
            container: 'map',
            style: 'mapbox://styles/mapbox/streets-v11',
            center: [30, 30],
            zoom: 4
        });

        mapboxgl.setRTLTextPlugin(
            'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js',
            null,
            true // Lazy load the plugin
        );


        document.getElementById('lang_buttons').addEventListener('click', (event) => {
            const language = event.target.id.substr('button-'.length);
            // Use setLayoutProperty to set the value of a layout property in a style layer.
            // The three arguments are the id of the layer, the name of the layout property,
            // and the new property value.
            map.setLayoutProperty('country-label', 'text-field', [
                'get',
                `name_${language}`
            ]);
        });

        // map.addControl(new mapboxgl.NavigationControl());



        // map.addControl(
        //     new MapboxDirections({
        //         accessToken: mapboxgl.accessToken
        //     }),
        //     'top-left'
        // );

        // const geocoder = new MapboxGeocoder({
        //     accessToken: mapboxgl.accessToken,
        //     language: 'de-DE', // Specify the language as German.
        //     mapboxgl: mapboxgl
        // });
        // map.addControl(geocoder);

        // Add geolocate control to the map.
        // map.addControl(
        //     new mapboxgl.GeolocateControl({
        //         positionOptions: {
        //             enableHighAccuracy: true
        //         },
        //         // When active the map will receive updates to the device's location as it changes.
        //         trackUserLocation: true,
        //         // Draw an arrow next to the location dot to indicate which direction the device is heading.
        //         showUserHeading: true
        //     })
        // );

        const marker = new mapboxgl.Marker({
            draggable: true
        }).setLngLat([latitude, longitude]).addTo(map);


        function onDragEnd() {
            const lngLat = marker.getLngLat();
            // coordinates.style.display = 'block';
            // coordinates.innerHTML = `Longitude: ${lngLat.lng}<br />Latitude: ${lngLat.lat}`;
            $('input[name="lat"]').val(lngLat.lat);
            $('input[name="lng"]').val(lngLat.lng);
        }

        marker.on('dragend', onDragEnd);

        // const script = document.getElementById('search-js');
        // mapboxsearch = document.querySelector('[autocomplete~="street-address"], [autocomplete~="address-line1"]');
        // script.onload = function() {
        //     mapboxsearch.autofill({
        //         accessToken: 'pk.eyJ1IjoibGVnYWxvZ2FpbCIsImEiOiJjbDM3NXF2Nm8xdXBoM2JwOWMyZ2Zua3o2In0.MVzxl1JEKwb-V9z5unrOwQ'
        //     });
        // };

    </script>

    <script>
        var swiper = new Swiper('.date-inner.swiper-container', {
            slidesPerView: 6,
            spaceBetween: 0,
            // centeredSlides: true,
            speed: 1000,
            pagination: false,
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            mousewheel: false,
            keyboard: true,
            autoplay: {
                delay: 10000,
            },
            loop: false,
            breakpoints: {
                0: {
                    slidesPerView: 2,
                },
                480: {
                    slidesPerView: 2,
                },
                787: {
                    slidesPerView: 3,
                },
                991: {
                    slidesPerView: 4,
                },
                1200: {
                    slidesPerView: 6,
                }
            }
        });
    </script>

    <script>
        $('.documentation_slider .form-check-label').click(function() {
            var contt = $(".form_cont_scroll").offset().top;
            $(this).siblings(".form-check-input").click()
            $('html, body').animate({
                    scrollTop: contt
                }, 100);
            return false;
        });
    </script>

@endsection
