@extends('frontend3')

@section('content')

    <!-- site content -->
    <div id="siteContent" class="site-content">
        <div class="container mt-12 mb-48">
            <div class="row">
                @include('frontend3.steps.sidebar_update')
                @php $step = 6;@endphp
                <form method="post" action="{{ url('tim-ban/cap-nhat', ['id' => $room->id]) }}"
                      enctype="multipart/form-data">

                    {!! csrf_field() !!}
                    <div class="col-xs-12 col-sm-8 mb-12">


                        @for($i = 1; $i <= $step; $i++)
                            @include('frontend3.steps.step_'.$i, compact('room'))
                        @endfor


                        <div class="text-right mt-24">
                            <button type="submit" class="btn ht-btn-primary px-24">Cập nhật
                            </button>
                        </div>
                    </div>
                </form>

            </div>
        </div>
    </div>
    <!-- END site content -->

@endsection

@push('scripts')
<script src="/assets/global/plugins/bootbox/bootbox.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/frontend3/assets/js/dropzone.js"></script>
<script type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCydLs7dhJPuozABFQjJO-uk1PITW18oo8&libraries=places&region=vi&language=vi&sensor=false"></script>
<script type="text/javascript" src="/frontend/scripts/infobox.min.js"></script>
<script type="text/javascript" src="/frontend/scripts/markerclusterer.js"></script>
<script type="text/javascript" src="/js/gmap.js"></script>

<script>

    function readURL2(input) {
        if (input.files) {

            for (i = 0; i < input.files.length; i++) {

                if (input.files[i]) {

                    var form_data = new FormData();
                    form_data.append('image', input.files[i]);
                    form_data.append('room_id', '{{ $room->id }}');

                    $.ajax({
                        url: '{{ url('upload-update-image-room-need-more') }}',
                        type: 'post',
                        dataType: 'json',
                        data: form_data,
                        processData: false,
                        contentType: false,
                        enctype: 'multipart/form-data',
                        cache: false,
                        success: function (response) {
                            $('<div class="single-uploaded-image">' +
                                '<div class="image-wrap ht-rectangle ratio-11">' +
                                '<div class="ht-inner">' +
                                '<img src="/files/' + response.result + '" alt=""' +
                                'class="image-main">' +
                                '</div>' +
                                '</div>' +
                                '<a href="#" class="image-delete-btn image-delete-btn-ajax" data-name="'+response.result+'"><i class="ion-android-close"></i></a>' +
                                '</div>').insertBefore('#form-upload');
                        },
                        error: function (error) {

                        }
                    });
                }
            }
        }
    }

    $(document).on('change', '#image-input2', function () {
        readURL2(this);
    });


    $(document).on('click', '.image-delete-btn-2', function (e) {
        e.preventDefault();
        $(this).parent().remove();
    });

    $(document).on('click', '.image-delete-btn-ajax', function (e) {
        e.preventDefault();
        var that = this;

        bootbox.confirm({
            message: "Bạn có chắc chắn muốn xóa",
            buttons: {
                confirm: {
                    label: 'Có',
                    className: 'btn-success'
                },
                cancel: {
                    label: 'Không',
                    className: 'btn-danger'
                }
            },


            callback: function (result) {
                if (result == true) {
                    var name = $(that).attr('data-name');

                    $.ajax({
                        url: '{{ url('delete-image-need-more') }}',
                        data: {
                            room_id: '{{ $room->id }}',
                            image: name
                        },
                        type:'post',
                        success: function (response) {
                            if(response.status == 1)
                            {
                                $('#uploaded-images').html(response.html);
                            }
                        }
                    });

                    {{--if (typeof(images) != 'undefined') {--}}
                        {{--if (images.length > 0) {--}}
                            {{--var index = images.indexOf(name);--}}
                            {{--images.splice(index, 1);--}}
                            {{--$.ajax({--}}
                                {{--url: '{{ url('update-images-need-more') }}',--}}
                                {{--data: {--}}
                                    {{--room_id: '{{ $room->id }}',--}}
                                    {{--images: images--}}
                                {{--},--}}
                                {{--type:'post',--}}
                                {{--success: function (response) {--}}
                                    {{--if(response.status == 1)--}}
                                    {{--{--}}
                                        {{--$('#uploaded-images').html(response.html);--}}
                                    {{--}--}}
                                {{--}--}}
                            {{--});--}}

                        {{--}--}}
                    {{--}--}}

                }
            }
        });
    });


