<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @link       http://xplodedthemes.com
 * @since      1.0.0
 *
 * @package    XT_Woo_Floating_Cart
 * @subpackage XT_Woo_Floating_Cart/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    XT_Woo_Floating_Cart
 * @subpackage XT_Woo_Floating_Cart/public
 * @author     XplodedThemes <helpdesk@xplodedthemes.com>
 */
class XT_Woo_Floating_Cart_Public {

	/**
	 * Core class reference.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      XT_Woo_Floating_Cart    core    Core Class
	 */
	private $core;


	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param    obj    $core    Plugin core class
	 */
	public function __construct( &$core ) {

		$this->core = $core;
		
	}
	
	function init_ajax() {
		
		require_once $this->core->plugin_path() . 'public/class-ajax.php';
	}

	function body_class($classes) {
		
		$trigger_hide_view_cart = xt_woofc_option('trigger_hide_view_cart', false);
		
		if(!empty($trigger_hide_view_cart)) {
			$classes[] = 'xt_woofc-hide-view-cart';
		}
		
		return $classes;
	}

	/**
	 * 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 XT_Woo_Floating_Cart_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The XT_Woo_Floating_Cart_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_register_style('woofcicons', $this->core->plugin_url( 'public/assets/css', 'woofcicons.css'), array(), $this->core->plugin_version(), 'all' );
		wp_enqueue_style('woofcicons');

		wp_register_style(
		    $this->core->plugin_slug(),
            $this->core->plugin_url( 'public/assets/css', 'frontend.css'),
            array(),
            filemtime($this->core->plugin_path( 'public/assets/css', 'frontend.css')),
            'all'
        );
		wp_enqueue_style( $this->core->plugin_slug());

		if(is_rtl()) {
			wp_register_style(
			    $this->core->plugin_slug('rtl'),
                $this->core->plugin_url( 'public/assets/css', 'rtl.css'),
                array($this->core->plugin_slug()),
                filemtime($this->core->plugin_path( 'public/assets/css', 'rtl.css')),
                'all'
            );
			wp_enqueue_style( $this->core->plugin_slug('rtl'));
		}
	}

	/**
	 * 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 XT_Woo_Floating_Cart_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The XT_Woo_Floating_Cart_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		
		// LOAD WOOCOMMERCE DEPENDENCIES
		$wc_suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
		$wc_ajax_cart_enabled    = 'yes' === get_option( 'woocommerce_enable_ajax_add_to_cart' );
		if($wc_ajax_cart_enabled !== 'yes') {
			update_option( 'woocommerce_enable_ajax_add_to_cart', 'yes' );
		}
		
		$wc_assets_path          = str_replace( array( 'http:', 'https:' ), '', WC()->plugin_url() ) . '/assets/';
		$wc_frontend_script_path = $wc_assets_path . 'js/frontend/';
		
		
		wp_enqueue_script( 'wc-add-to-cart', $wc_frontend_script_path . 'add-to-cart' . $wc_suffix . '.js', array( 'jquery'));
		wp_enqueue_script( 'wc-cart-fragments', $wc_frontend_script_path . 'cart-fragments' . $wc_suffix . '.js', array( 'jquery', 'jquery-cookie' ) );

		// LOAD VENDORS
		wp_enqueue_script("jquery-effects-core");
		wp_enqueue_script( $this->core->plugin_slug('jquery.ajaxqueue'), $this->core->plugin_url( 'public' ) . 'assets/vendors/jquery.ajaxqueue'.$this->core->script_suffix.'.js', array( 'jquery' ), $this->core->plugin_version(), false );
		wp_enqueue_script( $this->core->plugin_slug('jquery.touch'), $this->core->plugin_url( 'public' ) . 'assets/vendors/jquery.touch'.$this->core->script_suffix.'.js', array( 'jquery' ), $this->core->plugin_version(), false );
		wp_enqueue_script( $this->core->plugin_slug('cookie'), $this->core->plugin_url( 'public' ) . 'assets/vendors/js.cookie'.$this->core->script_suffix.'.js', array( 'jquery' ), $this->core->plugin_version(), false );
		wp_enqueue_script( $this->core->plugin_slug('tweenmax'), $this->core->plugin_url( 'public' ) . 'assets/vendors/TweenMax'.$this->core->script_suffix.'.js', array( 'jquery' ), $this->core->plugin_version(), false );
		wp_enqueue_script( $this->core->plugin_slug('jquery.serializejson'), $this->core->plugin_url( 'public' ) . 'assets/vendors/jquery.serializejson'.$this->core->script_suffix.'.js', array( 'jquery' ), $this->core->plugin_version(), false );
		
		// MAIN SCRIPT
		wp_register_script(
		    $this->core->plugin_slug(),
            $this->core->plugin_url( 'public/assets/js', 'frontend'.$this->core->script_suffix.'.js'),
            array( 'jquery', 'wc-cart-fragments' ),
            filemtime($this->core->plugin_path( 'public/assets/js', 'frontend'.$this->core->script_suffix.'.js')),
            false
        );

		$vars = array(
            'can_use_premium_code' => $this->core->fs()->can_use_premium_code__premium_only(),
			'ajaxurl' => admin_url('admin-ajax.php'),
			'wc_ajax_url' => home_url('/?wc-ajax=%%endpoint%%'),
			'lang' => array(
				'wait' => esc_html__('Please wait', 'woo-floating-cart'),
				'loading' => esc_html__('Loading', 'woo-floating-cart'),
				'min_qty_required' => esc_html__('Min quantity required', 'woo-floating-cart'),
				'max_stock_reached' => esc_html__('Stock limit reached', 'woo-floating-cart')
			)
		);
		
		wp_localize_script( $this->core->plugin_slug(), 'XT_WOOFC', $vars );
		wp_enqueue_script($this->core->plugin_slug());
	}

	/**
	 * Load frontend Theme Fixes.
	 * @access  public
	 * @since   1.0.0
	 * @return void
	 */
	public function enqueue_theme_fixes () {
		
		$theme_name = get_template();
		
		$theme_fixes = array(
		//	'theme-name' => array('css', 'js')
		);
	
		if(!empty($theme_fixes[$theme_name])) {
			
			foreach($theme_fixes[$theme_name] as $type) {
				
				if($type == 'css') {
				
					wp_register_style( $this->core->plugin_slug($theme_name), $this->core->plugin_url( 'public' ) . 'assets/theme-fix/css/' . $theme_name . '.css', array( $this->core->plugin_slug() ), $this->core->plugin_version() );
					wp_enqueue_style( $this->core->plugin_slug($theme_name) );
					
				}else{
				
					wp_register_script( $this->core->plugin_slug($theme_name), $this->core->plugin_url( 'public' ) . 'assets/theme-fix/js/' . $theme_name . '.js', array( $this->core->plugin_slug() ), $this->core->plugin_version(), true );
					wp_enqueue_script( $this->core->plugin_slug($theme_name) );
				}
			
			}
	
		}

	} // End enqueue_theme_fixes ()
	
	
	function add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {

		WC()->session->set( 'xt_woofc_last_added', $cart_item_key);

		return $cart_item_key;		
	}
	
