<?php  
namespace WCQT\classes\frontend;

class ShopPage
{
	public function __construct()
	{
		//Add to cart button management
		add_filter('woocommerce_loop_add_to_cart_link',array($this,'render_add_to_cart_button_on_shop_page'),99, 2); 
		
		add_filter('woocommerce_before_shop_loop', array($this, 'before_shop_page_rendering'));
	}
	function render_add_to_cart_button_on_shop_page($original_text, $product)
	{
		global $wcqt_product_model, $wcqt_user_model, $wcqt_option_model, $wcqt_wpml_model;
		
		$options = $wcqt_option_model->get_options();
		$current_lang = $wcqt_wpml_model->get_current_language();
		
		if($product->get_type() == 'variable')
			return $original_text;
		
		$enable_add_to_cart_button = wcqt_get_value_if_set($options, array('general', 'show_add_to_cart_button'), false) == 'true';
		
		$products = $wcqt_product_model->get_quotable_products_list();
		$add_to_cart_button = $enable_add_to_cart_button ? $original_text." " : "";
		if($products == "always" || in_array($product->get_id(), $products))
			return $add_to_cart_button.sprintf( '<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>',
													esc_url(  $product->add_to_cart_url()."&add_to_quote=yes" ),
													esc_attr( 1 ),
													esc_attr( $product->get_id() ),
													esc_attr( $product->get_sku() ),
													esc_attr( 'button wp-element-button add_to_cart_button wcqt_add_to_quote_button product_type_simple'), //To enable ajax: ajax_add_to_cart. It however redirect to product page instead of shop page 
													wcqt_get_value_if_set($options, array('texts', 'add_to_quote_button', $current_lang), esc_html__("Add to quote", 'woocommerce-quote'))
													);
		else 
			return $original_text;
	}
	
	function before_shop_page_rendering()
	{
		global $wcqt_option_model;
		
		$options = $wcqt_option_model->get_options();
		$target_url = get_page_link(wcqt_get_value_if_set($options, array('general', "quote_page_id"), ""));
		
		wp_enqueue_style('wcqt-shop-page', WCQT_PLUGIN_PATH.'/css/frontend/shop-page.css');
		wp_register_script( 'wcqt-shop-page', WCQT_PLUGIN_PATH.'/js/frontend/shop-page.js', array('jquery') );	
		$js_data = array( 
						'ajax_url' => admin_url( 'admin-ajax.php' ),
						'security' => wp_create_nonce('wcqt_shop_page_security'),
						'is_cart_fragments_js_enqueued' => wp_script_is('wc-cart-fragments') ? "true" : "false",
						'quote_page_url' => $target_url,
					);
		wp_localize_script('wcqt-shop-page', 'wcqt_shop_page', $js_data);
		wp_enqueue_script( 'wcqt-shop-page');
	}
	
}
?>