<?php
/**
 * This class register the special meta for the cart
 *
 * @package YITH\DynamicPricing\And\Discounts\Classes
 * @since 4.3.0
 */

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

use Automattic\WooCommerce\StoreApi\Schemas\V1\CartSchema;

class YWDPD_WC_Blocks_Register {

	public function __construct() {
		add_action( 'woocommerce_blocks_loaded', array( $this, 'register_endpoint' ) );
	}

	/**
	 * Register the endpoint
	 *
	 * @return void
	 */
	public function register_endpoint() {
		woocommerce_store_api_register_endpoint_data(
			array(
				'endpoint'        => CartSchema::IDENTIFIER,
				'namespace'       => 'yith_dynamic_wc_block_manager',
				'data_callback'   => array( $this, 'my_data_callback' ),
				'schema_callback' => array( $this, 'my_schema_callback' ),
				'schema_type'     => ARRAY_A,
			)
		);
	}

	/**
	 * Return the data
	 *
	 * @return string[]
	 */
	public function my_data_callback() {
		$cart_rule_manager = ywdpd_dynamic_pricing_discounts()->get_cart_rules_manager();
		$notices = $cart_rule_manager->get_free_shipping_notice();
		return array(
			'ywdpd_coupon_label'   => $cart_rule_manager->get_coupon_code_details(),
			'ywdpd_coupon_code'    => $cart_rule_manager->get_coupon_code(),
			'ywdpd_can_add_coupon' =>  $cart_rule_manager->can_add_coupon()  ? 'yes' : 'no',
			'ywdpd_free_shipping_notices' => $notices,
			'ywdpd_total_discount_message' => YITH_WC_Dynamic_Options::show_discount_info_in_cart() ? yith_ywdpd_get_total_discount_message() : ''
		);
	}

	/**
	 * The schema callback
	 *
	 * @return array[]
	 */
	public function my_schema_callback() {
		return array(
			'ywdpd_coupon_label' => array(
				'description' => _x( 'The coupon label applied in cart', 'The coupon label', 'ywdpd' ),
				'type'        => 'string',
				'readonly'    => true,
			),
			'ywdpd_coupon_code'  => array(
				'description' => _x( 'The coupon code applied in cart', 'The coupon code', 'ywdpd' ),
				'type'        => 'string',
				'readonly'    => true,
			),
			'ywdpd_can_add_coupon'  => array(
				'description' => _x( 'Can apply or not the coupon', 'The coupon check', 'ywdpd' ),
				'type'        => 'string',
				'readonly'    => true,
			)
		);
	}
}

new YWDPD_WC_Blocks_Register();