<?php 
namespace WCQT\classes\com;

class Cart
{
	function __construct()
	{
	
		//Ajax 
		add_action('wp_ajax_wcqt_add_product_to_quote', array( &$this,'ajax_add_product_to_quote'), 10);
		add_action('wp_ajax_nopriv_wcqt_add_product_to_quote', array( &$this,'ajax_add_product_to_quote'), 10);
		
		
		
		//Cart management 
		add_action('woocommerce_checkout_process', array( $this, 'checkout_validation' ));
		add_action( 'wp_loaded', array( $this, 'manage_product_page_add_to_quote' ), 20 );
		add_action('woocommerce_add_to_cart_validation', array($this, 'add_to_cart_validation'), 10, 5);
		add_action('woocommerce_update_cart_validation', array($this, 'cart_update_validation'), 10, 4);
		
		//Visibility management
		add_filter('pre_get_posts', array( $this,'check_which_products_to_hide_and_update_the_cart')); //wp_loaded //posts_request
		
		//Price management 
		add_filter('woocommerce_get_price_html', array(&$this, 'manage_html_price'), 10, 2 );
		add_filter('woocommerce_show_variation_price', array(&$this, 'manage_variation_html_price'), 10, 3 ); //displays the HTML prices
		add_filter('woocommerce_variation_prices', array(&$this, 'manage_variation_prices_array'), 10, 3 ); //triggered after all the variation prices (regular and sales) have been retrieved
	}
	
	public function manage_html_price($price, $product)
	{
		global $wcqt_option_model, $wcqt_product_model;
		$options = $wcqt_option_model->get_options();
		
		if(wcqt_get_value_if_set($options, array('general', 'show_prices'), "false") == "true" || is_admin())
			return $price;
		
		$quotable_products = $wcqt_product_model->get_quotable_products_list(); 
		$quotable_variations = $wcqt_product_model->quotable_variations($product);
		$is_variable = $product->is_type('variable');
		
		if($quotable_products == "always" || (!$is_variable && in_array($product->get_id(), $quotable_products)) || ($is_variable && !empty($quotable_variations)))
		{
			return "";
		}
		return $price;
	}
	public function manage_variation_html_price($show, $product, $variation)
	{
		global $wcqt_option_model, $wcqt_product_model;
		$options = $wcqt_option_model->get_options();
		
		if(wcqt_get_value_if_set($options, array('general', 'show_prices'), "false") == "true" || is_admin())
			return true;
		
		$quotable_products = $wcqt_product_model->get_quotable_products_list(); 
		$quotable_variations = $wcqt_product_model->quotable_variations($product);
		$is_variable = $product->is_type('variable');
		
		if($quotable_products == "always" || (!$is_variable && in_array($product->get_id(), $quotable_products)) || (in_array($variation->get_id(), $quotable_variations)) )
		{
			return false;
		}
		
		return $show;
	}
	//This is useful only if only some variation has been selected for quoting
	function manage_variation_prices_array($prices_array, $product, $for_display)
	{
		global $wcqt_product_model, $wcqt_option_model;
		$options = $wcqt_option_model->get_options();
		if(wcqt_get_value_if_set($options, array('general', 'show_prices'), "false") == "true" || is_admin())
			return $prices_array;
		
		$result = $wcqt_product_model->quotable_variations($product);
		if(!$result)
			return $prices_array;
		$prices_type = ['price', 'regular_price', 'sale_price'];
		foreach($result as $variation_id)
			foreach($prices_type as $price_type)
			{
				if(isset($prices_array[$price_type][$variation_id]))
					unset($prices_array[$price_type][$variation_id]);
			}
			
		return $prices_array;
	}
	public function check_which_products_to_hide_and_update_the_cart($query)
	{
		global $wcqt_user_model, $wcqt_product_model, $wcqt_option_model;
		
		$options = $wcqt_option_model->get_options();
		if(!wcqt_get_value_if_set($options, array('general', 'hide_quotable_products'), false) || is_admin())
			return $query;
		
		if( (@is_single() || @is_shop() || @is_archive() || @is_category() ||@is_page() || @is_cart() || @is_checkout())) //Due bad 'woocommerce_is_checkout' action managment by WooCommerce One Step Checkout plugin
		{
			$quotable_products = $wcqt_product_model->get_quotable_products_list(false); 
			$can_request_a_quote = $wcqt_user_model->can_request_a_quote();
			if(!$can_request_a_quote)
			{
				if( $quotable_products != 'always')
					$query->set('post__not_in', array_merge($query->query_vars['post__not_in'], $quotable_products));
				else
					$query->set('p', -123123); //simulating request a not existing product
			}
		}
		return $query;
	}
	
