<?php
/**
 * The public-facing functionality of the plugin.
 *
 * @link       http://www.datacake.com.br
 * @since      1.0.0
 *
 * @package    Datacake_core
 * @subpackage Datacake_core/public
 */
namespace Datacake\Core\Pub;
use Datacake\Core\Models\IspCity;
use Datacake\Core\Models\IspRedirect;
use Datacake\Core\Utils;
use Datacake\Core\Shortcodes\CityShortcode;
use Datacake\Core\Shortcodes\ChannelShortCode;
use Datacake\Core\Shortcodes\CoberturaShortcode;
use Datacake\Core\Widgets\CitySEOWidget;

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 *
 * @package    Datacake_core
 * @subpackage Datacake_core/public
 * @author     Datacake <ajuda@datacake.com.br>
 */
class DatacakeCorePublic {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;
	
	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of the plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;
		$this->register_short_codes();

	}

	public function register_short_codes(){
		$cityShortcode = new CityShortcode();
		add_shortcode('dk_city_list', array($cityShortcode, 'shortcode_cities_list'));
		add_shortcode('dk_city_select', array($cityShortcode, 'shortcode_select_cities'));
		add_shortcode('dk_city_pin', array($cityShortcode, 'shortcode_pin_city'));
		add_shortcode('dk_city_cobertura', array($cityShortcode, 'shortcode_cobertura'));
		add_shortcode('dk_city_map', array($cityShortcode, 'shortcode_map'));
		$channelShortCode = new ChannelShortCode();
		add_shortcode('dk_channels', array($channelShortCode, 'shortcode_canais'));

		
		add_action('widgets_init', array($this, 'register_widgets'));
	}

	public function register_post_types(){
		/**
		 * Cadastro de Lista de Planos
		 */
		// Portfolio Categories
		register_taxonomy(
			'isp_planos_category', array( 'isp_planos' ), array(
				'labels' => array(
					'name' => apply_filters( 'isp_planos_category_label', __( 'Categorias de Planos', 'datacake_core' ) ),
					'menu_name' =>  'Categorias',
				),
				'show_admin_column' => TRUE,
				'hierarchical' => TRUE,
				'rewrite' => array( 'slug' => 'planos_category_slug' ),
			)
		);

		// Portfolio Tags
		register_taxonomy(
			'isp_planos_tag', array( 'isp_planos' ), array(
				'labels' => array(
					'name' => apply_filters( 'isp_planos_tags_label', __( 'Tags de Planos', 'datacake_core' ) ),
					'menu_name' =>  'Tags' ,
				),
				'show_admin_column' => TRUE,
				'rewrite' => array( 'slug' => 'planos_tag_slug' ),
			)
		);
		

		$args = array(
			'labels' => array(
				'name' => __( 'DK Planos', 'datacake_core' ),
				'singular_name' => __( 'DK Plano', 'datacake_core' ),
				'add_new' => __( 'Adicionar Novo Plano', 'datacake_core' ),
				'add_new_item' => __( 'Adicionar Novo Plano', 'datacake_core' ),
				'edit_item' => __( 'Editar Plano', 'datacake_core' ),
				'featured_image' => __( 'Featured Image', 'datacake_core' ),
				'view_item' => __( 'Ver Plano','datacake_core'),
				'not_found' => __( 'Nenhum plano encontrado','datacake_core' ),
				'not_found_in_trash' => __( 'Nenhum plano encontrado no lixo.', 'datacake_core' ),
			),
			'description' => 'Datacake Post do tipo Planos',
			'public' => false,
			'show_ui' => true,
			'show_in_admin_bar' => true,
			'show_in_rest' => false,
			'menu_position' => 6,
			'menu_icon' => 'dashicons-products',
			'rewrite' => false,
			'supports' => array(
				'title',
				'editor',
				'thumbnail',
				'custom-fields'
			),
		);
		register_post_type( 'isp_planos', $args );
		
		/**
		 * Cadastro de Canais
		 */
		// Portfolio Categories
		register_taxonomy(
			'isp_canais_category', array( 'isp_canais' ), array(
				'labels' => array(
					'name' => apply_filters( 'isp_canais_category_label', __( 'Categorias de Canais', 'datacake_core' ) ),
					'menu_name' =>  'Categorias',
				),
				'show_admin_column' => TRUE,
				'hierarchical' => TRUE,
				'rewrite' => array( 'slug' => 'planos_category_slug' ),
			)
		);

		// Portfolio Tags
		register_taxonomy(
			'isp_canais_tag', array( 'isp_canais' ), array(
				'labels' => array(
					'name' => apply_filters( 'isp_canais_tags_label', __( 'Tags de Canais', 'us' ) ),
					'menu_name' =>  'Tags' ,
				),
				'show_admin_column' => TRUE,
				'rewrite' => array( 'slug' => 'planos_tag_slug' ),
			)
		);


		$args = array(
			'labels' => array(
				'name' => __( 'DK Canal', 'datacake_core' ),
				'singular_name' => __( 'DK Canal', 'datacake_core' ),
				'add_new' => __( 'Adicionar Novo Canal', 'datacake_core' ),
				'add_new_item' => __( 'Adicionar Novo Canal', 'datacake_core' ),
				'edit_item' => __( 'Editar Canal', 'datacake_core' ),
				'featured_image' => __( 'Featured Image', 'datacake_core' ),
				'view_item' => __( 'Ver Canal','datacake_core'),
				'not_found' => __( 'Nenhum Canal encontrado','datacake_core' ),
				'not_found_in_trash' => __( 'Nenhum Canal encontrado no lixo.', 'datacake_core' )
			),
			'description' => 'Datacake Post do tipo Canais',
			'public' => false,
			'show_ui' => true,
			'show_in_admin_bar' => true,
			'show_in_rest' => false,
			'menu_position' => 6,
			'menu_icon' => 'dashicons-playlist-video',
			'rewrite' => false,
			'supports' => array(
				'title',
				'editor',
				'thumbnail',
				'custom-fields'
			),
		);
		register_post_type( 'isp_canais', $args );
		 
	}

	function register_widgets(){
		register_widget(new CitySEOWidget);
	}
	/**
	 * Register the stylesheets for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in DatacakeCoreLoader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The DatacakeCoreLoader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/datacake_core-public.css', array(), $this->version, 'all' );
		wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/csshake.min.css', array(), $this->version, 'all' );

	}

	/**
	 * Register the JavaScript for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in DatacakeCoreLoader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The DatacakeCoreLoader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/datacake_core-public.js', array( 'jquery' ), $this->version, false );
	}
	/**
	 * This function will do the redirect logic based on the city cookie
	 */
	function page_redirects($query)
	{
		// If adming we do not do the behavior
		
		if (empty($query->is_admin)) {

			$page_id = null;
			if (!empty($query->query_vars['page_id']) || !empty($query->queried_object->ID)) {
				//$this->setCity($cidade['nome']);
				if ($query->query_vars['page_id'] != 0) {
					$page_id = $query->query_vars['page_id'];
				} else {
					$page_id = $query->queried_object->ID;
				}
			}
			
			$utils = new Utils();
			$city = $utils->getCity();
			// If city exists we will find if we have redirects
			if($city){
				if($page_id){
					$redirect = IspRedirect::where('from_page_id',$page_id)
					->whereHas(
						'cities',function($query){
							$utils = new Utils();
							$city = $utils->getCity();
							$query->where('city_id',$city->id);
						}
					)->first();
					if($redirect){
						$query->query_vars['page_id'] = $redirect->to_page_id;
						if (isset($query->queried_object)) $query->queried_object->ID = $redirect->to_page_id;
					}
				}
			}else{
				if($page_id){
					$data_force_redirect = get_option('datacake_redir_force',null);
					$data_redirect_id = get_option('datacake_redir_page_id',null);
					
					if($data_force_redirect && $data_redirect_id){
						global $wp;
						$currentUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
						if(strpos($currentUrl, 'wp-admin') !== false || strpos($currentUrl, 'wp-login') !== false){
							//Admin or login found in the current url let's not redirect
						}else{
							$redirect = isset($_GET['redirect']) ? $_GET['redirect'] : $currentUrl;
							$link = get_permalink($data_redirect_id)."?redirect=".$redirect;
							if($data_redirect_id != $page_id){
								header("Location: $link");
								die();
							}
						}
					}
				}
			}
		}
	}
	/**
	 * This function check for city_id or city on the GET params and set 
	 * the cookie and session to be used for other functionalites
	 */
	function set_cookie_based_on_get()
    {	
		$utils = new Utils();
		$cur_city = $utils->getCity();
		$city = null;
		if (isset($_GET['city_id'])) {
			if($cur_city && $cur_city->id == $_GET['city_id']){
				return;
			}
			$city = IspCity::find(sanitize_key($_GET['city_id']));
		}
        if (isset($_GET['city']) && !$city) {
			if($cur_city && $cur_city->code == $_GET['city']){
				return;
			}
			$city = IspCity::where('name',sanitize_text_field($_GET['city']))->first();
			if(!$city){
				$city = IspCity::where('code',sanitize_text_field($_GET['city']))->first();
			}
		}
		
		
		if($city){
			$utils->setCity($city->id);
		}
    }

	/**
	 * This function adds the cities to the Sitemap to essencialy dupliate the number of posts and pages
	 */
	function add_sitemap_custom_items($sitemap_custom_items = "")
	{
		
	
		global $wpdb;
        $cidades = $wpdb->get_results("SELECT nome FROM {$wpdb->prefix}lp_cidades order by nome", 'ARRAY_A');
		$cityEntity = new IspCity();
		$cidades = $cityEntity->select('id','name','code')->orderBy('name','ASC')->get();
        

        foreach ($cidades as $cidade) {
            $nome = $cidade['code'];
            
            $link = \WPSEO_Sitemaps_Router::get_base_url("?city=$nome");
            //$link = WPSEO_Utils::sanitize_url($link);
            //$date = $this->timezone->format_date( $cidade['lastmod'] );
          //  echo $nome;
          //<lastmod>2017-03-16T10:56:41-03:00</lastmod>
            $sitemap_custom_items .= "<url>
        		<loc> $link</loc>
        		<changefreq>weekly</changefreq>
                <priority>0.8</priority>
        	</url>";
        }
    	return $sitemap_custom_items;

	}
}
