@extends('admin.layouts.container')
@section('css')
    <link rel="stylesheet" href="{{asset('assets/admin/css/lib/toastr.css')}}">

    <style>
        .highlight{
            background: #FC0 !important;
        }
    </style>
@endsection
@section('content')
    <div class="side-title">
        <h3>{{$head ?? '' }}</h3>
    </div>

    <div class="border-item">
        <form class="form-row add_hall_from" method="post" action="{{ $action }}" enctype="multipart/form-data" autocomplete="off">
            @if($hotel ?? ''  && $hotel->id)
                @method('PUT')
            @endif
            @csrf
            <div class="form-group col-lg-12">
                <label for="location">{{ meta('address', $local) ?? __('hotels.address') }}</label>
                <div class="d-flex justify-content-between align-items-center">
                    <input type="text" name="address" id="location" class="form-control" placeholder="{{__('hotels.address') . __('hotels.choose_address_via_map')}}" value='{{ $hotel->address ?? "" }}'>
                    <button style="font-size: 12px" type="button" class="butn small modal-btn mr-2" data-toggle="modal" data-target="#exampleModalCenter">
                        <span>{{__('hotels.location')}}</span>
                    </button>
                    <input type="hidden" name="lat" value='{{ $hotel->lat ?? "" }}'>
                    <input type="hidden" name="lng" value='{{ $hotel->lng ?? "" }}'>
                </div>
            </div>
            <div class="form-group col-lg-4">
                <label>{{ meta('city_id', $local) ?? __('hotels.city_id') }} </label>
                <select name="city_id" class="form-control">
                    <option value="">{{ meta('city_id', $local) ?? __('hotels.city_id') }}</option>
                    @if(count($cities))
                        @foreach($cities as $city)
                            <option {{($hotel->city_id ?? null) == $city->id ? 'selected': ''}} value="{{$city->id}}">{{$city->name}}</option>
                        @endforeach
                    @endif
                </select>
            </div>
            <div class="form-group col-lg-4">
                <label>{{ meta('email', $local) ?? __('hotels.email') }} </label>
                <input type="email" class="form-control" name="email" placeholder="{{ meta('email', $local) ?? __('hotels.email') }}" value='{{ $hotel->email ?? "" }}'/>
            </div>
            <div class="form-group col-lg-4">
            <label>{{ meta('status', $local) ?? __('hotels.status') }} </label>
            <select name="hall_status" class="form-control">
{{--                <option value="">{{ meta('status', $local) ?? __('hotels.status') }}</option>--}}
                <option {{($hotel->status ?? null) == 1 ? 'selected': ''}} value="1">{{__('hotels.active')}}</option>
                <option {{($hotel->status?? null) == 0 ? 'selected': ''}} value="0">{{__('hotels.non_active')}}</option>
            </select>
        </div>

            <div class="card p-3 mb-3 col-lg-12">
                <label>{{ meta('added_service', $local) ??  __('hotels.added_service') }} </label>
                <div class="row card-body">
                    @if(count($added_service))
                        @foreach($added_service as $value => $service)
                            <div class="col-md-4">
                                <div class="custom-control custom-checkbox mb-2">
                                    <input data-price=".added_service_price_{{$value}}" type="checkbox" {{ in_array($value, $hotel['added_service'] ?? []) ? 'checked' : '' }} value="{{ $value }}" class="custom-control-input" id="{{ $value }}" name="added_service[]">
                                    <label class="custom-control-label" for="{{ $value }}"> {{$service}}</label>
                                </div>
                                <input readonly type="number" min="1" name="added_service_price[{{$value}}]" class="form-control added_service_price_{{$value}}" placeholder="{{ meta('added_service_price', $local) ??  __('hotels.added_service_price') }}" value="{{($hotel ?? null) ? $hotel['added_service_price'][$loop->index] : ''}}">
                            </div>
                        @endforeach
                    @endif
                </div>
            </div>
            <div class="card p-3 mb-3 col-lg-12">
                <label>{{ meta('room_type', $local) ??  __('hotels.room_type') }} </label>
                <div class="row card-body">
                    @if(count($room_type))
                        @foreach($room_type as $value => $type)
                            <div class="col-md-3">
                                <div class="custom-control custom-checkbox mb-2">
                                    <input data-price=".room_type_price_{{$value}}" type="checkbox" {{ in_array($value, $hotel['room_type'] ?? []) ? 'checked' : '' }} value="{{ $value }}" class="custom-control-input" id="room_type_{{ $value }}" name="room_type[]">
                                    <label class="custom-control-label" for="room_type_{{ $value }}"> {{$type}}</label>
                                </div>
                                <input readonly type="number" min="1" name="room_type_price[{{$value}}]" class="form-control room_type_price_{{$value}}" placeholder="{{ meta('room_type_price', $local) ??  __('hotels.room_type_price') }}" value="{{($hotel ?? null) ? $hotel['room_type_price'][$loop->index] : ''}}">
                            </div>
                        @endforeach
                    @endif
                </div>
            </div>

            @foreach(languages() as $language)
            <div class="form-group col-lg-6">
                <label>{{ meta('name', $language->local) ?? __('hotels.name') }} {{ count($languages) > 1 ? "({$language->name})" : '' }} </label>
                <input type="text" class="form-control" name="name_{{ $language->local }}" placeholder="{{ meta('name', $language->local) ?? __('hotels.name') }}" value='{{ $hotel[$language->local]->name ?? "" }}'/>
            </div>
            @endforeach
            <div class="border-item photos col-md-12 other_image_container">
                <div class="row">
                    @if ($hotel ?? false)
                        @foreach ($hotel['images'] as $photo)
                            <div class="col-md-4">
                                <div class="items">
                                    <div class="img">
                                        <a href="{{ asset($photo ?? '')}}" data-fancybox="gallery"><img src="{{ asset($photo ?? '')}}" alt=""></a>
                                    </div>
                                    <input type="hidden" name="images[]" value="{{ $photo ?? "" }}">
                                    <a href="#" class="close"><i class="fas fa-times"></i></a>
                                </div>
                            </div>
                        @endforeach
                    @endif
                </div>
                <div class="text-center">
                    <input id="other_image_thumbnail" class="other_image_thumbnail" type="hidden"/>
                    <div class="clearfix"></div>
                    <span id="add">
                    <a id="lfm" data-width="" data-cache="article_gallery" data-input=".other_image_thumbnail" data-preview="" data-show="" data-hide="" class="lfm add">
                        Add New Item
                    </a>
                </span>
                </div>
            </div>

            <div class="text-center mt-5 col-12">
                <button class="butn add_hall_button"><span>{{ __('dashboard.save') }}</span></button>
            </div>
        </form>
    </div>


    <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLongTitle">{{__('hotels.location')}}</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div style="border:0; height: 400px; width: 100%" class="map" id="map"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="butn color small save_location"><span>{{__('hotels.save_location')}}</span></button>
                </div>
            </div>
        </div>
    </div>