	//Add to Quote list (product page page). Reference: class-wc-form-handler -> add_to_cart_action
	public function manage_product_page_add_to_quote()
	{
		if ( ! isset( $_REQUEST['add-to-quote-product-page'] ) || ! is_numeric( wp_unslash( $_REQUEST['add-to-quote-product-page'] ) ) ) {
			return;
		}

		wc_nocache_headers();
		
		$product_id     = apply_filters( 'woocommerce_add_to_cart_product_id', absint( wp_unslash( $_REQUEST['add-to-quote-product-page'] ) ) );
		$variation_id = empty( $_REQUEST['variation_id'] ) ? 0 : absint( wp_unslash( $_REQUEST['variation_id'] ) );
		$this->add_to_cart_validation(true, $product_id, wp_unslash( $_REQUEST['quantity'] ), $variation_id , null, true);
		
	}
	//Add to Quote list via ajax 
	public function ajax_add_product_to_quote()
	{
		$product_id = filter_input( INPUT_POST, 'product_id', FILTER_VALIDATE_INT );
		$quantity = filter_input( INPUT_POST, 'quantity', FILTER_VALIDATE_INT );
		if($product_id && (wp_verify_nonce( wcqt_get_value_if_set($_POST, 'security', ""), 'wcqt_shop_page_security' ) || wp_verify_nonce( wcqt_get_value_if_set($_POST, 'security', ""), 'wcqt_product_page_security' )))
		{
			$this->add_to_cart_validation(true, $product_id, $quantity);
		}
		wp_die();
	}
	//Add to Quote list (product page) avoiding to be added to cart
	public function add_to_cart_validation( $original_result, $product_id, $quantity , $variation_id = 0, $variations = null, $added_via_post_on_product_page = false )
	{
		global $woocommerce, $wcqt_session_model, $wcqt_product_model, $wcqt_user_model, $wcqt_wpml_model, $wcqt_option_model;
		$options = $wcqt_option_model->get_options();
		$quotable_products = $wcqt_product_model->get_quotable_products_list(); 
		$product_can_be_purchased = wcqt_get_value_if_set($options, array('general', 'show_add_to_cart_button'), false) == 'true';
		$wc_product = wc_get_product($product_id);
		//double check on variation management 
		if($wc_product->is_type('variation'))
		{
			$variation_id = $product_id;
			$product_id = $wc_product->get_parent_id();
		}
		$quotable_variations = $wcqt_product_model->quotable_variations($product_id);
		
		
		
		$add_to_quote_action = wcqt_get_value_if_set($_REQUEST, 'action', 'none') == 'wcqt_add_product_to_quote'; //Added to quote list via shop page (ajax request)
		if(!$added_via_post_on_product_page && !$add_to_quote_action && $product_can_be_purchased)
			return $original_result;
		 
		if($quotable_products == "always" || (in_array($product_id, $quotable_products)) || ($variation_id != 0 && in_array($variation_id, $quotable_variations)) )
		{
			$wc_product = wc_get_product($variation_id ? $variation_id : $product_id);
			$title = isset($wc_product) && $wc_product != false ? $wc_product->get_title( ) : "";
			$wcqt_session_model->add_product_to_quote_list($product_id, $variation_id, $quantity);
			$curr_lang = $wcqt_wpml_model->get_current_language();
			$message = wcqt_get_value_if_set($options, array('shop_page', 'texts', 'added_to_list', $curr_lang), esc_html__('%s added to quote list', 'woocommerce-quote'));
			
			wc_add_notice(sprintf($message, $title),'success');
			
			
			//To check if ajax redirect is active:  if('yes' === get_option( 'woocommerce_cart_redirect_after_add' ))
			//NOTE if set to yes, REMEMBER TO REMOVE ITEM FROM CART
			return false; //To make the ajax work after clicking the "add to quote" button, this needs to return "true";
		}
		return $original_result;
	}
	//Update cart
	public function cart_update_validation($original_result, $cart_item_key, $values, $quantity )
	{
		global $woocommerce, $wcqt_session_model, $wcqt_product_model, $wcqt_user_model, $wcqt_option_model;
		$options = $wcqt_option_model->get_options();
		$product_can_be_purchased = wcqt_get_value_if_set($options, array('general', 'show_add_to_cart_button'), false) == 'true';
		
		if($product_can_be_purchased)
			return $original_result;
		
		$items = WC()->cart->cart_contents;
		$quotable_products = $wcqt_product_model->get_quotable_products_list(); 
		$quotable_variations = $wcqt_product_model->quotable_variations($product_id);
		
		if(isset($items[$cart_item_key]))
		{
			if($quotable_products == "always" || (in_array($items[$cart_item_key]['product_id'], $quotable_products)) || ($variation_id != 0 && in_array($items[$cart_item_key]['variation_id'], $quotable_variations)))
			{
				$wc_product = wc_get_product($items[$cart_item_key]['variation_id'] ? $items[$cart_item_key]['variation_id'] : $items[$cart_item_key]['product_id']);
				$title = isset($wc_product) && $wc_product != false ? $wc_product->get_title( ): "";
				wc_add_notice( sprintf(esc_html__('"%s" cannot be purchased. It will be removed from the cart.', 'woocommerce-quote') , $title) ,'error');
				WC()->cart->remove_cart_item($cart_item_key);
			}
		}
		return $original_result;
	}
	function checkout_validation()
	{
		global $woocommerce, $wcqt_session_model, $wcqt_product_model, $wcqt_user_model, $wcqt_option_model;
		$options = $wcqt_option_model->get_options();
		$quotable_products = $wcqt_product_model->get_quotable_products_list(); 
		$items_to_remove = array();
		$results = array();
		
		$product_can_be_purchased = wcqt_get_value_if_set($options, array('general', 'show_add_to_cart_button'), false) == 'true';
		
		if($product_can_be_purchased)
			return;
		
		foreach(WC()->cart->get_cart() as $cart_item_key => $item)
		{
			$wc_product = wc_get_product($item['variation_id'] ? $item['variation_id'] : $item['product_id']);
			$title = isset($wc_product) && $wc_product != false ? $wc_product->get_title( ): "";
			
			if($quotable_products == "always" || (in_array($item['product_id'], $quotable_products) || ($item['variation_id'] != 0 && in_array($item['variation_id'], $quotable_products))))
			{
				$results[] = sprintf( esc_html__('"%s" cannot be purchased. It will be removed from your order.','woocommerce-quote'), $title);
				$items_to_remove[] = $cart_item_key;
			}
		}
		
		if(!empty($items_to_remove))
			foreach($items_to_remove as $item_to_remove)
				WC()->cart->remove_cart_item($item_to_remove);
		
		foreach($results as $result)
			wc_add_notice( $result ,'error');
	}
	//
	
	//For some reasons, product added to quote are redirected to product page instead of shop page. This fixes that issue
	public function add_to_cart_redirect($url, $product)
	{
		global $wcqt_product_model, $wcqt_user_model;
		
		if(!$product)
			return $url;
		$products = $wcqt_product_model->get_quotable_products_list();
		if($products == "always" || in_array($product->get_id(), $products))
			return get_permalink( wc_get_page_id( 'shop' ) );
			
		return $url;
	}
}
?>