<?php
namespace BricksUltimate\Elements;

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

use BricksUltimate\{Plugin, Helpers};

class WooMiniCart extends \Bricks\Element {
	public $category 	= 'cart';
	public $name 		= 'bu-mini-cart';
	public $icon 		= 'ti-layout-cta-left';
	public $nestable 	= true;

	// Return localized element label
	public function get_label() {
		return esc_html__( '(BU)Mini Cart Builder', 'bricksultimate' );
	}

	// Set builder controls
	public function set_controls() {
		$this->controls['emptyCartSelector'] = [
			'tab'    => 'content',
			'type'   => 'text',
			'label'  => esc_html__( 'Empty cart message selector', 'bricksultimate' ),
			'placeholder'  => esc_html__( 'Enter empty cart message selector', 'bricksultimate' )
		];
	}

	// 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-minicart', Helpers::get_asset_url('css') . 'minicart.min.css', [], filemtime(Helpers::get_asset_path('css') . 'minicart.min.css') );
		} else {*/
			wp_enqueue_script( 'bu-minicart', Helpers::get_asset_url('js') . 'minicart.min.js', ['wc-cart-fragments'], filemtime(Helpers::get_asset_path('js') . 'minicart.min.js'), true );

			wp_enqueue_script( 
				'bu-item-qty', 
				Helpers::get_asset_url('js') . 'buitemqty.min.js', 
				['wc-cart-fragments'], 
				filemtime(Helpers::get_asset_path('js') . 'buitemqty.min.js' ),
				true
			);
		//}
	}

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

		add_filter( 'bricks/element/render_attributes', [ '\BricksUltimate\Helpers', 'bu_add_attributes' ], 1000, 3 );
		add_filter( 'woocommerce_product_variation_title_include_attributes', '__return_false' );

		$emptySelector = Helpers::get_value( $this->settings, 'emptyCartSelector', false );
		if( $emptySelector )
			$this->set_attribute( '_root', 'data-empty-cart', $emptySelector );

		echo "<{$this->tag} {$this->render_attributes("_root")}>";
		echo "<{$this->tag} class=\"bu-minicart-{$this->id} bu-minicart-wrap\">";
		echo \Bricks\Frontend::render_children( $this );
		echo "</{$this->tag}>";
		echo "</{$this->tag}>";

		remove_filter( 'bricks/element/render_attributes', [ '\BricksUltimate\Helpers', 'bu_add_attributes' ], 1000, 3 );
		remove_filter( 'woocommerce_product_variation_title_include_attributes', '__return_false' );
	}

	public static function render_builder() {
	?>
		<script type="text/x-template" id="tmpl-bricks-element-bu-mini-cart">
			<component :is="tag" :data-post-id="bricks.postId">
				<bricks-nestable :element="element" />
			</component>
		</script>
		<?php
	}
}