<?php
use Elementor\Controls_Manager;

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

class ECAFE_Event_Tracker {
	private static $loadscript = false;

	public function __construct() {

		add_action( 'elementor/element/common/_section_style/after_section_end', array( $this, 'add_et_controls' ), 10, 2 );

		add_action( 'elementor/frontend/widget/before_render', array( $this, 'ec_et_before_render' ), 10 );
		add_action( 'elementor/frontend/section/before_render', array( $this, 'ec_et_before_render' ), 10 );
		add_action( 'elementor/frontend/before_render', array( $this, 'ec_et_before_render' ), 10, 1 );
	}

	public function ec_eventtracker_enqueue_scripts() {

		if ( ! wp_script_is( 'ecafe-event-tracker', 'enqueued' ) ) {
			wp_enqueue_script( 'ecafe-event-tracker' );
		}
	}

	public function add_et_controls( $element, $section_id ) {

		$element->start_controls_section(
			'ecafe_event_tracker',
			[
				'label' => esc_html__( 'EC Event Tracker', 'essential-classy-addons-for-elementor' ),
				'tab'   => Controls_Manager::TAB_ADVANCED,
			]
		);
		$element->add_control(
			'ec_enable',
			array(
				'label'        => esc_html__( 'Tracking', 'essential-classy-addons-for-elementor' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Enable', 'essential-classy-addons-for-elementor' ),
				'label_off'    => esc_html__( 'Disable', 'essential-classy-addons-for-elementor' ),
				'return_value' => 'yes',
			)
		);
		$element->add_control(
			'ec_preset',
			array(
				'label'       => esc_html__( 'Quick Setup', 'essential-classy-addons-for-elementor' ),
				'type'        => Controls_Manager::SELECT,
				'default'     => '',
				'label_block' => true,
				'options'     => array(
					''  => esc_html__( 'Custom', 'essential-classy-addons-for-elementor' ),
					// BASIC (Elementor)
					'cta' => esc_html__( 'CTA Click (Button)', 'essential-classy-addons-for-elementor' ),
					'link_click' => esc_html__( 'Link Click', 'essential-classy-addons-for-elementor' ),
					'form_submit' => esc_html__( 'Form Submit', 'essential-classy-addons-for-elementor' ),
					'popup_open' => esc_html__( 'Popup Open', 'essential-classy-addons-for-elementor' ),
					'popup_close' => esc_html__( 'Popup Close', 'essential-classy-addons-for-elementor' ),
					'video_play' => esc_html__( 'Video Play', 'essential-classy-addons-for-elementor' ),
					'image_click' => esc_html__( 'Image Click', 'essential-classy-addons-for-elementor' ),
					// LEADS
					'lead' => esc_html__( 'Lead Generation', 'essential-classy-addons-for-elementor' ),
					'newsletter' => esc_html__( 'Newsletter Signup', 'essential-classy-addons-for-elementor' ),
					// ENGAGEMENT
					'scroll_50' => esc_html__( 'Scroll 50%', 'essential-classy-addons-for-elementor' ),
					'scroll_90' => esc_html__( 'Scroll 90%', 'essential-classy-addons-for-elementor' ),
					'time_30s' => esc_html__( 'Time on Page (30s)', 'essential-classy-addons-for-elementor' ),
					// WOOCOMMERCE
					'add_to_cart' => esc_html__( 'Add To Cart', 'essential-classy-addons-for-elementor' ),
					'view_product' => esc_html__( 'View Product', 'essential-classy-addons-for-elementor' ),
					'checkout' => esc_html__( 'Checkout Started', 'essential-classy-addons-for-elementor' ),
					'purchase' => esc_html__( 'Purchase Complete', 'essential-classy-addons-for-elementor' ),
				),
				'description'  => __( 'One-click setup for common tracking..', 'essential-classy-addons-for-elementor' ),
				'condition'   => array(
					'ec_enable' => 'yes',
				),
			)
		);
		$element->add_control(
			'ec_goal',
			array(
				'label'       => esc_html__( 'What do you want to track?', 'essential-classy-addons-for-elementor' ),
				'type'        => Controls_Manager::SELECT,
				'default'     => 'click',
				'label_block' => true,
				'options'     => array(
					'click'  => esc_html__( 'Button Click', 'essential-classy-addons-for-elementor' ),
					'view'  => esc_html__( 'Page View', 'essential-classy-addons-for-elementor' ),
					'form'  => esc_html__( 'Form Submit', 'essential-classy-addons-for-elementor' ),
					'purchase'  => esc_html__( 'Purchase', 'essential-classy-addons-for-elementor' ),
					'custom'  => esc_html__( 'Custom', 'essential-classy-addons-for-elementor' ),
				),
				'condition'   => array(
					'ec_enable' => 'yes',
					'ec_preset' => '',
				),
			)
		);
		$element->add_control(
			'ec_event',
			array(
				'label'       => esc_html__( 'Event Name', 'essential-classy-addons-for-elementor' ),
				'type'        => Controls_Manager::SELECT,
				'default'     => 'generate_lead',
				'label_block' => true,
				'options'     => array(
					'view_item'  => esc_html__( 'View Item', 'essential-classy-addons-for-elementor' ),
					'add_to_cart'  => esc_html__( 'Add To Cart', 'essential-classy-addons-for-elementor' ),
					'begin_checkout'  => esc_html__( 'Begin Checkout', 'essential-classy-addons-for-elementor' ),
					'purchase'  => esc_html__( 'Purchase', 'essential-classy-addons-for-elementor' ),
					'generate_lead'  => esc_html__( 'Generate Lead', 'essential-classy-addons-for-elementor' ),
				),
				'condition'   => array(
					'ec_enable' => 'yes',
					'ec_preset' => '',
					'ec_goal!' => 'custom',
				),
			)
		);
		$element->add_control(
			'ec_event_custom',
			array(
				'label'       => esc_html__( 'Custom Event Name', 'essential-classy-addons-for-elementor' ),
				'type'        => Controls_Manager::TEXT,
				'label_block' => true,
				'dynamic' => ['active' => true],
				'description' => __( 'Enter Event Name', 'essential-classy-addons-for-elementor' ),
				'condition'   => array(
					'ec_enable' => 'yes',
				'ec_goal' => 'custom',
				),
			)
		);
		$element->add_control(
			'ec_platforms',
			array(
				'label'       => esc_html__( 'Send To', 'essential-classy-addons-for-elementor' ),
				'type'        => Controls_Manager::SELECT2,
				'default' => [ 'ga4' ],
				'multiple' => true,
				'label_block' => true,
				'options'     => array(
					'ga4'  => esc_html__( 'Google Analytics (GA4)', 'essential-classy-addons-for-elementor' ),
					'fb'  => esc_html__( 'Facebook Pixel', 'essential-classy-addons-for-elementor' ),
					'ads'  => esc_html__( 'Google Ads', 'essential-classy-addons-for-elementor' ),
				),
				'condition'   => array(
					'ec_enable' => 'yes',
				),
			)
		);
		$element->add_control(
			'ec_trigger',
			array(
				'label'       => esc_html__( 'Trigger', 'essential-classy-addons-for-elementor' ),
				'type'        => Controls_Manager::CHOOSE,
				'options'     => array(
					'click'   => array(
						'title' => esc_html__( 'Click', 'essential-classy-addons-for-elementor' ),
						'icon'  => 'eicon-click',
					),
					'scroll' => array(
						'title' => esc_html__( 'Scroll', 'essential-classy-addons-for-elementor' ),
						'icon'  => 'eicon-scroll',
					),
					'delay'  => array(
						'title' => esc_html__( 'Delay', 'essential-classy-addons-for-elementor' ),
						'icon'  => 'eicon-clock',
					),
					'exit'  => array(
						'title' => esc_html__( 'Exit', 'essential-classy-addons-for-elementor' ),
						'icon'  => 'eicon-exit',
					),
				),
				'default'     => 'click',
				'label_block' => false,
				'condition'   => array(
					'ec_enable' => 'yes',
					'ec_goal!' => 'view',
					'ec_preset' => '',
				),
			)
		);
		$element->add_control(
			'ec_scroll',
			array(
				'label'     => __( 'Scroll %', 'essential-classy-addons-for-elementor' ),
				'type'      => Controls_Manager::NUMBER,
				'min'       => 1,
				'max'       => 100,
				'step'      => 5,
				'default'   => 50,
				'condition' => array(
					'ec_enable' => 'yes',
					'ec_trigger' => 'scroll',
				),
			)
		);
		$element->add_control(
			'ec_delay',
			array(
				'label'     => __( 'Delay (ms)', 'essential-classy-addons-for-elementor' ),
				'type'      => Controls_Manager::NUMBER,
				'default'   => 3000,
				'condition' => array(
					'ec_enable' => 'yes',
					'ec_trigger' => 'delay',
				),
			)
		);

		/* ADVANCED */
		$repeater = new \Elementor\Repeater();

		$repeater->add_control(
			'key',
			array(
				'label'       => esc_html__( 'Key', 'essential-classy-addons-for-elementor' ),
				'type'        => Controls_Manager::TEXT,
				'dynamic' => ['active' => true],
			)
		);
		$repeater->add_control(
			'value',
			array(
				'label'       => esc_html__( 'Value', 'essential-classy-addons-for-elementor' ),
				'type'        => Controls_Manager::TEXT,
				'dynamic' => ['active' => true],
			)
		);
		$element->add_control(
			'ec_params',
			array(
				'label'       => esc_html__( 'Advanced Parameters', 'essential-classy-addons-for-elementor' ),
				'type'        => Controls_Manager::REPEATER,
				'condition'   => array(
					'ec_enable' => 'yes',
					'ec_preset' => '',
				),
				'fields'      => $repeater->get_controls(),
				'title_field' => '{{key}}',
				'separator' => 'before'
			)
		);
		$element->add_control(
			'ec_debug',
			array(
				'label'        => esc_html__( 'Debug Mode', 'essential-classy-addons-for-elementor' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Enable', 'essential-classy-addons-for-elementor' ),
				'label_off'    => esc_html__( 'Disable', 'essential-classy-addons-for-elementor' ),
				'return_value' => 'yes',
				'description'  => __( 'Check on Frontend Console.', 'essential-classy-addons-for-elementor' ),
				'separator' => 'before',
				'condition'   => array(
					'ec_enable' => 'yes',
				),
			)
		);
		$element->end_controls_section();
	}

	public function ec_et_before_render( $element ) {
		$settings = $element->get_settings_for_display();
		if ( ! isset($settings['ec_enable']) || $settings['ec_enable'] !== 'yes' ) return;

		if ( ! self::$loadscript ) {
			$this->ec_eventtracker_enqueue_scripts();
			self::$loadscript = true;
		}
		
		$event = '';
		$params = [];

		if (!empty($settings['ec_params'])) {
			foreach ($settings['ec_params'] as $param) {
				$params[] = [
					'key' => sanitize_text_field($param['key']),
					'value' => sanitize_text_field($param['value']),
				];
			}
		}

		$data = [
			'platforms' => !empty($settings['ec_platforms']) ? $settings['ec_platforms'] : ['ga4'],			
			'params' => $params,
			'debug' => !empty($settings['ec_debug']),
		];

		$preset = !empty($settings['ec_preset']) ? $settings['ec_preset'] : '';

		if ($preset) {

			switch ($preset) {

				// CTA
				case 'cta':
				case 'link_click':
				case 'image_click':
					$event = 'select_content';
					$data['trigger'] = 'click';
				break;
			
				// FORM / LEAD
				case 'lead':
				case 'form_submit':
				case 'newsletter':
					$event = 'generate_lead';
					$data['trigger'] = 'form';
				break;
				
				// VIDEO
				case 'video_play':
					$event = 'video_start';
					$data['trigger'] = 'click';
				break;
			
				// POPUP
				case 'popup_open':
					$event = 'view_item';
					$data['trigger'] = 'delay';
					$data['delay'] = 500;
				break;
			
				case 'popup_close':
					$event = 'close';
					$data['trigger'] = 'exit';
				break;
			
				// SCROLL
				case 'scroll_50':
					$event = 'scroll';
					$data['trigger'] = 'scroll';
					$data['scroll'] = 50;
				break;
			
				case 'scroll_90':
					$event = 'scroll';
					$data['trigger'] = 'scroll';
					$data['scroll'] = 90;
				break;
			
				// TIME
				case 'time_30s':
					$event = 'engagement_time';
					$data['trigger'] = 'delay';
					$data['delay'] = 30000;
				break;
			
				// WOOCOMMERCE
				case 'add_to_cart':
					$event = 'add_to_cart';
					$data['trigger'] = 'click';
				break;
			
				case 'view_product':
					$event = 'view_item';
					$data['trigger'] = 'view';
				break;
			
				case 'checkout':
					$event = 'begin_checkout';
					$data['trigger'] = 'click';
				break;
			
				case 'purchase':
					$event = 'purchase';
					$data['trigger'] = 'click';
				break;
			}

		} else {
			if ($settings['ec_goal'] === 'custom') {
				$event = !empty($settings['ec_event_custom']) ? $settings['ec_event_custom'] : 'custom_event';
			} else {
				$event = !empty($settings['ec_event']) ? $settings['ec_event'] : 'generate_lead';
			}
		}
		$data['name'] = sanitize_text_field($event ?: 'custom_event');
		$data['trigger'] = isset($data['trigger']) 
			? $data['trigger'] 
			: (!empty($settings['ec_trigger']) ? $settings['ec_trigger'] : 'click');

		$data['scroll'] = isset($data['scroll']) 
			? $data['scroll'] 
			: (!empty($settings['ec_scroll']) ? intval($settings['ec_scroll']) : 0);

		$data['delay'] = isset($data['delay']) 
			? $data['delay'] 
			: (!empty($settings['ec_delay']) ? intval($settings['ec_delay']) : 0);

		// Auto parameters for presets
		if ($preset === 'cta') {
			$data['params'][] = [
				'key' => 'button_text',
				'value' => sanitize_text_field($element->get_settings('text') ?: 'cta_click')
			];
		}

		if ($preset === 'lead') {
			$data['params'][] = [
				'key' => 'form_name',
				'value' => 'elementor_form'
			];
		}

		$element->add_render_attribute('_wrapper', [
			'class' => 'ecafe-event-track',
			'data-ec' => wp_json_encode($data)
		]);
	}
}

new ECAFE_Event_Tracker();