<?php

namespace BricksUltimate\ElementControls;

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

use BricksUltimate\Helpers;

class AjaxPopup {
	public $syncELements;

	public function __construct() {
		$this->syncELements = [ 'button', 'div', 'svg', 'heading', 'image', 'product-add-to-cart', 'bu-atc', 'bu-atci' ];
		
		foreach( $this->syncELements as $element ) {
			add_filter( "bricks/elements/$element/control_groups", array( $this, 'add_ajax_popup_control_groups' ) );
			add_filter( "bricks/elements/$element/controls", [ $this, 'add_ajax_popup_controls' ] );
		}

		add_action( 'bricks/frontend/before_render_data', [ $this, 'element_before_render_data' ], 10, 2 );

		add_action( 'wp_ajax_bu_ajax_popup', [ $this, 'bu_fetch_popup_data' ] );
		add_action( 'wp_ajax_nopriv_bu_ajax_popup', [ $this, 'bu_fetch_popup_data' ] );
	}

	/**
	 * Adds ajax popup groups under style tab
	 * 
	 * @param array $control_groups
	 * @return array $control_groups
	 */
	public function add_ajax_popup_control_groups( $control_groups ) {
		$control_groups['buapgrp'] = [
				'tab'      => 'style',
				'title'    => esc_html__( 'Ajax Popup', 'bricksultimate' ),
		];

		return $control_groups;
	}

	/**
	 * Adds ajax popup controls
	 * 
	 * @param array $controls
	 * @return array $controls
	 */
	public function add_ajax_popup_controls( $controls ) {
		$controls['enabledAjaxPopup'] = [
			'tab' 		=> 'content',
			'group' 	=> 'buapgrp',
			'type'      => 'checkbox',
			'label'     => esc_html__( 'Enable the AJAX action', 'bricksultimate' ),
			'reset' 	=> true,
		];

		$controls['fetchType'] = [
			'tab' 		=> 'content',
			'group' 	=> 'buapgrp',
			'type'      => 'select',
			'options' 	=> [ 
				'post' => __('Post Query'), 
				'term' => __('Term Query'), 
				'static' => __('Static content') 
			],
			'default' 	=> 'post',
			'label'     => esc_html__( 'Query Loop Builder Type', 'bricksajaxpopup' ),
			'required' 	=> ['enabledAjaxPopup', '=', true]
		];

		$controls['fetchPosts'] = [
			'tab' 		=> 'content',
			'group' 	=> 'buapgrp',
			'type'      => 'text',
			'label'     => esc_html__( 'Fetching Post ID', 'bricksajaxpopup' ),
			'required' 	=> [ ['fetchType', '=', 'post'], ['enabledAjaxPopup', '=', true] ]
		];
		
		$controls['fetchTerm'] = [
			'tab' 		=> 'content',
			'group' 	=> 'buapgrp',
			'type'      => 'text',
			'label'     => esc_html__( 'Fetching Term ID', 'bricksajaxpopup' ),
			'required' 	=> [ ['fetchType', '=', 'term'], ['enabledAjaxPopup', '=', true] ]
		];

		$controls['loaderIcon'] = [
			'tab' 		=> 'content',
			'group' 	=> 'buapgrp',
			'type'      => 'text',
			'label'     => esc_html__( 'Loading Icon(gif)', 'bricksultimate' ),
			'info' 		=> esc_html__( 'Enter animated gif URL', 'bricksultimate' ),
			'required' 	=> ['enabledAjaxPopup', '=', true]
		];

		return $controls;
	}

	public function element_before_render_data( $elements, $area ) {
		if( bricks_is_builder() || bricks_is_builder_iframe() )
			return;
		
		foreach ( $elements as $element ) {
			$settings = $element['settings'];

			if( in_array( $element['name'], $this->syncELements ) && ! empty( $settings['enabledAjaxPopup'] ) ) {
				if( class_exists('WooCommerce') ) {
					wp_enqueue_script('wc-add-to-cart-variation');
					wp_enqueue_script('wc-single-product');
					if( ! empty( \BricksUltimate\Plugin::$bu_settings['swatches'] ) && \BricksUltimate\Plugin::$bu_settings['swatches'] == 'enabled' ) {
						wp_enqueue_style( 'bu-swatches' );
						wp_enqueue_script( 'bu-swatches' );
					}
				}
				
				wp_enqueue_script( 'bu-ajax-popup' );
				wp_localize_script( 
					'bu-ajax-popup', 
					'APOPUP', 
					array( 
						'nonce' => wp_create_nonce( "bu-ajax-popup" ), 
						'loader' => Helpers::get_value( $settings, 'loaderIcon', get_option( 'siteurl') . '/wp-includes/js/tinymce/skins/lightgray/img/loader.gif' ) 
					) 
				);
			}
		}
	}

	public function bu_fetch_popup_data() {
		check_ajax_referer( 'bu-ajax-popup', 'security' );

		global $postId, $termId, $orderID;

		$order = false;
		$popup_id = (int) $_POST['popup_id'];
		$postId = isset( $_POST['post_id'] ) ? (int) $_POST['post_id'] : false;
		$termId = isset( $_POST['term_id'] ) ? (int) $_POST['term_id'] : false;

		if( class_exists('WooCommerce') ) {
			$order = \wc_get_order( $postId );
				
			if ( $order ) {
				$GLOBALS['orderID'] = $postId;
				$GLOBALS['tplOrder'] = $order;
			}
		}

		if( $postId && $postId > 0 && $order === false ) {
			add_filter( 'bricks/posts/query_vars', [ $this, 'filter_post_query' ], 10, 3 );
		}
		
		if( $termId && $termId > 0 && $order === false ) {
			add_filter( 'bricks/terms/query_vars', [ $this, 'filter_term_query' ], 10, 3 );
		}

		\Bricks\Database::$page_data['preview_or_post_id'] = $popup_id;
		
		$elements = \Bricks\Database::get_data( $popup_id );

		if ( empty( $elements ) ) {
			$data = array(
				'error' => __( 'Popup has no elements.', 'bricksultimate' ),
			);
			
			wp_send_json_success($data);
		}

		$popup_content = \Bricks\Frontend::render_data( $elements, 'popup' );

		if ( empty( $popup_content ) ) {
			$data = array(
				'error' => __( 'Popup has no content.', 'bricksultimate' ),
			);
			
			wp_send_json_success($data);
		}

		if( $postId && $postId > 0 && $order === false ) {
			remove_filter( 'bricks/posts/query_vars', [ $this, 'filter_post_query' ], 10, 3 );
		}
		
		if( $termId && $termId > 0 && $order === false ) {
			remove_filter( 'bricks/terms/query_vars', [ $this, 'filter_term_query' ], 10, 3 );
		}

		wp_send_json_success( ['content' => $popup_content, 'error' => false ] );
	}

	public function filter_term_query( $query_vars, $settings, $element_id ) {
		global $termId;
		
		if( $termId ) { 
			$query_vars['include'] = $termId;
		}

		return $query_vars;
	}
	
	public function filter_post_query( $query_vars, $settings, $element_id ) {
		global $postId;

		if( $postId ) { 
			$query_vars['p'] = $postId; 
		}

		return $query_vars;
	}
}