<?php
namespace Datacake\Core\Shortcodes;

use Datacake\Core\Models\IspCity;
use Datacake\Core\Utils;

class CityShortcode {
    public $cityEntity = null;
    public $utils = null;
    public function __construct()
    {
        $this->cityEntity = new IspCity();
        $this->utils = new Utils();
    }
    public function shortcode_pin_city($attrs){
        $opt = shortcode_atts(array(
            'class' => 'pin-city',
            'class-marker' => 'fa fa-map-marker',
            'class-dropdown' => 'fa fa-chevron-down'
        ), $attrs);
        $class = $opt['class'];
        $classMarker = $opt['class-marker'];
        $classDropdown = $opt['class-dropdown'];
        $data_redirect_id = get_option('datacake_redir_page_id',null);
        global $wp;
        $currentUrl = home_url( add_query_arg( array(), $wp->request ) );
        
        $link = get_permalink($data_redirect_id)."?redirect=".$currentUrl;
        $city = $this->utils->getCity();
        $name = isset($city->name) ? $city->name : 'Selecione uma cidade';
        return "
            <div class=\"$class\">
                <a href=\"$link\">
                    <i aria-hidden=\"true\" class=\"$classMarker\"></i>
                    <span class=\"pl-1\">
                        $name
                    </span>
                    <i class=\"$classDropdown\"></i>
                </a>
            </div>
        ";

    }
    public function shortcode_select_cities($attrs = null)
    {
        ////global $wpdb;
        $opt = shortcode_atts(array(
            'display_field' => 'name',
            'group_class' => 'form-group',
            'group_id' => 'choosecity-formgroup',
            'name' => 'in-cities',
            'select-class' => 'form-control',
            'btn_id' => 'chooseCitySubmit',
            'btn_class' => 'btn btn-outline-primary text-white',
            'btn_text' => 'Continuar',
            'ignore_neighborhood' => false,
            'auto_select'=>false,
        ), $attrs);
        $referer = isset($_GET['redirect'])?$_GET['redirect']:get_home_url();
        $html = "";
        $query = $this->cityEntity->orderBy('name','ASC');
        if($opt['ignore_neighborhood']){
            $query = $query->where('is_neighborhood',false);
        }
        $auto_select = $opt['auto_select'];
        $cities = $query->get();

       
        if (!empty($cities)) {
            //$html .= '<form action="/home">';
            $html .= '<div class id="'.$opt['group_id'].'" class="'.$opt['group_class'].'" >';
            $html .= '<select name="' . $opt['name'] . '" class="form-control" id="'.$opt['name'].'" aria-required="true" aria-invalid="false" onchange="detect_city_select_change(this)">';
            $html .= "<option value=''>Selecione uma cidade</option>";
            $cityCookie = false;
            $cityCookie = $this->utils->getCity();
            foreach ($cities as $city) {
                $seleted = ($cityCookie && $city->id == $cityCookie->id) ? "selected='selected'" : "";
                $html .= "<option value='" . $city->id . "' " . $seleted . " >" . $city->{$opt['display_field']} . "</option>";
            }
            $html .= "</select>";
            if (!$auto_select) {
                $html .= "<button onClick=\"send_to_page(event)\" type=\"submit\" id=\"".$opt['btn_id']."\" class=\"".$opt['btn_class']."\"> ".$opt['btn_text']." </button>";
            }
            $html .= "</div>";
            //$html .= "</form><!---->";

            $html .= "
                <script>
                    function send_to_page(event){
                        if(event.preventDefault){
                            event.preventDefault();
                        }
                        var e = document.getElementById(\"".$opt['name']."\");
                        var cityId = e.value;
                        if(cityId){
                            var _url = '$referer';
                            // Let's check if referer is not the same url
                            if(_url.includes(location.href)){
                                _url = '/';
                            }
                            var url = _url;
                            url += (_url.split('?')[1] ? '&':'?') + 'city_id='+cityId;
                            window.location = url;
                        }else{
                            
                            e.classList.add('shake')
                            e.classList.add('shake-hard');
                            setTimeout(function(){
                                e.classList.remove('shake')
                                e.classList.remove('shake-hard');
                            },1000);
                            
                        }
                    }
                    function detect_city_select_change(event){
                        var auto_select = new Boolean($auto_select);
                        if(auto_select){
                            send_to_page(event);
                        }
                    }
                </script>
            ";
            
            //$html .= "<input type='hidden' value='' id='in-cidade-outra' name='in-cidade-outra' />";

            //$html .= '<script> var ajaxurl = "' . admin_url('admin-ajax.php') . '"; </script>';
        }
        return $html;
    }

    public function shortcode_cities_list($attrs = null)
    {
        global $wpdb;
        $opt = shortcode_atts(array(
            'list_class' => 'g-cols via_flex valign_top type_default',
            'list_item_class' => 'vc_col-sm-{{col}} wpb_column vc_column_container',
            'col' => 3,
            'include_neighborhood' => false,
        ), $attrs);
        $col = $opt['col'];
        $list_class = $opt['list_class'];
        $list_item_class = $opt['list_item_class'];
        $list_item_class = str_replace("{{col}}",$col,$list_item_class);
        $query = $this->cityEntity->orderBy('name','ASC');
        if(!$opt['include_neighborhood']){
            $query = $query->where('is_neighborhood',false);
        }
        
        $cities = $query->get();
        
        
        $html = "<div class=\"wpb_row\"><div class=\"$list_class\">";
        
        $count = 0;
        if (!empty($cities)) {
            foreach ($cities as $city) {
                $count++;
                $last = '';
                if ($count == $col) {
                    $last = 'last';
                    $count = 0;
                }
                $name = $city->is_neighborhood ? $city->neighborhood_name : $city->name;
                $html .= "<div class='$list_item_class $last $city->code' >" . $name . "</div>";

            }
        }
        $html .= "</div></div>";
        return $html;
    }

    public function shortcode_cobertura($attrs = null)
    {
        $opt = shortcode_atts(array(
            'success' => '😊🎉✔<br>Temos cobertura em sua cidade',
            'error' => 'Infelizmente sua cidade não tem cobertura ainda.<br>Qualquer dúvida entre em contato.',
            'assine_url' => '/assine'
        ), $attrs);

        $html = '<form id="check_cobertura" class="w-form  layout_ver for_cform us_form_1" autocomplete="off" action="http://www.joao.com.br/?page_id=4540" method="post"><div class="w-form-h"><div class="w-form-row for_text cols_2">
            <div class="w-form-row-field">
                            <input aria-label="Nome" type="text" name="postal_code" value="" placeholder="CEP" maxlength="9">
                </div>
            <div class="w-form-row-state">Digite seu cep</div>
    </div>
    <div class="w-form-row cols_2">
            <div class="w-form-row-field">
                            <input aria-label="Nº da residência" type="text" name="address_number" value="" placeholder="Nº da residência">
                </div>
                <div class="w-form-row-state">Digite seu cep</div>
    </div>
    <div class="w-form-row for_submit align_center">
        <div class="w-form-row-field">
            <button class="w-btn  us-btn-style_1" aria-label="Enviar" type="submit">
                <span class="g-preloader type_1"></span>
                    <span class="w-btn-label">CONTINUAR</span>
            </button>
           
        </div>
    </div>
    </div><div id="cobertura_erro" c;ass="text_center" style="display:none;"> '.$opt['error'].'</div></form>
    
    <div id="cobertura_sucesso" class="card-body text_center" style="display:none;">
        <div class="form-success">
            <h3 class="text-center c-primary">'.$opt['success'].'<br>
            <a class="btn btn-primary text-white text-uppercase" href="'.$opt['assine_url'].'">assine já</a>
            </h3>
        </div><!---->
    </div>
    <script>
    jQuery(document).ready(function($){
        var url = "'.get_option('datacake_api')['url'].'"
        $( "#check_cobertura" ).submit(function( event ) {
            var data = $(this).serializeArray()
            console.log(data);
            
            event.preventDefault();
            $.get(url+"api/provider/city/"+data[0]["value"].replace(/\D/g,"")+"/postal_code/?fields=name%2Ccode%2Clat", function( data ) {
                $("#cobertura_sucesso").show();
                $("#cobertura_erro").hide();
                $("#check_cobertura").hide();
            }).fail(function() {
                
                $("#cobertura_erro").show();
                $("#cobertura_sucesso").hide();
                
            })
        });
        
      
    });
    </script>' ;
        return $html;
    }

    public function shortcode_map($attrs = null)
    {
        $padroes = shortcode_atts(array(
            'marker_icon' => 'null',
            'height' => '400px',
            'zoom' => '4',
        ), $attrs);
        $markerIcon = $padroes['marker_icon'];
        $height = $padroes['height'];
        $zoom = $padroes['zoom'];
        $token = get_option('datacake_api')['google_api_key'];
        
        $cities = $this->cityEntity->orderBy('name','ASC')->whereNotNull('long')->select('name','lat','long')->whereNotNull('lat')->get()->toArray();
        $json_cities = json_encode($cities);
        $html = "<div id=\"map_cobertura\"></div>
        <script>
        function initMap() {
            // Create an info window to share between markers.
            const infoWindow = new google.maps.InfoWindow();

            // The map, centered at Uluru
            var bounds = new google.maps.LatLngBounds();
            const map = new google.maps.Map(document.getElementById(\"map_cobertura\"), {
                zoom: $zoom,
            });
            
            var cities = JSON.parse('$json_cities');
            cities.forEach(function(city, i) {
                var pos = { 'lat': Number(city.lat), 'lng': Number(city.long) };
                
                var marker = new google.maps.Marker({
                    position:pos,
                    map,
                    title: city.name,
                    //label: city.name,
                    optimized: true,
                    markerIcon: $markerIcon
                });

                //extend the bounds to include each marker's position
                bounds.extend(marker.position);

                // Add a click listener for each marker, and set up the info window.
                marker.addListener(\"click\", () => {
                    infoWindow.close();
                    infoWindow.setContent(marker.getTitle());
                    infoWindow.open(marker.getMap(), marker);
                });
            })
            //now fit the map to the newly inclusive bounds
            map.fitBounds(bounds);

            
           
        }
        </script>
        <script
        src=\"https://maps.googleapis.com/maps/api/js?key=$token&callback=initMap&libraries=&v=weekly\"
        async
        ></script>
        <style>
        #map_cobertura {
            height: $height;
            width: 100%;
          }
        </style>          
        ";
        return $html;
    }



}