<?php
namespace BricksUltimate\Elements;

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

use BricksUltimate\{Helpers, Plugin, WooCommerce};

class WooReviewOrder extends \Bricks\Element_Container {
	public $category = 'checkout';
	public $name 	= 'bu-review-order';
	public $icon 	= 'ti-layout-width-default';
	public $nestable = true;

	// Return localized element label
	public function get_label() {
		return esc_html__( '(BU)Content Updater', 'bricksultimate' );
	}

	// Set builder controls
	public function set_controls() {

		parent::set_controls();

		$this->controls['eventSep'] = [
			'type'        => 'separator',
		];

		$this->controls['eventType'] = [
			'type'        => 'select',
			'label'       => esc_html__( 'Events type', 'bricks' ),
			'options'     => [
				'wc' => 'WC Events',
				'js' => 'Dispatch Event'
			],
			'multiple'    => false
		];

		$this->controls['eventInfo'] = [
			'type' 		=> 'info',
			'content' 	=> esc_html__( 'By default, it is triggered by wc_fragment_refresh event.', 'bricks' ),
		];

		$this->controls['trigger'] = [
			'type'        => 'select',
			'label'       => esc_html__( 'Trigger on', 'bricks' ),
			'options'     => [
				'adding_to_cart' 				=> 'adding_to_cart',
				'added_to_cart' 				=> 'added_to_cart',
				'removed_from_cart' 			=> 'removed_from_cart',
				'wc_fragment_refresh' 			=> 'wc_fragment_refresh',
				'wc_fragments_loaded' 			=> 'wc_fragments_loaded',
				'wc_fragments_refreshed' 		=> 'wc_fragments_refreshed',
				'wc_cart_emptied' 				=> 'wc_cart_emptied',
				'update_checkout' 				=> 'update_checkout',
				'updated_wc_div' 				=> 'updated_wc_div',
				'updated_cart_totals' 			=> 'updated_cart_totals',
				'country_to_state_changed' 		=> 'country_to_state_changed',
				'updated_shipping_method' 		=> 'updated_shipping_method',
				'applied_coupon' 				=> 'applied_coupon',
				'removed_coupon' 				=> 'removed_coupon',
				'applied_coupon_in_checkout' 	=> 'applied_coupon_in_checkout',
				'removed_coupon_in_checkout' 	=> 'removed_coupon_in_checkout',
				'init_checkout' 				=> 'init_checkout',
				'payment_method_selected' 		=> 'payment_method_selected'
			],
			'multiple'  => true,
			'required' 	=> [ 'eventType', '=', 'wc' ]
		];

		$this->controls['dispatchEvents'] = [
			'type'        => 'select',
			'label'       => esc_html__( 'Custom eventlistener', 'bricks' ),
			'options'     => [
				'bu_ocp_open' 					=> 'bu_ocp_open',
				'bu_ocp_close' 					=> 'bu_ocp_close',
				'bu/popup/ajaxend' 				=> 'bu/popup/ajaxend',
				'buAjaxSearchComplete' 			=> 'buAjaxSearchComplete',
				'buAfterGridTable' 				=> 'buAfterGridTable',
				'buwoo_update_wishlist' 		=> 'buwoo_update_wishlist',
				'buwoo_added_to_wishlist' 		=> 'buwoo_added_to_wishlist',
				'buwoo_removed_from_wishlist' 	=> 'buwoo_removed_from_wishlist',
				'buwoo_update_mini_wishlist' 	=> 'buwoo_update_mini_wishlist',
				'bu_update_compare' 			=> 'bu_update_compare',
				'bu_update_mini_compare' 		=> 'bu_update_mini_compare',
				'bu_update_cart_quantity' 		=> 'bu_update_cart_quantity',
				'bricks/tabs/changed' 			=> 'bricks/tabs/changed',
				'bricks/ajax/end' 				=> 'bricks/ajax/end',
				'bricks/ajax/popup/loaded' 		=> 'bricks/ajax/popup/loaded',
				'bricks/ajax/pagination/completed' 	=> 'bricks/ajax/pagination/completed',
				'bricks/ajax/load_page/completed' 	=> 'bricks/ajax/load_page/completed',
				'bricks/ajax/query_result/displayed' => 'bricks/ajax/query_result/displayed',
			],
			'multiple'  => true,
			'required' 	=> [ 'eventType', '=', 'js' ]
		];

		$this->controls['spinnerSep'] = [
			'label' => esc_html__( 'Loading Animation', 'bricksultimate' ),
			'type' 	=> 'separator'
		];

		$this->controls['showSpinner'] = [
			'label' => esc_html__( 'Enable loading animation', 'bricksultimate' ),
			'type' 	=> 'checkbox'
		];

		$this->controls['spinnerColor'] = [
			'group' => 'spinner',
			'type' 	=> 'checkbox',
			'label' => esc_html__('Color', 'bricks'),
			'css' 	=> [
				[
					'property' 	=> '--loading-color'
				]
			]
		];

		$this->controls['spinnerSize'] = [
			'group' => 'spinner',
			'type' 	=> 'number',
			'label' => esc_html__('Size', 'bricks'),
			'units' => true,
			'css' 	=> [
				[
					'property' 	=> '--loading-size'
				]
			]
		];
	}

