@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')
                @if(!session()->has('step'))
                    <form method="post" action="{{ url('tim-ban/step1') }}" enctype="multipart/form-data" id="form-need-more">
                        @else
                            @php $step = session()->get('step' );

                            if(session()->has('session_step'))
                            {
                                $step = session()->get('session_step');
                            }

                            if($step >= 6) {$step = 6;}

                            @endphp
                            <form method="post" action="{{ url('tim-ban/step').$step }}" enctype="multipart/form-data" id="form-need-more">
                                @endif
                                {!! csrf_field() !!}
                                <div class="col-xs-12 col-sm-8 mb-12">
                                    @if(!session()->has('step'))
                                        @include('frontend3.steps.step_1')
                                    @else
                                        @php $step = session()->get('step' );
                                            if($step >= 6) {$step = 6;}
                                        @endphp

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

                                    <div class="text-right mt-24">
                                        @if(!session()->has('step'))
                                            <button type="submit" class="btn ht-btn-primary px-24">Tiếp tục</button>
                                        @else
                                            @if(session()->get('step') < 6 )
                                                <button type="submit" class="btn ht-btn-primary px-24">Tiếp tục</button>
                                            @else
                                                <button type="submit" class="btn ht-btn-primary px-24">Đăng tin ngay
                                                </button>
                                            @endif

                                        @endif
                                    </div>
                                </div>
                            </form>

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

@endsection

@push('scripts')
{{--<script>--}}
    {{--$("#form-need-more").validate(--}}
        {{--{--}}
            {{--ignore: ".ignore",--}}
            {{--rules: {--}}
                {{--gender: {--}}
                    {{--required: true,--}}
                {{--},--}}
                {{--number_peoples: {--}}
                    {{--required: true,--}}
                {{--},--}}
                {{--province: {--}}
                    {{--required: true,--}}
                {{--},--}}
                {{--district: {--}}
                    {{--required: true,--}}
                {{--},--}}
                {{--ward: {--}}
                    {{--required: true,--}}
                {{--},--}}
                {{--address: {--}}
                    {{--required: true,--}}
                {{--},--}}
                {{--date_available: {--}}
                    {{--required: true,--}}
                {{--},--}}
                {{--age: {--}}
                    {{--required: true,--}}
                {{--},--}}
                {{--price: {--}}
                    {{--required: true,--}}
                    {{--min: 1--}}
                {{--},--}}
                {{--size: {--}}
                    {{--required: true,--}}
                    {{--min: 1--}}
                {{--},--}}
                {{--desc: {--}}
                    {{--required: true,--}}
                {{--}--}}
            {{--},--}}
            {{--messages: {--}}
                {{--gender: "Không được bỏ trống giới tính",--}}
                {{--number_peoples: "Không được bỏ trống số người",--}}
                {{--province: "Không được bỏ trống tỉnh / thành phố",--}}
                {{--district: "Không được bỏ trống quận / huyện",--}}
                {{--ward: "Không được bỏ trống phường xã",--}}
                {{--address: "Không được bỏ trống địa chỉ",--}}
                {{--price: {--}}
                    {{--required: "Không được bỏ trống giá",--}}
                    {{--min: 'Giá phải lớn hơn 0'--}}
                {{--},--}}
                {{--size: {--}}
                    {{--required: "Không được bỏ trống diện tích",--}}
                    {{--min: 'Diện tích phải lớn hơn 0'--}}
                {{--},--}}
                {{--desc: "Không được bỏ trống miêu tả",--}}
                {{--age: "Không được bỏ trống tuổi",--}}
                {{--date_available: "Không được bỏ trống ngày chuyển đến"--}}
                {{--// image: 'Vui lòng không bỏ trống hình ảnh'--}}
            {{--}--}}
        {{--}--}}
    {{--);--}}
{{--</script>--}}
@endpush

@push('scripts')
<script src="/assets/global/plugins/bootbox/bootbox.min.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/2.1.2/jquery.scrollTo.min.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 reader = new FileReader();

                    reader.onload = function (e) {
                        $('<div class="single-uploaded-image">' +
                            '<div class="image-wrap ht-rectangle ratio-11">' +
                            '<div class="ht-inner">' +
                            '<img src="' + e.target.result + '" alt=""' +
                            'class="image-main">' +
                            '</div>' +
                            '</div>' +
                            '<a href="#" class="image-delete-btn"><i class="ion-android-close"></i></a>' +
                            '</div>').insertBefore('#form-upload');
                    }


                    reader.readAsDataURL(input.files[i]);

                    var form_data = new FormData();
                    form_data.append('image', input.files[i]);

                    $.ajax({
                        url: '{{ url('upload-image-room-need-more') }}',
                        type: 'post',
                        dataType: 'json',
                        data: form_data,
                        processData: false,
                        contentType: false,
                        enctype: 'multipart/form-data',
                        cache: false,
                        success: function (response) {
                        },
                        error: function (error) {

                        }
                    });
                }
            }
        }
    }

    $("#image-input2").change(function () {
        readURL2(this);
    });

    $(document).ready(function () {
        var step = '{{ $step }}';
        $.scrollTo('#step-' + step, 800);

    });

    $(document).on('click', '.image-delete-btn', 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('update-images-need-more-upload') }}',
                        data: {
                            image: name
                        },
                        type: 'post',
                        success: function (response) {
                            if (response.status == 1) {
                                $(that).parent().remove();
                            }
                        }
                    });

                }
            }
        });


    });


</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();

    var current_lat = localStorage.getItem('current_lat');
    var current_lng = localStorage.getItem('current_lng');

    if (current_lat === null || current_lng === null) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                if (typeof (Storage) !== 'undefined') {
                    localStorage.setItem('current_lat', position.coords.latitude);
                    localStorage.setItem('current_lng', position.coords.longitude);

                    current_lat = parseFloat(position.coords.latitude);
                    current_lng = parseFloat(position.coords.longitude);
                }
            });
        }
    }

    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

            current_lat = localStorage.getItem('current_lat');
        current_lng = localStorage.getItem('current_lng');

        if (current_lat !== null && current_lng !== null) {

            current_lat = parseFloat(current_lat);
            current_lng = parseFloat(current_lng);

            var myLatlng = new google.maps.LatLng(current_lat, current_lng);
            var pos = {
                lat: current_lat,
                lng: current_lng
            };

        } else {
            var myLatlng = new google.maps.LatLng(starting_lat, starting_lng);
            var pos = {
                lat: starting_lat,
                lng: starting_lng
            };
        }
        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);
                    }
                }
            });
        });


        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