<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-body">
            <input type="hidden" name="is_crm" id="is_crm" value="<?php  echo $is_crm ? 1 : 0;?>"/>
            <div class="row form-group ">
                <div class="col-md-2">
                    <label><?php  echo CommonLanguage::getMessage('region');?></label>
                    <input type="hidden" id="region_id" name="region_id" class="full-width" />
                </div>
                <div class="col-md-2">
                    <label><?php  echo CommonLanguage::getMessage('customer_group');?></label>
                    <input type="hidden" id="customer_group_id" name="customer_group_id" class="full-width" />
                </div>
                <div class="col-md-2">
                    <label><?php  echo CommonLanguage::getMessage('city');?></label>
                    <input type="hidden" id="city_id" name="city_id" class="full-width" />
                </div>
                <div class="col-md-2">
                    <label><?php  echo CommonLanguage::getMessage('routes');?></label>
                    <input type="hidden" id="route_ids" name="route_ids" class="full-width" />
                </div> 
                <div class="col-md-2 m-t-20">
                    <input type="checkbox" id="is_not_linked_to_route" name="is_not_linked_to_route" />
                    <label><?php  echo CommonLanguage::getMessage('is_not_linked_to_route');?></label>
                </div>
            </div>
            <div class="row">
                <button style="color:white !important;" class="btn bg-primary-darker white" id="assign_route"><?php print CommonLanguage::getMessage('assign_route'); ?></button>
                <button style="color:white !important;" class="btn bg-primary-darker white" id="unassign_route"><?php print CommonLanguage::getMessage('unassign_route'); ?></button>
                <button style="color:white !important;" class="btn bg-primary-darker white" id="clear_selected"><?php print CommonLanguage::getMessage('clear_selected'); ?></button>
            </div>
            <div class="row m-t-10">
                <div style="color:white !important;" class="col-md-12 alert alert-warning" id="selected_pins_text"><?php  echo CommonLanguage::getMessage('no_pins_selected');?></div>
            </div>
            <div class="row">
                <div id="map" style="width:100%;height:600px;background:#95a5a6"></div>
            </div>
        </div>
        <?php echo Forms::ModalLoader('route_customer_loader'); ?>
    </div>
</div>
<div class="modal fade" id="assign_route_modal" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="bold"><?php echo CommonLanguage::getMessage('assign_route'); ?></h5>
            </div>
            <div class="modal-body">
                <div class="row"><?php echo Forms::AlertDiv('assign_route_alert'); ?></div>
                <form id="assign_route_form" method="POST" onsubmit="return false">
                    <div class="row form-group">
                        <div class=" col-md-12  " >
                            <label class="labelText">
                                <?php print CommonLanguage::getMessage('route'); ?>
                                <span class="red-star">*</span>
                            </label>
                            <input type="hidden" id="current_route_id" name="route_id" class="full-width " required />
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close'); ?></button>
                <button class="btn bg-primary-darker white" id="submit_assign_route"><?php print CommonLanguage::getMessage('Save'); ?></button>
            </div>
            <?php echo Forms::ModalLoader('assign_route_loader'); ?>
        </div>
    </div>