	function add_to_cart_fragments($fragments) {
		
		WC()->cart->calculate_totals();
		
		$list = xt_woo_floating_cart_template('parts/cart/list', array(), true);
		$total = xt_woofc_checkout_total();
		$count = WC()->cart->get_cart_contents_count();
		
		$fragments['xt_woofc'] = array(
			'subtotal' => $total,
			'total_items' => $count,
		);	
		
		if(empty($_COOKIE['xt_woofc_last_removed'])) {
			$fragments['.xt_woofc-list'] = $list;
		}
		$fragments['.xt_woofc-checkout span.amount'] = '<span class="amount">'.$total.'</span>';
		$fragments['.xt_woofc-count li:nth-child(1)'] = '<li>'.$count.'</li>';
		$fragments['.xt_woofc-count li:nth-child(2)'] = '<li>'.($count + 1).'</li>';
		
		return $fragments;
	}
	
	function remove_cart_item($cart_item_key, $wc_cart) {
		
		$position = array_search($cart_item_key, array_keys($wc_cart->cart_contents));
		WC()->session->set( 'xt_woofc_removed_position', $position);
		
		WC()->cart->calculate_totals();
	}
	
	function cart_item_restored($cart_item_key, $wc_cart) {

		$position = WC()->session->get( 'xt_woofc_removed_position');
		
		$restored_item = $wc_cart->cart_contents[$cart_item_key];
		
		$bundled_product = false;
		if(function_exists('wc_pb_is_bundled_cart_item')) {
			$bundled_product = true;
		}

		if(!$bundled_product) {
			
			unset($wc_cart->cart_contents[$cart_item_key]);
			
			$new_cart_contents = array();
			$i = 0;
			$repositioned = false;
			foreach($wc_cart->cart_contents as $key => $item) {
				
				if($i == $position) {
					$new_cart_contents[$cart_item_key] = $restored_item;
					$repositioned = true;
				}
				
				$new_cart_contents[$key] = $item;
				$i++;
			}
			
			if(!$repositioned) {
				$new_cart_contents[$cart_item_key] = $restored_item;
			}
			
			$wc_cart->cart_contents = $new_cart_contents;
		}
		
		WC()->session->__unset( 'xt_woofc_removed_position');
		
		WC()->cart->calculate_totals();
	}
	
	public function render() {
		
		$exlude_pages = xt_woofc_option('hidden_on_pages', array());
		if(!empty($exlude_pages)) {
			foreach($exlude_pages as $page) {
				if(!empty($page) && is_page($page)) {
					return false;
				}
			}
		}
		
		echo '<div id="xt_woofc">';
		xt_woo_floating_cart_template('minicart');
		echo '</div>';
	}	
}
