<?php
/**
 * This class manage the compatibility with Cart and Checkout block
 *
 * @package YITH\DynamicPricing\And\Discounts\Classes
 * @since 4.3.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class YWDPD_WC_Blocks {
	use YWDPD_Singleton_Trait;


	protected function __construct() {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ), 20 );
		add_filter( 'woocommerce_get_item_data', array( $this, 'woocommerce_get_item_data' ), 10, 2 );
		add_filter( 'ywdpd_reload_after_ajax_add_to_cart', array( $this, 'force_reload_page'), 99);
	}

	/**
	 * Enqueue styles and scripts
	 *
	 * @return void
	 */
	public function enqueue_scripts() {
		global $post;

		if ( has_block( 'woocommerce/checkout', $post ) || has_block( 'woocommerce/cart', $post ) ) {
			$deps = include YITH_YWDPD_DIR . 'assets/js/build/wc-blocks/badge-discount/index.asset.php';

			wp_enqueue_script(
				'ywdpd-badge-discount-block',
				YITH_YWDPD_ASSETS_URL . '/js/build/wc-blocks/badge-discount/index.js',
				$deps['dependencies'],
				$deps['version'],
				true
			);

			$deps = include YITH_YWDPD_DIR . 'assets/js/build/wc-blocks/coupon-filter/index.asset.php';

			wp_enqueue_script(
				'ywdpd-coupon-manager-block',
				YITH_YWDPD_ASSETS_URL . '/js/build/wc-blocks/coupon-filter/index.js',
				$deps['dependencies'],
				$deps['version'],
				true
			);

			$args = array(
				'action' => 'update_cart_after_payment_method',
				'nonce' => wp_create_nonce( 'update_cart_after_payment_method' ),
				'ajaxURL' => admin_url( 'admin-ajax.php', is_ssl() ? 'https' : 'http' )
			);
			wp_localize_script( 'ywdpd-coupon-manager-block', 'ywdpd_ajax_args', $args );


			$deps = include YITH_YWDPD_DIR . 'assets/js/build/wc-blocks/free-shipping-banner/index.asset.php';

			wp_enqueue_script(
				'ywdpd-free-shipping-banner-block',
				YITH_YWDPD_ASSETS_URL . '/js/build/wc-blocks/free-shipping-banner/index.js',
				$deps['dependencies'],
				$deps['version'],
				true
			);
		}
	}

	/**
	 * Add the custom info about sales discount
	 *
	 * @param array $data The data.
	 * @param array $cart_item The cart item.
	 *
	 * @return array
	 */
	public function woocommerce_get_item_data( $data, $cart_item ) {
		if ( isset( $cart_item['ywdpd_discounts']['applied_discounts'] ) ) {
			$discounts = $cart_item['ywdpd_discounts']['applied_discounts'];
			$names     = array();
			foreach ( $discounts as $discount ) {
				$rule = ywdpd_get_rule( $discount['set_id'] );
				$names[]  = $rule->get_name();
			}

			$data[] = array_merge(
				array(
					'name'   => 'ywdpd-rules-applied',
					'hidden' => true
				),
				array(
					'value' => implode( ',', $names )
				)
			);
		}

		return $data;
	}

	/**
	 * Change the script param to reload a page
	 *
	 * @param string $reload The default value.
	 *
	 * @return string
	 */
	public function force_reload_page( $reload ){
		global $post;
		if( has_block( 'woocommerce/cart', $post)){
			$reload = 'yes';
		}
		return $reload;
	}
}