<?php
class NBT_WooCommerce_AjaxCart_Frontend{
	protected $args;
	
	function __construct() {
	
		add_action('wp_enqueue_scripts', array($this, 'embed_style'));
		add_action( 'wp_ajax_nopriv_nbt_add_to_cart', array($this, 'nbt_add_to_cart') );
		add_action( 'wp_ajax_nbt_add_to_cart', array($this, 'nbt_add_to_cart') );
		add_action( 'wp_ajax_nopriv_nbt_remove_to_cart', array($this, 'nbt_remove_to_cart') );
		add_action( 'wp_ajax_nbt_remove_to_cart', array($this, 'nbt_remove_to_cart') );
		add_action( 'wp_ajax_nopriv_nbt_add_to_cart_single', array($this, 'nbt_add_to_cart_single') );
		add_action( 'wp_ajax_nbt_add_to_cart_single', array($this, 'nbt_add_to_cart_single') );
		add_filter('nbt_cart_icon', array($this, 'custom_nbt_cart_icon'), 10, 4);
		add_shortcode( 'nbt_ajax_cart', array($this, 'shortcode_ajax_cart'), 10, 1 );

		add_filter('woocommerce_update_order_review_fragments', array($this, 'woocommerce_update_order_review_fragments'), 9999, 1);



	}

	public function woocommerce_update_order_review_fragments($array){
		// Get order review fragment
		ob_start();
		woocommerce_order_review();
		$array['.woocommerce-checkout-review-order-table'] = ob_get_clean();


		return $array;

	}

	public function woocommerce_cart_subtotal($price){

		$wc_currency = WC()->session->get('wc_currency');
		if(!$wc_currency){
			$wc_currency = get_woocommerce_currency();
		}

		if(class_exists('NBT_Solutions_Currency_Switcher')){
			$settings_mcs = get_option('settings_mcs' );
			$this->currency = $settings_mcs[$wc_currency];

			$format = '%1$s%2$s';
			switch ($this->currency['position']) {
			    case 'left' :
				$format = '%1$s%2$s';
				break;
			    case 'right' :
				$format = '%2$s%1$s';
				break;
			    case 'left_space' :
				$format = '%1$s&nbsp;%2$s';
				break;
			    case 'right_space' :
				$format = '%2$s&nbsp;%1$s';
				break;
			}

			return wc_price($price * $this->currency['rates'], array(
				'decimals' => $this->currency['decimals'],
				'price_format' => $format,
				'currency' => $wc_currency
			));
		}else{
			return wc_price($price);
		}


		
	}

	public function shortcode_ajax_cart(){

		if(function_exists('nbt_ajax_template')){
			nbt_ajax_template();
		}
		
	}

	public function custom_nbt_cart_icon($output, $icon, $count, $price){
		return sprintf('<i class="%s"></i><span class="nbt-ac-count">%d</span>', $icon, $count);
	}

