@extends('frontend3')

@section('styles')
    <style>
        svg {
            width: 16px;
            height: 16px;
        }
    </style>
@endsection

@section('content')
    @php $agent = new \Jenssegers\Agent\Agent(); @endphp

    <div id="siteContent" class="site-content">
        <div class="property-list property-list--has-map-desktop clearfix">
            <div class="property-list__list-by-card-section">
                <div class="property-list__search">
                    <form action="">
                        <div class="form-group my-0">
                            <div class="flex-item flex-item-tw">
                                <label class="search-label hidden-xs">Tìm kiếm</label>
                            </div>
                            <div class="flex-item flex-item-dw">
                                <input type="text" class="serach-input form-control form-control-lg px-0" id="query"
                                       placeholder="Tìm theo tên đường, khu vực, thành phố,...">
                            </div>
                            <input type="hidden" id="query_lat" name="lat" value="{{ request()->input('lat') }}">
                            <input type="hidden" id="query_lng" name="lng" value="{{ request()->input('lng') }}">
                            <div class="flex-item flex-item-tw">
                                <button type="submit" class="search-submit btn ht-btn-default btn-lg btn-icon"><i
                                            class="ion-ios-search-strong"></i></button>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="property-list__filter">
                    <div class="property-list__filter__show-content">
                        <div class="row">
                            <div class="col-xs-12 col-sm-6 more-pr">
                                <div class="row">
                                    <div class="col-xs-4">
                                        <div class="filter-label-wrap">
                                            <label>Tỉnh / Thành phố</label>
                                        </div>
                                    </div>
                                    <div class="col-xs-8">
                                        <div class="filter-input-wrap">
                                            <select class="select2-form-control form-control" id="province">
                                                <option value="" selected>Chọn</option>
                                                @foreach($provinces as $province)
                                                    <option value="{{ $province->provinceid }}">{{ $province->name }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-xs-12 col-sm-6 more-pl more-mt-on-xs">
                                <div class="row">
                                    <div class="col-xs-4">
                                        <div class="filter-label-wrap">
                                            <label>Quận / Huyện</label>
                                        </div>
                                    </div>
                                    <div class="col-xs-8">
                                        <div class="filter-input-wrap">
                                            <select class="select2-form-control form-control" id="district">

                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-xs-12 col-sm-6 more-pr">
                                <div class="row">
                                    <div class="col-xs-4">
                                        <div class="filter-label-wrap">
                                            <label>Xã / Phường</label>
                                        </div>
                                    </div>
                                    <div class="col-xs-8">
                                        <div class="filter-input-wrap">
                                            <select class="select2-form-control form-control" id="ward">

                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-xs-12 col-sm-6 more-pl more-mt-on-xs">
                                <div class="row">
                                    <div class="col-xs-4">
                                        <div class="filter-label-wrap">
                                            <label>Khoảng giá</label>
                                        </div>
                                    </div>
                                    <div class="col-xs-8">
                                        <div class="filter-input-wrap">
                                            <select class="form-control" name="price" id="price">
                                                <option value="0" selected>Vui lòng chọn</option>
                                                <option value="1">Dưới 1 triệu</option>
                                                <option value="2">Từ 1 đến 2 triệu</option>
                                                <option value="3">Từ 2 đến 3 triệu</option>
                                                <option value="4">Từ 3 đến 5 triệu</option>
                                                <option value="5">Từ 5 đến 7 triệu</option>
                                                <option value="6">Từ 7 đến 10 triệu</option>
                                                <option value="7">Từ 10 đến 15 triệu</option>
                                                <option value="8">Trên 15 triệu</option>
                                            </select>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="property-list__filter--collapsed-content" id="content-collapse" style="display: none">
                        <div class="row">
                            <div class="col-xs-4 col-sm-2">
                                <div class="filter-label-wrap">
                                    <label>Tiện ích</label>
                                </div>
                            </div>
                            <div class="col-xs-8 col-sm-9">
                                <div class="form-group">
                                    @foreach ($amenities->chunk(3) as $chunk)
                                        <div class="row">

                                            @foreach ($chunk as $item)
                                                <div class="col-xs-12 col-sm-4">

                                                    <div class="checkbox checkbox--customized">

                                                        <label class="ws-nw"><input type="checkbox" class="amenities"
                                                                                    @if(is_array($checkedAmenities))
                                                                                    @if(in_array($item->id, $checkedAmenities)) checked
                                                                                    @endif
                                                                                    @endif  value="{{ $item->id }}">

                                                            <span></span>

                                                            <img src="/files/{{ $item->web_image }}" class="svg"
                                                                 style="max-height: 18px; max-width: 18px; margin-right: 3px"> {{ $item->name }}
                                                        </label></div>
                                                </div>
                                            @endforeach
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-xs-4 col-sm-2">
                                <div class="filter-label-wrap">
                                    <label>Quy định</label>
                                </div>
                            </div>
                            <div class="col-xs-8 col-sm-9">
                                <div class="form-group">
                                    @foreach ($policies->chunk(3) as $chunk2)
                                        <div class="row">
                                            @foreach ($chunk2 as $item2)
                                                <div class="col-xs-12 col-sm-4">
                                                    <div class="checkbox checkbox--customized"><label class="ws-nw">
                                                            <input type="checkbox" class="policies"
                                                                   @if(is_array($checkedPolicies))
                                                                   @if(in_array($item2->id, $checkedPolicies)) checked
                                                                   @endif
                                                                   @endif  value="{{ $item2->id }}">
                                                            <span></span>
                                                            <img src="/files/{{ $item2->web_image }}"
                                                                 style="max-height: 18px; max-width: 18px; margin-right: 3px">
                                                            {{ $item2->name }}</label>
                                                    </div>
                                                </div>
                                            @endforeach
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="property-list__filter__action">
                        <div class="flex flex-ai-center flex-jc-between">
                            <div class="flex-item">
                                <a href="#" class="btn ht-btn-default" id="collapse">Thêm bộ lọc</a>
                            </div>
                            <div class="flex-item">
                                <a href="#" class="btn ht-btn-default px-24" id="set-default">Mặc định</a>
                                <a href="#" class="btn ht-btn-primary px-24" id="filter">Lọc</a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="property-list__toggle-view hidden-md hidden-lg">
                    <ul id="propertyList_toggleViewNav" class="list-unstyled">
                        <li class="active select-box" data-type="list"><a href="#"><i class="ion-grid mr-8"></i>Hiển thị danh sách</a></li>
                        <li class="select-box" data-type="map"> <a href="#"><i class="ion-android-map mr-8"></i>Hiển thị bản đồ</a></li>
                    </ul>
                </div>
                <div class="list-property-cards py-24 px-36 ht-styled-scroll has-max-width-on-md mx-auto mobile-view-active" id="hostels">

                </div>
            </div>

            <div class="@if($agent->isMobile()) hidden @endif property-list__list-on-map-section bg-color-grey-200" id="map">

            </div>
        </div>
    </div>
@endsection

@push('scripts')

<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="/js/infobox.js"></script>
<script type="text/javascript" src="/frontend/scripts/markerclusterer.js"></script>
<script type="text/javascript" src="/js/gmap.js"></script>

<script>
    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);
                    map.setCenter({
                        lat: current_lat,
                        lng: current_lng,
                    })
                }
            });
        }
    }
