@extends('web.layouts.container')

@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-4">
                                <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="col-md-4">
                                <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 class="row justify-content-between mt-5 pt-3">
                        <div class="col show_in_outside_office">
                            <div class="form-group">
                                <select name="city_id" class="form-control">
                                    <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-control">
                                    <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 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>
                            </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" placeholder="{{__('documentations.address_placeholder')}}" class="form-control">
                        </div>
                    </div>
                    <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>
                        {{-- Date block--}}
                        <div class="date-inner documentation_container">
                            @if(count($documentations))
                                @foreach($documentations as $documentationDate => $documentation)
                                    <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>
                                @endforeach
                            @else
                                <div class="alert alert-secondary text-danger text-center">{{__('documentations.no_data')}}</div>
                            @endif
                        </div>
                    </div>
                    <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>
                        {{-- Time block--}}
                        <div class="date-inner documentation_time_container"></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>
                    <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>

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

@section('inner_js')

{{--    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>--}}
{{--    <script defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDpVcBEVHKN5-iO0-z5MoEeLLpfV18JZjg&callback=initMap"></script>--}}
    <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) {
                window.location.href = response.url;
            }
        });

        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="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>`);
                }
            } 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="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>`);
                }
            } 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>

        function initMap() {
            /** Map one block */
            let map = new google.maps.Map(document.getElementById("map"), {
                zoom: 7,
                center: { lat: parseFloat(latitude) , lng: parseFloat(longitude) }
            });

            let marker = new google.maps.Marker({
                map: map,
                draggable: true,
                animation: google.maps.Animation.DROP,
                position: { lat: parseFloat(latitude) , lng: parseFloat(longitude) }
            });


            marker.addListener("dragend", function (map) {
                let lat = map.latLng.lat(), lng = map.latLng.lng();
                localStorage.setItem('lat', lat);
                localStorage.setItem('lng', lng);
                $('input[name="lat"]').val(lat);
                $('input[name="lng"]').val(lng);
                var geocoder = new google.maps.Geocoder();
                var infowindow = new google.maps.InfoWindow();

                google.maps.event.addListener(marker, 'dragend', function() {
                    infowindow.close();
                });

                var latlng = { lat: parseFloat(lat), lng: parseFloat(lng) };
                geocoder.geocode({ location: latlng }, function(results, status) {
                    if (status === "OK") {
                        if (results[0]) {
                            infowindow.setContent(results[0].formatted_address);
                            infowindow.open(map, marker);
                            $('input[name="address"]').val(results[0].formatted_address);
                        } else {
                            window.alert("No results found");
                        }
                    } else {
                        window.alert("Geocoder failed due to: " + status);
                    }
                });
                if (marker.getAnimation() !== null) {
                    marker.setAnimation(null);
                } else {
                    marker.setAnimation(google.maps.Animation.BOUNCE);
                }
            });
        }
    </script>
@endsection
