<?php
namespace Cool_FormKit_Pro\Widgets\HelloPlusAddons;

use HelloPlus\Modules\Forms\Classes\Action_Base;
use Elementor\Controls_Manager;

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

/**
 * Class HelloPlus_Conditional_Whatsapp_Redirect
 */
class HelloPlus_Conditional_Whatsapp_Redirect extends Action_Base {

	public function get_name(): string {
		return 'conditional_whatsapp_1';
	}

	public function get_label(): string {
		return 'Conditional WhatsApp';
	}

    public function controler_id( $control_id ) {
        return $control_id . '_conditional_whatsapp_1';
    }

    private static $registered_actions = [];

	public function register_settings_section( $widget ) {
        $control_id = $this->controler_id( 'section_whatsapp-redirect' );
        if ( in_array( $control_id, self::$registered_actions, true ) ) {
                return; // Already registered
        }

        self::$registered_actions[] = $control_id;
        
		$widget->start_controls_section(
			$this->controler_id('section_whatsapp-redirect'),
			[
				'label' => $this->get_label(),
				'condition' => [
					'cool_formkit_submit_actions' => $this->get_name(),
				],
			]
		);

		$widget->add_control(
			$this->controler_id('whatsapp_to'),
			[
				'label' => \esc_html__( 'WhatsApp Phone', 'cool-formkit' ),
				'type' => \Elementor\Controls_Manager::TEXT,
				'placeholder' => \esc_html__( '13459999999', 'cool-formkit' ),
				'label_block' => true,
				'render_type' => 'none',
				'classes' => 'elementor-control-whats-phone-direction-ltr',
				'description' => \esc_html__( 'Phone with country code, like: 5551999999999', 'cool-formkit' ),
				'dynamic' => [
					'active' => true,
				],
			]
		);

		$widget->add_control(
			$this->controler_id('whatsapp_message'),
			[
				'label' => \esc_html__( 'WhatsApp Message', 'cool-formkit' ),
				'type' => \Elementor\Controls_Manager::TEXTAREA,
				'placeholder' => \esc_html__( 'Write yout text or use fields shortcode', 'cool-formkit' ),
				'label_block' => true,
				'render_type' => 'none',
				'classes' => 'elementor-control-whats-direction-ltr',
				'description' => \esc_html__( 'Use fields shortcodes for send form data or write your custom text.<br>=> To add break line use token: %break%', 'cool-formkit' ),
				'dynamic' => [
					'active' => true,
				],
			]
		);

        $cfef_conditional_logic_id = $this->controler_id( 'conditional_logic' );

        $widget->add_control(
            $cfef_conditional_logic_id,
            array(
                'label' => esc_html__( 'Enable Conditions', 'cool-formkit' ),
                'render_type' => 'none',
                'type' => Controls_Manager::SWITCHER,
            )
        );

        $widget->add_control(
            $this->controler_id( 'conditional_whatsapp_field_display' ),
            array(
                'label' => esc_html__( 'Send mode', 'cool-formkit' ),
                'type' => Controls_Manager::CHOOSE,
                'options' => array(
                    'show' => array(
                        'title' => esc_html__( 'Send if', 'cool-formkit' ),
                        'icon' => 'fa fa-paper-plane',
                    ),
                    'hide' => array(
                        'title' => esc_html__( 'Don not send', 'cool-formkit' ),
                        'icon' => 'fa fa-times',
                    ),
                ),
                'default' => 'show',
                'condition' => array(
                    $cfef_conditional_logic_id => 'yes'
                ),
            )
        );

        $widget->add_control(
            $this->controler_id( 'conditional_whatsapp_field_trigger' ),
            array(
                'label' => esc_html__( 'Conditions Trigger', 'cool-formkit' ),
                'type' => Controls_Manager::SELECT,
                'options' => array(
                    "All"=> esc_html__('All - AND Conditions','cool-formkit'),
                    "Any"=> esc_html__('Any - OR Conditions','cool-formkit')
                ),
                'default' => 'All',
                'condition' => array(
                    $cfef_conditional_logic_id => 'yes'
                ),
            )
        );

        $repeater = new \Elementor\Repeater();

        $repeater->add_control(
            'conditional_logic_id',
            array(
                'label' => esc_html__( 'Field ID', 'cool-formkit' ),
                'type' => Controls_Manager::TEXT,
                'label_block' => true,
                'default' => '',
                'ai' => array(
                    'active' => false,
                ),
            )
        );

        $repeater->add_control(
            'conditional_logic_operator',
            array(
                'label' => esc_html__( 'Operator', 'cool-formkit' ),
                'type' => Controls_Manager::SELECT,
                'label_block' => true,
                'options' => array(
                    '==' => esc_html__( 'is equal ( == )', 'cool-formkit' ),
                    '!=' => esc_html__( 'is not equal (!=)', 'cool-formkit' ),
                    '>'  => esc_html__( 'greater than (>)', 'cool-formkit' ),
                    '<'  => esc_html__( 'less than (<)', 'cool-formkit' ),
                        '>=' => esc_html__( 'greater than equal (>=)', 'cool-formkit' ),
                        '<=' => esc_html__( 'less than equal (<=)', 'cool-formkit' ),
                        'e'  => esc_html__( "empty ('')", 'cool-formkit' ),
                        '!e' => esc_html__( 'not empty', 'cool-formkit' ),
                        'c'  => esc_html__( 'contains', 'cool-formkit' ),
                        '!c' => esc_html__( 'does not contain', 'cool-formkit' ),
                        '^'  => esc_html__( 'starts with', 'cool-formkit' ),
                        '~'  => esc_html__( 'ends with', 'cool-formkit' ),
                    ),
                    'default' => '==',
                    'ai' => array(
                        'active' => false,
                    ),
                )
            );

            $repeater->add_control(
                'conditional_logic_value',
                array(
                    'label' => esc_html__( 'Value to compare', 'cool-formkit' ),
                    'type' => Controls_Manager::TEXT,
                    'label_block' => true,
                    'default' => '',
                    'ai' => array(
                        'active' => false,
                    ),
                )
            );

            $widget->add_control(
                $this->controler_id( 'conditional_whatsapp_fields_datas' ),
                array(
                    'name' => 'conditional_whatsapp_fields_datas',
                    'label' => esc_html__( 'Send if / Do not Send', 'cool-formkit' ),
                    'type' => Controls_Manager::REPEATER,
                    'fields' => $repeater->get_controls(),
                    'condition' => array(
                        $cfef_conditional_logic_id => 'yes'
                    ),
                    'style_transfer' => false,
                    'title_field' => '{{{ conditional_logic_id }}} {{{ conditional_logic_operator }}} {{{ conditional_logic_value }}}',
                    'default' => array(
                        array(
                            'conditional_logic_id' => '',
                            'conditional_logic_operator' => '==',
                            'conditional_logic_value' => '',
                        ),
                    ),
                )
            );
		$widget->end_controls_section();
	}