@endsection

@section('inner_js')
    <!-- Editor JS files -->
    <script src="{{ asset('/assets/admin/js/lib/tinymce.min.js') }}"></script>
    {{--    <script src="//cdn.tinymce.com/4/tinymce.min.js"></script>--}}
    <script>
        var route_prefix = "{{ url(config('lfm.prefix')) }}";
        var url = "{{url('/')}}/",
            currentLanguage = "{{$local}}",
            inputName = '';
    </script>
    <script src="{{ asset('assets/admin/js/editor.js') }}"></script>
    <script src="{{ asset('assets/admin/js/lfm.js') }}"></script>
    <script src="{{ asset('assets/admin/js/articles.js') }}"></script>
    <script src="{{ asset('assets/admin/js/lib/toastr.min.js') }}"></script>



    <script>

        let getCityAndSectorRoute = "{{route('hotels.getCityAndSector')}}";

        localStorage.setItem('articleGallery', null);
        localStorage.setItem('oldArticleStorage', null);

        $('.add_hall_button').click(async function (e) {
            e.preventDefault();

            let form = $('.add_hall_from'),
                data = new FormData(form[0]),
                url = form.attr('action'),
                method = form.attr('method');

            $('.discount_dates_input').each(function () {
                if ($(this).prop('checked') === false){
                    data.append('discount_dates[]', 0);
                    data.append('discount_percentage[]', 'empty');
                } else {
                    data.append('discount_dates[]', 1);
                    let inputSibling = $(this).siblings('.discount_percentage');
                    data.append('discount_percentage[]', inputSibling.val());

                }});


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

            if (response.url){
                window.location.href = response.url;
            }

            if (response.errors){
                toasterError(response.errors);
            }


        });

        $(document).on('click', '.active_hall' , async function (e) {
            e.preventDefault();
            let url = $(this).data('href'),
                method = 'get';

            const response=await ajax({
                url,
                dataType: 'json',
                method,
            });
            if (response.message) {
                $(this).children('i').toggleClass('fa-check text-success fa-times text-danger')

            }
        });

        let checkBoxInputs = $('input[type="checkbox"]');
        checkBoxInputs.click(function () {
            if($(this).prop('checked') === true){
                $($(this).data('price')).removeAttr('readonly')
            } else {
                $($(this).data('price')).val('');
                $($(this).data('price')).attr('readonly', 'readonly');
            }
        });

        checkBoxInputs.each(function () {
            if($(this).prop('checked') === true){
                $($(this).data('price')).removeAttr('readonly')
            } else {
                $($(this).data('price')).val('');
                $($(this).data('price')).attr('readonly', 'readonly');
            }
        });

    </script>

    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA5HuBEjkPPxQH4c7Nhfx2-u5XXCtSIzUk&callback=initMap&libraries=&v=weekly" defer></script>
{{--    <script src="{{ asset('assets/web/js/lib/google_maps.js') }}"></script>--}}

    <script>
        // The following example creates a marker in Stockholm, Sweden using a DROP
        // animation. Clicking on the marker will toggle the animation between a BOUNCE
        // animation and no animation.

        let latitude = null,
            longitude = null;
        if (navigator.geolocation) {
            navigator.geolocation.watchPosition(function (position) {
                // let lat = $('input.latitude'),
                //     lng = $('input.longitude');
                // latitude = lat.val(parseFloat(position.coords.latitude));
                // longitude = lng.val(parseFloat(position.coords.longitude));
                latitude = parseFloat(position.coords.latitude);
                longitude = parseFloat(position.coords.longitude);
                localStorage.setItem('lat', latitude);
                localStorage.setItem('lng', longitude);
            });
        } else {
            alert('Geolocation is not supported by this browser')
        }

        var marker;
        var save_location = $('.save_location');
        function initMap() {
            var map = new google.maps.Map(document.getElementById("map"), {
                zoom: 7,
                center: { lat: parseFloat(latitude) , lng: parseFloat(longitude) }
            });

            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);
                $('#latitude').val(lat);
                $('#longitude').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);
                            document.getElementById('location').value = 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);
                }
            });
        }

        save_location.click(function (map) {
            let lat = localStorage.getItem('lat'),
                lng = localStorage.getItem('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();

            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);
                        document.getElementById('location').value = 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);
            }

            $('.modal').modal('hide')
        });
    </script>

@endsection



