<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @package    Wp_Tymber_Shop
 * @subpackage Wp_Tymber_Shop/admin
 * @author     Tymber <dev@tymber.me>
 * @since      1.0.0
 */
class Wp_Tymber_Shop_Admin {

	/**
	 * 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 this plugin.
	 * @param      string $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {
		$this->plugin_name = $plugin_name;
		$this->version     = $version;

		if ( ! get_option( '_tv2_lite_disable_relative_url' ) ) {
			/* Disable Relative URLs on admin dashboard ( and while not doing AJAX ) */
			if ( ! is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ){
				add_action( 'registered_taxonomy', array( $this, 'tv2_buffer_start_relative_url' ) );
				add_action( 'shutdown', array( $this, 'tv2_buffer_end_relative_url' ) );
			}
		}

		if ( ! get_option( '_tv2_lite_turnoff_mainsite_redirection' ) ) {
			add_action( 'wp', array( $this, 'tv2_lite_redirect_to_main_domain' ) );
		}

		if ( ! get_option( '_tv2_lite_disable_storemenu' ) ) {
			add_action( 'rest_api_init', array( $this, 'tv2_lite_add_custom_headers' ), 15 );
			add_action( 'rest_api_init', function () {
				register_rest_route( 'sidebar-nav', '/store/', array(
					'methods'  => 'GET',
					'callback' => function() {
						$sidebarmenu_name   = 'store';
						$sidebarmenu_exists = wp_get_nav_menu_object( $sidebarmenu_name );
						if ( ! $sidebarmenu_exists ) {
							$sidebarmenu_id = wp_create_nav_menu( $sidebarmenu_name );
						}
						return wp_get_nav_menu_items( 'store' );
					 },
				));
			} );
		}

		if ( ! get_option( '_tv2_lite_enable_wild_url_guesses' ) ) {
			add_filter( 'redirect_canonical', array( $this, 'tv2_lite_remove_redirect_guess_404_permalink' ) );
		}
	}

	/**
	 * Loads the Carbon Fields
	 *
	 * @since      1.0.0
	 */
	public function crb_load() {
		\Carbon_Fields\Carbon_Fields::boot();
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @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 Wp_Tymber_Shop_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Wp_Tymber_Shop_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		wp_enqueue_media();

		wp_enqueue_script($this->plugin_name, WP_TYMBER_SHOP_URL . 'admin/js/wp-tymber-shop-admin.js?1', array('jquery', 'wp-util'), $this->version, true);

		$update_page = false;

		if ( get_option( 'wp_tymber_shop_version' ) && get_option( '_tymber-api_token' ) ) {
			$update_page = true;
		}
		wp_localize_script(
			$this->plugin_name,
			'tymber_admin',
			array(
				'update_page' => $update_page
			)
		);
	}


	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @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 Wp_Tymber_Shop_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Wp_Tymber_Shop_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_style($this->plugin_name, WP_TYMBER_SHOP_URL . '/admin/css/wp-tymber-shop-admin.css', array(), $this->version, 'all');
	}

	public function tv2_callback_relative_url( $buffer ) {
		// Replace normal URLs
		$home_url = esc_url(home_url('/'));
		$home_url_relative = wp_make_link_relative($home_url);

		// Replace URLs in inline scripts
		$home_url_escaped = str_replace('/', '\/', $home_url);
		$home_url_escaped_relative = str_replace('/', '\/', $home_url_relative);

		$buffer = str_replace($home_url, $home_url_relative, $buffer);
		$buffer = str_replace($home_url_escaped, $home_url_escaped_relative, $buffer);

		return $buffer;
	}

	public function tv2_lite_add_custom_headers() {
		add_filter( 'rest_pre_serve_request', function( $value ) {
			header( 'Access-Control-Allow-Headers: Authorization, X-WP-Nonce,Content-Type, X-Requested-With');
			header( 'Access-Control-Allow-Origin: *' );
			header( 'Access-Control-Allow-Methods: GET' );
			header( 'Access-Control-Allow-Credentials: true' );

			return $value;
		} );
	}

	public function tv2_lite_remove_redirect_guess_404_permalink( $redirect_url ) {
		if ( is_404() && ! isset( $_GET['p'] ) ) {
			return false;
		}

		return $redirect_url;
	}

	public function tv2_buffer_start_relative_url() { ob_start( array( $this, 'tv2_callback_relative_url' ) ); }
	public function tv2_buffer_end_relative_url() { @ob_end_flush(); }

	public function tv2_lite_redirect_to_main_domain() {
		if ( ! is_user_logged_in() && $GLOBALS['pagenow'] !== 'wp-login.php' && !is_admin() && is_page()  ) {
			$first_two_letters =  $_SERVER['REQUEST_URI'][0].$_SERVER['REQUEST_URI'][1];


			if( $_SERVER['REQUEST_URI'] =='' || $_SERVER['REQUEST_URI'] =='/' || substr($_SERVER['REQUEST_URI'], -1) == '/' || $first_two_letters == '/?' ){

			}
			else{
				if( $_SERVER['QUERY_STRING'] !='' ){
					$path = str_replace("?".$_SERVER['QUERY_STRING'],"",$_SERVER['REQUEST_URI']);
					$path = rtrim($path,"/"). '/'."?".$_SERVER['QUERY_STRING'];
					if( $path != $_SERVER['REQUEST_URI'] ){
						wp_redirect(  $path );
						exit();
						die;
					}
				}
				else
				{
					$path = $_SERVER['REQUEST_URI'];
					$path = rtrim($path,"/"). '/';
					wp_redirect(  $path );
					exit();
					die;
				}

			}
		}
	}
}