	/**
	 * On Export
	 *
	 * Clears form settings on export
	 * @param array $element
	 */
	public function on_export( $element ) {
		unset(
			$element['settings'][$this->controler_id('whatsapp_to')],
			$element['settings'][$this->controler_id('whatsapp_message')]
		);

		return $element;
	}

	/**
	 * Runs the action after submit
	 *
	 * @param \ElementorPro\Modules\Forms\Classes\Form_Record $record
	 * @param \ElementorPro\Modules\Forms\Classes\Ajax_Handler $ajax_handler
	 */
	public function run( $record, $ajax_handler ) {
        $submit_actions = $record->get( 'form_settings' )['cool_formkit_submit_actions'] ?? [];
		if ( ! in_array( $this->get_name(), (array) $submit_actions, true ) ) {
			return;
		}

        $settings = $record->get( 'form_settings' );

        $send_to_whatsapp = true;

        if ( isset( $settings[ $this->controler_id( 'conditional_logic' ) ] ) 
            && $settings[ $this->controler_id( 'conditional_logic' ) ] === 'yes' ) {

            $send_mode   = $settings[ $this->controler_id( 'conditional_whatsapp_field_display' ) ]; // 'show' or 'hide'
            $logic_match = $settings[ $this->controler_id( 'conditional_whatsapp_field_trigger' ) ]; // 'All' or 'Any'
            $conditions  = $settings[ $this->controler_id( 'conditional_whatsapp_fields_datas' ) ] ?? [];

            $results     = [];
            $form_fields = $record->get( 'fields' );

            foreach ( $conditions as $cond ) {
                $field_value = isset( $form_fields[ trim($cond['conditional_logic_id']) ]['value'] ) 
                    ? $form_fields[ trim($cond['conditional_logic_id']) ]['value'] 
                    : '';

                if ( is_array( $field_value ) ) {
                    $field_value = implode( ', ', $field_value );
                }

                $results[] = $this->cfefp_check_whatsapp_action_logic( $field_value, $cond['conditional_logic_operator'], $cond['conditional_logic_value'] );
            }

            $conditions_pass = ($logic_match === 'All') 
                ? ! in_array( false, $results, true ) 
                : in_array( true, $results, true );

            $send_to_whatsapp = ($send_mode === 'show') ? $conditions_pass : ! $conditions_pass;
        }

        if(!$send_to_whatsapp){
            return;
        }

		$whatsapp_to = $record->get_form_settings( $this->controler_id('whatsapp_to') );
		$whatsapp_message = $record->get_form_settings( $this->controler_id('whatsapp_message') );

		$whatsapp_message = str_replace('%break%', '%0D%0A', $whatsapp_message);

		$whatsapp_to = 'https://wa.me/'.$whatsapp_to.'?text='.$whatsapp_message.'';
		$whatsapp_to = $record->replace_setting_shortcodes( $whatsapp_to, true );

		if ( ! empty( $whatsapp_to ) ) {
			$ajax_handler->add_response_data( 'redirect_url', $whatsapp_to );
		}
	}