	public function nbt_remove_to_cart(){
		global $woocommerce, $currency;
		$ajax = new WC_AJAX();
		$cart = WC()->instance()->cart;

		$total = 0;
		$product_id = intval($_REQUEST['product_id']);
		$variation_id = intval($_REQUEST['variation_id']);
		$item_count = WC()->cart->cart_contents_count;
		if($item_count > 0){
			$get_cart = WC()->cart->get_cart();
			foreach ($get_cart as $item_key => $item) {
				if($item['product_id'] == $product_id && !isset($_REQUEST['variation_id'])){
					$woocommerce->cart->set_quantity( $item_key , 0 );
					$json['complete'] = true;
				}

				if($item['variation_id'] == $variation_id && isset($_REQUEST['variation_id'])){
					$woocommerce->cart->set_quantity( $item_key , 0 );
					$json['complete'] = 'ok';
				}
			}
			$json['count'] = WC()->cart->get_cart_contents_count();

			
			$get_cart = WC()->cart->get_cart();
			foreach ($get_cart as $key => $value) {
				$total += $value['line_subtotal'];
				
			}
		}

		if(WC()->cart->get_cart_contents_count() == 0){
			$json['html'] = '<p class="woocommerce-mini-cart__empty-message">'.__( 'No products in the cart.', 'woocommerce' ).'</p>';
		}


			ob_start();

			if(preg_match("/<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">(.*)<\/span>([0-9.,]+)<\/span>/", WC()->cart->get_cart_subtotal(), $output_array) && isset($currency)){
				$sub_price = explode(get_option('woocommerce_price_decimal_sep'), $output_array[2]);
				$sub_price = preg_replace('/[.,]/', '', $sub_price[0]);

				if($sub_price == $total){
					$sub_totalprice = wc_price($total * $currency['nbt_currency-switcher_rates'], array(
						'currency' => $currency['nbt_currency-switcher_repeater_currency'],
						'decimals' => $currency['nbt_currency-switcher_decimals'],
						'price_format' => NBT_Solutions_Currency_Switcher::get_woocommerce_price_format($currency['nbt_currency-switcher_position'])
					));
				}else{
					$sub_totalprice = WC()->cart->get_cart_subtotal();
				}
				
			}else{
				$sub_totalprice = 'a'.WC()->cart->get_cart_subtotal();
			}

		$json['subtotal'] = '<strong>'.__( 'Subtotal', 'woocommerce' ).':</strong> '.$sub_totalprice.'';
		echo wp_json_encode($json, TRUE);
		wp_die();
	}


	function nbt_add_to_cart(){
		global $woocommerce;
		$cart_url = wc_get_cart_url();
		$get_cart = $woocommerce->cart->get_cart();

		$product_id = $_REQUEST['product_id'];
		$quantity = 1;



		$product = wc_get_product($product_id);



		if( $product->is_type( 'simple' ) ){
			WC()->cart->add_to_cart( $product_id, 1);
	
			$json['complete'] = true;
			$total = 0;
			$get_cart = WC()->cart->get_cart();
			foreach ($get_cart as $key => $value) {
				if( $value['product_id'] == $product_id ){
					$quantity = $value['quantity'];

					if ( $product->managing_stock() ) {
						$products_qty_in_cart = WC()->cart->get_cart_item_quantities();
						if ( isset( $products_qty_in_cart[ $product->get_stock_managed_by_id() ] ) && ! $product->has_enough_stock( $products_qty_in_cart[ $product->get_stock_managed_by_id() ] + $quantity ) ) {
							$out_stock = true;
						}

					}
				}
				
				$total += $value['line_subtotal'];
			}
			$json['count'] = WC()->cart->get_cart_contents_count();
			ob_start();
			template_loop(true);
			$json['html'] = ob_get_clean();
				ob_start();
				$get_subtotal = ac_get_price($total, true);
				?>
				<p class="total"><strong><?php _e( 'Subtotal', 'woocommerce' ); ?>:</strong> <?php echo $get_subtotal;//echo WC()->cart->get_cart_subtotal(); ?></p>

				<?php do_action( 'woocommerce_widget_shopping_cart_before_buttons' ); ?>

				<p class="buttons">
					<?php do_action( 'woocommerce_widget_shopping_cart_buttons' ); ?>
				</p>
				<?php
				$sub_html = ob_get_clean();
				$json['html'] = '<div class="nbt-cart-list-wrap"><ul class="cart_list">'.$json['html'].'</ul></div>'.$sub_html;


			if(isset($out_stock)){
				$json['title'] = sprintf( __( 'You cannot add that amount to the cart &mdash; we have %1$s in stock and you already have %2$s in your cart.', 'woocommerce' ), wc_format_stock_quantity_for_display( $product->get_stock_quantity(), $product ), wc_format_stock_quantity_for_display( $products_qty_in_cart[ $product->get_stock_managed_by_id() ], $product ) );
				$json['error'] = true;
			}else{
				$json['title'] = sprintf('<div class="text-notice"><a href="%s" class="wc-forward nbt-ac-carturl">View Cart</a> <div><strong>"%s"</strong> has been added to your cart.</div></div>', esc_url($cart_url), $product->get_name() );
			}

		}else{
			$json['url'] = get_permalink($product->get_id());
		}
		echo json_encode($json, TRUE);
		wp_die();
	}

	public function nbt_add_to_cart_single(){
		global $currency;

		$product_id = absint($_REQUEST['product_id']);
		if(isset($_REQUEST['variation_id'])){
			$variation_id = absint($_REQUEST['variation_id']);
		}
		$quantity = absint($_REQUEST['quantity']);

		// Ensure we don't add a variation to the cart directly by variation ID
		if ( 'product_variation' === get_post_type( $product_id ) ) {
			$variation_id = $product_id;
			$product_id   = wp_get_post_parent_id( $variation_id );
		}

		$product = wc_get_product( $variation_id ? $variation_id : $product_id );
		
		

		$cart_url = wc_get_cart_url();
		if(class_exists('NBT_Solutions_One_Step_Checkout')){
			$cart_url = wc_get_checkout_url();
		}



		if (isset($variation_id) && !empty($variation_id)) {
			$get_attributes = $product->get_attributes( 'edit' );
			$variation = array();
			if($get_attributes){
		    	foreach ($get_attributes as $k_attribute => $value) {
					$variation['attribute_'.$k_attribute] = $value;
		    	}
			}
			$return = WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation  );
		} else {
			$return = WC()->cart->add_to_cart( $product_id, $quantity);
		}
		
		if($return){
			$total = 0;
			$get_cart = WC()->cart->get_cart();
			foreach ($get_cart as $cart_item_key => $value) {
				if( $value['product_id'] == $product_id ){
					$quantity = $value['quantity'];

					if ( $product->managing_stock() ) {
						$products_qty_in_cart = WC()->cart->get_cart_item_quantities();
						if ( isset( $products_qty_in_cart[ $product->get_stock_managed_by_id() ] ) && ! $product->has_enough_stock( $products_qty_in_cart[ $product->get_stock_managed_by_id() ] + $quantity ) ) {
							$out_stock = true;
						}
					}
				}
				$total += $value['line_subtotal'];
			}
			$json['complete'] = true;


			$json['count'] = WC()->cart->get_cart_contents_count();
			ob_start();
			template_loop(true);
			$json['html'] = ob_get_clean();

		
			ob_start();

			if(preg_match("/<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">(.*)<\/span>([0-9.,]+)<\/span>/", WC()->cart->get_cart_subtotal(), $output_array) && isset($currency)){
				$sub_price = explode(get_option('woocommerce_price_decimal_sep'), $output_array[2]);
				$sub_price = preg_replace('/[.,]/', '', $sub_price[0]);

				if($sub_price == $total){
					$sub_totalprice = wc_price($total * $currency['nbt_currency-switcher_rates'], array(
						'currency' => $currency['nbt_currency-switcher_repeater_currency'],
						'decimals' => $currency['nbt_currency-switcher_decimals'],
						'price_format' => NBT_Solutions_Currency_Switcher::get_woocommerce_price_format($currency['nbt_currency-switcher_position'])
					));
				}else{
					$sub_totalprice = WC()->cart->get_cart_subtotal();
				}
				
			}else{
				$sub_totalprice = WC()->cart->get_cart_subtotal();
			}
			
			?>
			<p class="total"><strong><?php _e( 'Subtotal', 'woocommerce' ); ?>:</strong> <?php echo $sub_totalprice;?></p>

			<?php do_action( 'woocommerce_widget_shopping_cart_before_buttons' ); ?>

			<p class="buttons">
				<?php do_action( 'woocommerce_widget_shopping_cart_buttons' ); ?>
			</p>
			<?php
			$sub_html = ob_get_clean();
			$json['html'] = '<div class="nbt-cart-list-wrap"><ul class="cart_list">'.$json['html'].'</ul></div>'.$sub_html;


			if(isset($out_stock)){
				$json['title'] = sprintf( __( 'You cannot add that amount to the cart &mdash; we have %1$s in stock and you already have %2$s in your cart.', 'woocommerce' ), wc_format_stock_quantity_for_display( $product->get_stock_quantity(), $product ), wc_format_stock_quantity_for_display( $products_qty_in_cart[ $product->get_stock_managed_by_id() ], $product ) );
				$json['error'] = true;
			}else{
				$json['title'] = sprintf('<div class="text-notice"><a href="%s" class="wc-forward nbt-ac-carturl">View Cart</a> <div><strong>"%s"</strong> has been added to your cart.</div></div>', esc_url($cart_url), $product->get_name() );
			}



		
		}else{
			$json['error'] = 'abc';
		}
		$ajaxcart_settings = get_option('ajax-cart_settings');
		$top = $ajaxcart_settings['wc_ajax_cart_top'];
		if(!$top){
			$top = 40;
		}
		$json['top'] = $top;


		if(get_option('woocommerce_cart_redirect_after_add') == 'yes'){
			if(class_exists('NBT_Solutions_One_Step_Checkout')){
				$json['url_checkout'] = wc_get_checkout_url();
			}else{
				$json['url_checkout'] = wc_get_cart_url();
			}
		}
		echo wp_json_encode($json, TRUE);
		wp_die();
	}

	function embed_style(){
		if( !defined('PREFIX_NBT_SOL') ){
			wp_enqueue_style( 'ntb-fonts', AJAX_CART_URL . 'assets/css/ntb-fonts.css',false,'1.1','all');
		}
		
		wp_enqueue_style( 'mCustomScrollbar', AJAX_CART_URL . 'assets/css/jquery.mCustomScrollbar.min.css',false,'1.1','all');
		wp_enqueue_style( 'jquery.growl', AJAX_CART_URL . 'assets/css/jquery.growl.css',false,'1.1','all');
		if( !defined('PREFIX_NBT_SOL') ){
			wp_enqueue_style( 'frontends', AJAX_CART_URL . 'assets/css/frontend.css',false, false,'all');
		}

		wp_enqueue_script( 'jquery.mCustomScrollbar', AJAX_CART_URL . 'assets/js/jquery.mCustomScrollbar.min.js', null, null, true );
		//wp_enqueue_script( 'jquery.growl', AJAX_CART_URL . 'assets/js/jquery.growl.js', null, null, true );
		if( !defined('PREFIX_NBT_SOL') ){
			wp_enqueue_script( 'ajax-cart', AJAX_CART_URL . 'assets/js/frontend.js?v='.time(), null, null, true );
		}

	}
}
new NBT_WooCommerce_AjaxCart_Frontend();