	// Enqueue element styles and scripts
	public function enqueue_scripts() {
		/*if( bricks_is_builder() || bricks_is_builder_iframe() || bricks_is_builder_call() ){
			wp_enqueue_style( 'bu-checkout', Helpers::get_asset_url('css') . 'checkout.min.css', [], filemtime(Helpers::get_asset_path('css') . 'checkout.min.css') );
		} else {*/
			wp_enqueue_script( 'bu-checkout', Helpers::get_asset_url('js') . 'checkout.min.js', [], filemtime(Helpers::get_asset_path('js') . 'checkout.min.js') );
		//}
	}

	public function add_filters() {
		if( ! Helpers::isBricksBuilderActive() || ! bricks_is_builder() ) {
			add_filter('woocommerce_update_order_review_fragments', [$this,'update_order_review_fragments'], 99 );
		}
	}

	public function update_order_review_fragments( $fragments ) {
		if( empty( Plugin::$bu_settings['wccntrsf'] ) )
			return $fragments;
		
		foreach( (array) Plugin::$bu_settings['wccntrsf'] as $el ) {
			$tpl_post_id = explode("|", $el );
			ob_start();
			WooCommerce::buwoo_content_updater( $el );
			$fragments['.buco-' . $tpl_post_id[0]] = ob_get_clean();
		}

		return $fragments;
	}

	public function render() {
		if( ! \BricksUltimate\Helpers::isBricksBuilderEditor() && ! \wp_doing_ajax() ) {
			$buSettings = get_option('bu_settings') ?? [];
			$templates = \Bricks\Database::$active_templates;
			$buSettings['wccntrsf'][$this->id] = $this->id . '|' . $this->post_id . '|' . $templates['header'];
			update_option( 'bu_settings', $buSettings );
		}

		$triggerlib = Helpers::get_value( $this->settings, 'eventType', false);
		if( $triggerlib ) {
			$data = [
				'triggerlib' 	=> $triggerlib,
				'prefix' 		=> is_checkout() ? 'buco-' : 'bu-',
				'events' 		=> ($triggerlib == 'wc') ? Helpers::get_value( $this->settings, 'trigger') : Helpers::get_value( $this->settings, 'dispatchEvents')
			];
			$this->set_attribute( '_root', 'data-trigger-events', wp_json_encode( $data ) );
		}

		if( ! empty( $this->settings['showSpinner'] ) ) {
			$this->set_attribute( '_root', 'class', ['show-spinner'] );
		}

		//* Bugs: conflicting with the cart counter and cart content elements
		if( is_checkout() )
			$this->set_attribute( '_root', 'class', ['buco-' . $this->id ] );
		else 
			$this->set_attribute( '_root', 'class', ['bu-' . $this->id ] );

		parent::render();
	}
}