    public function cfefp_check_whatsapp_action_logic($value_id,$operator,$value){
        // Sanitize and escape dynamic values.
        $value_id = esc_html( $value_id );
        $value    = trim( $value );
        $value    = esc_html( $value );

        switch($operator) {
            case "==":
                return $value_id == $value;
            case "!=":
                return $value_id != $value;
            case "e":
                return $value_id == "";
            case "!e":
                return $value_id != "";
            case "c":
                return str_contains($value_id, $value);
            case "!c":
                return !str_contains($value_id, $value);
            case "^":
                return str_starts_with($value_id, $value);
            case "~":
                return str_ends_with($value_id, $value);
            case ">":
                return $value_id > $value;
            case "<":
                return $value_id < $value;
            case "<=":
                return $value_id <= $value;
            case ">=":
                return $value_id >= $value;
            default:
                return false; // Default case if operator is not recognized
        }
    }
}

class HelloPlus_Conditional_Whatsapp_Redirect_2 extends HelloPlus_Conditional_Whatsapp_Redirect {
    public function get_name(): string {
		return 'conditional_whatsapp_2';
	}
    public function get_label(): string { 
		return esc_html__( 'Conditional Whatsapp 2', 'cool-formkit' );
	}
    public function controler_id( $control_id ) { 
		return $control_id . '_conditional_whatsapp_2';
	}
}
class HelloPlus_Conditional_Whatsapp_Redirect_3 extends HelloPlus_Conditional_Whatsapp_Redirect {
    public function get_name(): string {
		return 'conditional_whatsapp_3';
	}
    public function get_label(): string { 
		return esc_html__( 'Conditional Whatsapp 3', 'cool-formkit' );
	}
    public function controler_id( $control_id ) { 
		return $control_id . '_conditional_whatsapp_3';
	}
}
class HelloPlus_Conditional_Whatsapp_Redirect_4 extends HelloPlus_Conditional_Whatsapp_Redirect {
    public function get_name(): string {
		return 'conditional_whatsapp_4';
	}
    public function get_label(): string { 
		return esc_html__( 'Conditional Whatsapp 4', 'cool-formkit' );
	}
    public function controler_id( $control_id ) { 
		return $control_id . '_conditional_whatsapp_4';
	}
}