</script>
<script>
    @if($agent->isMobile())
$('.select-box').click(function(e) {
        e.preventDefault();
        var type = $(this).attr('data-type');
        $('.select-box').removeClass('active');
        $(this).addClass('active');

        if(type == 'list')
        {
            $('#hostels').removeClass('hidden');
            $('#map').addClass('hidden');
        } else {
            $('#map').removeClass('hidden').css({
                width: '100%',
                height: '100vh'
            });
            $('#hostels').addClass('hidden');
            map = new GMaps({
                div: '#map',
                lat: '21.0333',
                lng: '105.8500',
                zoom: 13,
                clickableIcons: false
            });

            var data = getValue();
            $.ajax({
                url: '{{ url('search-need-more-attr') }}',
                type: 'get',
                data: data,
                dataType: 'json',
                success: function (response) {
                    $('#hostels').html(response.html);
                    pushStateUrl(response.url);
                    map.removeOverlays();
                    bounds = [];
                    $.each(response.locations, function (key, value) {
                        var that = this;
                        var latlng = new google.maps.LatLng(value.lat, value.lng);
                        bounds.push(latlng);
                        overlay = map.drawOverlay({
                            lat: value.lat,
                            lng: value.lng,
                            content: value.content,
                            click: function () {
                                $('.items-map').hide();
                                var flag = $('[data-coor="' + value.lat + ',' + value.lng + '"]').data('flag');
                                if (flag) {
                                    $('[data-coor="' + value.lat + ',' + value.lng + '"]').show();
                                } else {
                                    $('[data-coor="' + value.lat + ',' + value.lng + '"]').hide();
                                }
                                $('[data-coor="' + value.lat + ',' + value.lng + '"]').data('flag', !flag);
                            }
                            // icon: '<div style="height: 50px; width: 50px; background-color: red">123</div>'
                        });


                    });

//                map.idle(function() {
//                    var textData = $('.room-data');
//
//                    textData.css({'line-height': textData.width() + 'px'});
//                });

                    map.setCenter({
                        lat: parseFloat(response.center.lat),
                        lng: parseFloat(response.center.lng),
                    });

                    if (bounds.length > 1) {

                        map.fitLatLngBounds(bounds);
                    } else {
                        map.setZoom(13);
                    }


                    {{--map.addMarker({--}}
                    {{--lat: parseFloat(response.center.lat),--}}
                    {{--lng: parseFloat(response.center.lng),--}}
                    {{--infoWindow: {--}}
                    {{--content: '{{ $hostel->name }}'--}}
                    {{--}--}}
                    {{--});--}}
                    // map.fitZoom();
                }
            });

        }
    });