</div>
<script>
    var selected_pins = [];
    var myMap;
    var markers = [];
	  var inital_lng_val = <?php echo json_encode(smc_session()['default_setting']['customer_map_lng']); ?>,
     inital_lat_val = <?php echo json_encode(smc_session()['default_setting']['customer_map_lat']); ?>,
     inital_lng =  inital_lng_val != '' ? inital_lng_val : '33.5571',
     inital_lat =  inital_lat_val != '' ? inital_lat_val : '35.3729';
    $(function(){
        build_select2($("#city_id"), "xhr/searchCity"); 
        build_select2($("#region_id"), "xhr/commonSearch?table=tbl_regions&col_id=region_id&col_name=region_name"); 
        build_select2($("#customer_group_id"), "xhr/general_group_Search?group_type=cust"); 
        build_select2($("#route_ids"), "xhr/commonSearch?table=tbl_route&col_id=route_id&col_name=route_name",1); 
        build_select2($("#current_route_id"), "xhr/commonSearch?table=tbl_route&col_id=route_id&col_name=route_name"); 
        $('#city_id,#region_id,#customer_group_id,#route_ids').on('change',function(){
            loadMarker();
        });
        loadMarker();
        $('#is_not_linked_to_route').on('click',function(){
            if($(this).is(":checked")){
                $('#route_ids').val('').trigger('change');
            }else{
                loadMarker(); 
            }
        });
        $('#assign_route').on('click',function(){
            if(selected_pins.length == 0){
                toastr.error('<?php echo CommonLanguage::getMessage('no_pins_selected');?>');
                return;
            }
            $('#assign_route_modal').modal('show');    
        });
        $('#unassign_route').on('click',function(){
            if(selected_pins.length == 0){
                toastr.error('<?php echo CommonLanguage::getMessage('no_pins_selected');?>');
                return;
            }
            var Data = new FormData();
            Data.append('cust_ids',JSON.stringify(selected_pins));
            Data.append('route_id','');
            Data.append('is_crm',$('#is_crm').val());
            $('#route_customer_loader').removeClass('hidden');
            $.ajax({
                url: "GeneralAjax/submitCustomersRoute",
                method: "POST",
                data: Data,
                processData: false,
                contentType: false,
                dataType: "JSON",
                complete: function (jqXHR, status) {
                    if (status == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            toastr.success(jqXHR.responseJSON[0]);
                            loadMarker();
                            $('#clear_selected').trigger('click')
                        }else{
                            toastr.error(jqXHR.responseJSON[0]);
                        }
                    }
                    $('#route_customer_loader').addClass('hidden');
                }
            });
        });
        $('#clear_selected').on('click',function(){
            selected_pins = [];
            $('#selected_pins_text').html('<?php  echo CommonLanguage::getMessage('no_pins_selected');?>');
            $.each(markers, function( index, value ) {
                markers[index].setIcon('https://www.google.com/mapfiles/marker_green.png');
            });
        });
        $("#submit_assign_route").on("click", function () {
            if (!$("#assign_route_form").valid())
                return;
            $("#assign_route_loader").removeClass('hidden');
            var Data = new FormData(document.getElementById("assign_route_form"));
            Data.append('cust_ids',JSON.stringify(selected_pins));
            Data.append('is_crm',$('#is_crm').val());
            $.ajax({
                url: "GeneralAjax/submitCustomersRoute",
                method: "POST",
                data: Data,
                processData: false,
                contentType: false,
                dataType: "JSON",
                complete: function (jqXHR, status) {
                    if (status == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            hideModalAlert('assign_route_modal', 'assign_route_alert');
                            loadMarker();
                            $('#clear_selected').trigger('click');
                        }
                        AddAlert("#assign_route_alert", jqXHR.responseJSON[0], jqXHR.responseJSON[1]);
                    }
                    $("#assign_route_loader").addClass('hidden');
                }
            });
        });
    });

    //
    function initMap() {
        var mapOptions = {
             center: new google.maps.LatLng(inital_lng,inital_lat),
            zoom: 12,
            scrollwheel: false,
            mapTypeControl: true,
            fullscreenControl: true,
            mapTypeId: google.maps.MapTypeId.MAP
        };
        myMap = new google.maps.Map(document.getElementById("map"), mapOptions);
    }
    //
    function loadMarker() {
        if($("#route_ids").val())
            $('#is_not_linked_to_route').prop('checked',false);
        var data ={city_id:$('#city_id').val(),region_id:$('#region_id').val(),
                   customer_group_id:$('#customer_group_id').val(),route_ids:$("#route_ids").val(),
                   is_not_linked_to_route:$('#is_not_linked_to_route').is(":checked") ? 1 : 0,
                   is_crm:$('#is_crm').val()};
        $.ajax({
            url: "GeneralAjax/get_customers_route_map",
            method: "GET",
            data: data,
            dataType: "JSON",
            complete: function (jqXHR, status) {
                if (status == 'success') {
                    deleteMarkers();
                    if (jqXHR.responseJSON['data'].length > 0) {
                        $.each(jqXHR.responseJSON['data'],function(indx, row){
                            var mark = {lat: parseFloat(row.customer_latitude), lng: parseFloat(row.customer_longitude)};
                            var contentString = '<div id="content">' +
                                '<div id="siteNotice">' +
                                '</div>' +
                                '<h3 id="firstHeading" class="firstHeading bold">' + row.customer_name + '</h3>' +
                                '</div>';
                            addMarker(mark, row.customer_name,row.customer_id,contentString);
                        });
                    }
                }
            }
        });
    }
    function addMarker(mark, title,cust_id,contentString) {
        var marker = new google.maps.Marker({
            position: mark,
            map: myMap,
            title: title,
            cust_id:cust_id
        });
        marker.setIcon('https://www.google.com/mapfiles/marker_green.png');

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });
        marker.addListener('mouseover',function(mark){
            infowindow.open(myMap, marker);
        });
        marker.addListener('click', function (mark) {
            if(!selected_pins.includes(this.cust_id)){
                selected_pins.push(this.cust_id);
                marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png');
            }else{
                marker.setIcon('https://www.google.com/mapfiles/marker_green.png');
                selected_pins.splice($.inArray(this.cust_id, selected_pins), 1);
            }
            if(selected_pins.length == 0){
                $('#selected_pins_text').html('<?php echo CommonLanguage::getMessage('no_pins_selected');?>');
            }else{
                $('#selected_pins_text').html(selected_pins.length+'<?php echo CommonLanguage::getMessage('pins_selected');?>'); 
            }
        });

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

    // Sets the map on all markers in the array.
    function setMapOnAll(map) {
        for (var i = 0; i < markers.length; i++)
            markers[i].setMap(map);
    }
    //
    function deleteMarkers() {
        setMapOnAll(null);
        markers = [];
    }
    //

    //
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDPQfukDXQUdWN4XNMa8asJryBPtJ9iBsQ&callback=initMap"></script>