</script>
<script>
    $(document).ready(function () {
        $('.datepicker').datepicker({
            format: 'dd/mm/yyyy',
            autoclose: true
        });

        var input = document.getElementById('query');
        var autocomplete = new google.maps.places.Autocomplete(input, {
            types: ["geocode"],
            componentRestrictions: {country: "vn"}
        });

        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            var lat_place = place.geometry.location.lat();
            var lng_place = place.geometry.location.lng();
            $('#query_lat').val(lat_place);
            $('#query_lng').val(lng_place);
        });
    });
</script>
<script>

            @php

                $lat = null;
                $lng = null;
                $address = null;
                    if(session()->has('data') &&  !str_contains(request()->fullUrl(), 'tim-ban/cap-nhat'))
                {

                    $data = session()->get('data');


                    if(isset($data['lat'])) {
                    $lat= $data['lat'];
                    }
                     if(isset($data['lng'])) {
                    $lng= $data['lng'];
                    }

                    if(isset($data['address'])) {
                    $address= $data['address'];
                    }

                }
            else {

            if(str_contains(request()->fullUrl(), 'tim-ban/cap-nhat'))
            {
                if(isset($room))
                {
                     $lat = $room->lat;
                     $lng = $room->lng;
                     $address = $room->address;

                }
                }
            }
            @endphp

    var starting_lat = 21.028511;
    var starting_lng = 105.804817;

    @if(!empty($lat) && !empty($lng))
        starting_lat = {{ $lat }};
    starting_lng = {{ $lng }};
            @endif


    var map;
    var marker = '';
    var myLatlng;
    var geocoder = new google.maps.Geocoder();
    var infowindow = new google.maps.InfoWindow();

    function initialize() {
        var mapOptions = {
            zoom: 12,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById("map"), mapOptions);

        @if(!empty($lat) && !empty($lng))

            myLatlng = new google.maps.LatLng(starting_lat, starting_lng);
        map.setCenter({
            lat: starting_lat,
            lng: starting_lng
        });
        marker = new google.maps.Marker({
            map: map,
            position: myLatlng,
            draggable: true
        });

        @if(!empty($address))

        infowindow.setContent('{{ $address }}');
        infowindow.open(map, marker);
                @endif

        var input2 = document.getElementById('query');
        var searchBox2 = new google.maps.places.SearchBox(input2);
        //   map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
        // Bias the SearchBox results towards current map's viewport.
        google.maps.event.addListener(searchBox2, 'places_changed', function () {
            searchBox2.set('map', null);
            var places = searchBox2.getPlaces();

            var bounds = new google.maps.LatLngBounds();

            var i, place;
            for (i = 0; place = places[i]; i++) {
                (function (place) {

                    marker.setPosition(place.geometry.location);
                    infowindow.setContent(place.formatted_address);
                    infowindow.open(map, marker);

                    $('#query_lat').val(place.geometry.location.lat());
                    $('#query_lng').val(place.geometry.location.lng());

                    google.maps.event.addListener(marker, 'map_changed', function () {
                        if (!this.getMap()) {
                            this.unbindAll();
                        }
                    });
                    bounds.extend(place.geometry.location);


                }(place));

            }
            map.fitBounds(bounds);
            searchBox2.set('map', map);
            map.setZoom(Math.min(map.getZoom(), 12));

        });

        @if(empty($address))

        geocoder.geocode({'latLng': myLatlng}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {


                    $('#query_lat').val(marker.getPosition().lat());
                    $('#query_lng').val(marker.getPosition().lng());
                    infowindow.setContent(results[0].formatted_address);
                    infowindow.open(map, marker);
                }
            }
        });

        @endif


        google.maps.event.addListener(marker, 'dragend', function () {

            geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[0]) {

                        $('#query_lat').val(marker.getPosition().lat());
                        $('#query_lng').val(marker.getPosition().lng());
                        infowindow.setContent(results[0].formatted_address);
                        infowindow.open(map, marker);
                    }
                }
            });
        });
        @else

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                map.setCenter(pos);
                marker = new google.maps.Marker({
                    map: map,
                    position: myLatlng,
                    draggable: true
                });
                infowindow.setContent('Vị trí của bạn');
                infowindow.open(map, marker);

                var input2 = document.getElementById('query');
                var searchBox2 = new google.maps.places.SearchBox(input2);
                //   map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
                // Bias the SearchBox results towards current map's viewport.
                google.maps.event.addListener(searchBox2, 'places_changed', function () {
                    searchBox2.set('map', null);
                    var places = searchBox2.getPlaces();

                    var bounds = new google.maps.LatLngBounds();

                    var i, place;
                    for (i = 0; place = places[i]; i++) {
                        (function (place) {

                            marker.setPosition(place.geometry.location);
                            infowindow.setContent(place.formatted_address);
                            infowindow.open(map, marker);

                            $('#query_lat').val(place.geometry.location.lat());
                            $('#query_lng').val(place.geometry.location.lng());

                            google.maps.event.addListener(marker, 'map_changed', function () {
                                if (!this.getMap()) {
                                    this.unbindAll();
                                }
                            });
                            bounds.extend(place.geometry.location);


                        }(place));

                    }
                    map.fitBounds(bounds);
                    searchBox2.set('map', map);
                    map.setZoom(Math.min(map.getZoom(), 12));

                });


                google.maps.event.addListener(marker, 'dragend', function () {

                    geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[0]) {

                                $('#query_lat').val(marker.getPosition().lat());
                                $('#query_lng').val(marker.getPosition().lng());
                                infowindow.setContent(results[0].formatted_address);
                                infowindow.open(map, marker);
                            }
                        }
                    });
                });


            }, function () {
                myLatlng = new google.maps.LatLng(starting_lat, starting_lng);
                map.setCenter({
                    lat: starting_lat,
                    lng: starting_lng
                });
                marker = new google.maps.Marker({
                    map: map,
                    position: myLatlng,
                    draggable: true
                });

                var input2 = document.getElementById('query');
                var searchBox2 = new google.maps.places.SearchBox(input2);
                //   map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
                // Bias the SearchBox results towards current map's viewport.
                google.maps.event.addListener(searchBox2, 'places_changed', function () {
                    searchBox2.set('map', null);
                    var places = searchBox2.getPlaces();

                    var bounds = new google.maps.LatLngBounds();

                    var i, place;
                    for (i = 0; place = places[i]; i++) {
                        (function (place) {

                            marker.setPosition(place.geometry.location);
                            infowindow.setContent(place.formatted_address);
                            infowindow.open(map, marker);

                            $('#query_lat').val(place.geometry.location.lat());
                            $('#query_lng').val(place.geometry.location.lng());

                            google.maps.event.addListener(marker, 'map_changed', function () {
                                if (!this.getMap()) {
                                    this.unbindAll();
                                }
                            });
                            bounds.extend(place.geometry.location);


                        }(place));

                    }
                    map.fitBounds(bounds);
                    searchBox2.set('map', map);
                    map.setZoom(Math.min(map.getZoom(), 12));

                });


                google.maps.event.addListener(marker, 'dragend', function () {

                    geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[0]) {

                                $('#query_lat').val(marker.getPosition().lat());
                                $('#query_lng').val(marker.getPosition().lng());
                                infowindow.setContent(results[0].formatted_address);
                                infowindow.open(map, marker);
                            }
                        }
                    });
                });
            });
        } else {
            // Browser doesn't support Geolocation
            myLatlng = new google.maps.LatLng(starting_lat, starting_lng);
            marker = new google.maps.Marker({
                map: map,
                position: myLatlng,
                draggable: true
            });
        }


        if (marker != '') {


            var input2 = document.getElementById('query');
            var searchBox2 = new google.maps.places.SearchBox(input2);
            //   map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
            // Bias the SearchBox results towards current map's viewport.
            google.maps.event.addListener(searchBox2, 'places_changed', function () {
                searchBox2.set('map', null);
                var places = searchBox2.getPlaces();

                var bounds = new google.maps.LatLngBounds();

                var i, place;
                for (i = 0; place = places[i]; i++) {
                    (function (place) {

                        marker.setPosition(place.geometry.location);
                        infowindow.setContent(place.formatted_address);
                        infowindow.open(map, marker);

                        $('#query_lat').val(place.geometry.location.lat());
                        $('#query_lng').val(place.geometry.location.lng());

                        google.maps.event.addListener(marker, 'map_changed', function () {
                            if (!this.getMap()) {
                                this.unbindAll();
                            }
                        });
                        bounds.extend(place.geometry.location);


                    }(place));

                }
                map.fitBounds(bounds);
                searchBox2.set('map', map);
                map.setZoom(Math.min(map.getZoom(), 12));

            });


            geocoder.geocode({'latLng': myLatlng}, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[0]) {


                        $('#query_lat').val(marker.getPosition().lat());
                        $('#query_lng').val(marker.getPosition().lng());
                        infowindow.setContent(results[0].formatted_address);
                        infowindow.open(map, marker);
                    }
                }
            });


            google.maps.event.addListener(marker, 'dragend', function () {

                geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[0]) {

                            $('#query_lat').val(marker.getPosition().lat());
                            $('#query_lng').val(marker.getPosition().lng());
                            infowindow.setContent(results[0].formatted_address);
                            infowindow.open(map, marker);
                        }
                    }
                });
            });

        }

        @endif
    }
    google.maps.event.addDomListener(window, 'load', initialize);



</script>
@endpush