@endif

    var bounds = [];

    function getValue() {
        var amenities = [];
        var policies = [];
        var province = '';
        var district = '';
        var ward = '';
        var lat = '';
        var lng = '';
        var price = 0;
        var q = '';

        $('.amenities:checked').each(function (i) {
            amenities.push($(this).val());
        });

        $('.policies:checked').each(function (i) {
            policies.push($(this).val());
        });

        province = $('#province').val();
        district = $('#district').val();
        ward = $('#ward').val();
        lat = $('#query_lat').val();
        lng = $('#query_lng').val();
        price = $('#price').val();
        q = $('#query').val();

        return {
            price: price,
            amenities: amenities,
            policies: policies,
            province: province,
            district: district,
            ward: ward,
            lat: lat,
            lng: lng,
            q: q
        }

    }


    function getData(data, url) {

        url = url || '{{ url('search-need-more-attr') }}';
        $.ajax({
            url: url,
            type: 'get',
            data: data,
            dataType: 'json',
            success: function (response) {
                $('#hostels').html(response.html);
                pushStateUrl(response.url);
                map.removeOverlays();
                bounds = [];
                $.each(response.locations, function (key, value) {
                    var that = this;
                    var latlng = new google.maps.LatLng(value.lat, value.lng);
                    bounds.push(latlng);
                    overlay = map.drawOverlay({
                        lat: value.lat,
                        lng: value.lng,
                        content: value.content,
                        click: function () {
                            $('.items-map').hide();
                            var flag = $('[data-coor="' + value.lat + ',' + value.lng + '"]').data('flag');
                            if (flag) {
                                $('[data-coor="' + value.lat + ',' + value.lng + '"]').show();
                            } else {
                                $('[data-coor="' + value.lat + ',' + value.lng + '"]').hide();
                            }
                            $('[data-coor="' + value.lat + ',' + value.lng + '"]').data('flag', !flag);
                        }

                    });

                });
                map.setCenter({
                    lat: parseFloat(response.center.lat),
                    lng: parseFloat(response.center.lng),
                });

                if (bounds.length > 1) {

                    map.fitLatLngBounds(bounds);
                } else {
                    map.setZoom(13);
                }
            }
        });
    }

    $(document).on('change', '#province', function (e) {
        $.ajax({
            url: '{{ url('get-sub-location') }}',
            type: 'get',
            data: {
                'id': $(this).val(),
                'type': 'province'
            },
            dataType: 'html',
            success: function (response) {
                $('#district').html(response);
                $('#ward').html('');

            }
        });
    });

    $(document).on('change', '#district', function (e) {
        $.ajax({
            url: '{{ url('get-sub-location') }}',
            type: 'get',
            data: {
                'id': $(this).val(),
                'type': 'district'
            },
            dataType: 'html',
            success: function (response) {
                $('#ward').html(response);

            }
        });
    });

    function pushStateUrl(url) {
        var obj = {Title: 'title', Url: url};
        history.pushState(obj, obj.Title, obj.Url);
    }

    $(document).on('click', 'div.text-center.py-24 > ul > li > a', function (e) {
        e.preventDefault();
        var url = $(this).attr('href');
        var data = getValue();
        getData(data, url);
    });

    $(document).ready(function () {

        $('.property-room-in-map').each(function () {
            var textData = $(this).find('.room-data');
            textData.css('line-height', textData.width() + 'px');
        });


        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);
            var data = getValue();
            getData(data);
        });


        $('#collapse').click(function () {
            $('#content-collapse').toggle();
            if ($('#collapse').text() == 'Thêm bộ lọc') {
                $('#collapse').text('Thu nhỏ');
            } else {
                $('#collapse').text('Thêm bộ lọc');
            }
        });

        map = new GMaps({
            div: '#map',
            lat: '21.0333',
            lng: '105.8500',
            zoom: 13,
            clickableIcons: false
        });

        var data = getValue();
        $.ajax({
            url: '{{ url('search-need-more-attr') }}',
            type: 'get',
            data: data,
            dataType: 'json',
            success: function (response) {
                $('#hostels').html(response.html);
                pushStateUrl(response.url);
                map.removeOverlays();
                bounds = [];
                $.each(response.locations, function (key, value) {
                    var that = this;
                    var latlng = new google.maps.LatLng(value.lat, value.lng);
                    bounds.push(latlng);
                    overlay = map.drawOverlay({
                        lat: value.lat,
                        lng: value.lng,
                        content: value.content,
                        click: function () {
                            $('.items-map').hide();
                            var flag = $('[data-coor="' + value.lat + ',' + value.lng + '"]').data('flag');
                            if (flag) {
                                $('[data-coor="' + value.lat + ',' + value.lng + '"]').show();
                            } else {
                                $('[data-coor="' + value.lat + ',' + value.lng + '"]').hide();
                            }
                            $('[data-coor="' + value.lat + ',' + value.lng + '"]').data('flag', !flag);
                        }
                        // icon: '<div style="height: 50px; width: 50px; background-color: red">123</div>'
                    });


                });

//                map.idle(function() {
//                    var textData = $('.room-data');
//
//                    textData.css({'line-height': textData.width() + 'px'});
//                });

                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);
                    map.setCenter({
                        lat: parseFloat(current_lat),
                        lng: parseFloat(current_lng),
                    });
                    map.setZoom(13);
                } else {

                    map.setCenter({
                        lat: parseFloat(response.center.lat),
                        lng: parseFloat(response.center.lng),
                    });


                    map.setZoom(13);
//                    if (bounds.length > 1) {
//
//                        map.fitLatLngBounds(bounds);
//                    } else {
//                        map.setZoom(13);
//                    }
                }


                {{--map.addMarker({--}}
                {{--lat: parseFloat(response.center.lat),--}}
                {{--lng: parseFloat(response.center.lng),--}}
                {{--infoWindow: {--}}
                {{--content: '{{ $hostel->name }}'--}}
                {{--}--}}
                {{--});--}}
                // map.fitZoom();
            }
        });


//
//        $('.amenities').click(function () {
//            var data = getValue();
//            getData(data);
//
//        });

//        $('#district, #ward, #province').on('change', function () {
//            var data = getValue();
//            getData(data);
//
//        });
    });


    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#register-image').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#image-input").change(function () {
        readURL(this);
    });

    $('#set-default').click(function (e) {
        e.preventDefault();
        $('.amenities').prop('checked', false);
        $('.policies').prop('checked', false);
        $('.ws-nw').css({
            color: 'black'
        }).find('svg').css({
            fill: 'black'
        });

        $('.select2-form-control').val('').trigger('change');
        $('#price').val(0);
        $('#query').val('');
        $('#query_lat').val('');
        $('#query_lng').val('');
        //   $('#province').val('');

    });


    $(function () {

        $('#filter').click(function (e) {
            e.preventDefault();
            var data = getValue();
            getData(data);

//            var lastScrollTop = 0;
//            var st = $('.property-list__list-by-card-section').scrollTop();


            var h = $('.property-list__search').outerHeight() + $('.property-list__filter').outerHeight();
            var s = $('.property-list__list-by-card-section').animate({scrollTop: '+'+h+'px'}, 800);
            // console.log(y);

        });
        jQuery('img.svg').each(function () {
            var $img = jQuery(this);
            var imgID = $img.attr('id');
            var imgClass = $img.attr('class');
            var imgURL = $img.attr('src');

            jQuery.get(imgURL, function (data) {
                // Get the SVG tag, ignore the rest
                var $svg = jQuery(data).find('svg');

                // Add replaced image's ID to the new SVG
                if (typeof imgID !== 'undefined') {
                    $svg = $svg.attr('id', imgID);
                }
                // Add replaced image's classes to the new SVG
                if (typeof imgClass !== 'undefined') {
                    $svg = $svg.attr('class', imgClass + ' replaced-svg');
                }

                // Remove any invalid XML tags as per http://validator.w3.org
                $svg = $svg.removeAttr('xmlns:a');

                // Check if the viewport is set, else we gonna set it if we can.
                if (!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
                    $svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))
                }

                // Replace image with new SVG
                $img.replaceWith($svg);

            }, 'xml');

        });
    });


</script>

@endpush