<?php
/**
 * Class Cfkef_Conditional_Fields_Redirection_Pro
 */
if ( ! defined( 'ABSPATH' ) ){
    exit;
} 

use Elementor\Controls_Manager;
use ElementorPro\Modules\Forms\actions\Redirect;
use Elementor\Modules\DynamicTags\Module;

if(!class_exists('Cfkef_Conditional_Fields_Redirection_Pro')) {
class Cfkef_Conditional_Fields_Redirection_Pro extends Redirect {

    /**
	 * Get action name.
	 *
	 * Retrieve Cfkef_Conditional_Fields_Redirection_Pro action name.
	 *
	 * @access public
	 * @return string
	 */
	public function get_name() {
		return 'conditional_fields_redirection_pro';
	}

    /**
	 * Get action label.
	 *
	 * Retrieve Conditional Fields Redirection action label.
	 *
	 * @access public
	 * @return string
	 */
	public function get_label() {
		return esc_html__( 'Redirect Conditionally', 'cool-formkit' );
	}

    /**
	 * Get action Controler ID.
	 *
	 * Retrieve Conditional Fields Controler ID.
	 *
	 * @access public
     * @param $control_id
	 * @return string
	 */
	public function controler_id( $control_id ) {
		return $control_id . '_cfefp_conditional_fields';
	}

    /**
	 * Register action controls.
	 *
	 * Method to register action controls.
	 *
	 * @access public
	 * @param \Elementor\Widget_Base $widget
	 */
	public function register_settings_section( $widget ) {
        
		$widget->start_controls_section(
			$this->controler_id( 'section_redirect' ),
			array(
				'label' => $this->get_label(),
				'condition' => array(
					'submit_actions' => $this->get_name(),
                ),
            )
		);
		$cfef_conditional_logic_id = $this->controler_id( 'cfef_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( 'cfef_logic_mode' ),
			array(
				'label' => esc_html__( 'Redirection mode', 'cool-formkit' ),
                'type' => Controls_Manager::CHOOSE,
                'options' => array(
                    'show' => array(
                        'title' => esc_html__( 'Redirect', 'cool-formkit' ),
                        'icon' => 'fa fa-link',
                    ),
                    'hide' => array(
                        'title' => esc_html__( 'No Redirect If', 'cool-formkit' ),
                        'icon' => 'fa fa-unlink',
                    ),
                ),
                'default' => 'show',
                'condition' => array(
                    $cfef_conditional_logic_id => 'yes'
                ),
            )
		);
		$widget->add_control(
			$this->controler_id( 'cfef_logic_meet' ),
			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(
            'cfef_logic_field_id',
            array(
                'label' => esc_html__( 'Field ID', 'cool-formkit' ),
                'type' => Controls_Manager::TEXT,
                'label_block' => true,
                'default' => '',
                'ai' => array(
                    'active' => false,
                ),
            )
        );

        $repeater->add_control(
            'cfef_logic_field_is',
            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(
            'cfef_logic_compare_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( 'cfef_repeater_data' ),
            array(
                'name' => 'cfef_repeater_data',
                'label' => esc_html__( 'Redirect / Do Not Redirect', 'cool-formkit' ),
                'type' => Controls_Manager::REPEATER,
                'fields' => $repeater->get_controls(),
                'condition' => array(
                    $cfef_conditional_logic_id => 'yes'
                ),
                'style_transfer' => false,
                'title_field' => '{{{ cfef_logic_field_id }}} {{{ cfef_logic_field_is }}} {{{ cfef_logic_compare_value }}}',
                'default' => array(
                    array(
                        'cfef_logic_field_id' => '',
                        'cfef_logic_field_is' => '==',
                        'cfef_logic_compare_value' => '',
                    ),
                ),
            )
        );

		$widget->add_control(
			$this->controler_id( 'cfef_redirection_to' ),
			array(
				'label' => esc_html__( 'Redirection', 'cool-formkit' ),
				'type' => Controls_Manager::TEXT,
				'placeholder' => esc_html__( 'https://coolplugins.net/', 'cool-formkit' ),
				'dynamic' => array(
					'active' => true,
					'categories' => array(
						Module::POST_META_CATEGORY,
						Module::TEXT_CATEGORY,
						Module::URL_CATEGORY,
                    ),
                ),
				'label_block' => true,
				'render_type' => 'none',
				'classes' => 'elementor-control-direction-ltr',
                'condition' => array(
                    $cfef_conditional_logic_id => 'yes'
                ),
                'ai'          => array(
                    'active' => false,
                ),
            )
		);

		$widget->end_controls_section();
	}

    /**
	 * On export.
	 *
	 * method to clear fields when exporting.
	 *
	 * @access public
	 * @param array $element
	 */
	public function on_export( $element ) {

		unset(
			$element['form_settings'][$this->controler_id( 'cfef_redirection_to' )]
		);
		return $element;
	}

    /**
	 * cfefp_check_field_redirection_logic.
	 *
	 * method to compare fields.
	 *
	 * @param $value_id, $operator, $value
     * @return boolean
	 */
    function cfefp_check_field_redirection_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
        }
    }

    /**
	 * Run action.
	 *
	 * Method for form redirection after form submission.
	 *
	 * @access public
	 * @param \ElementorPro\Modules\Forms\Classes\Form_Record  $record
	 * @param \ElementorPro\Modules\Forms\Classes\Ajax_Handler $ajax_handler
	 */
	public function run( $record, $ajax_handler ) {
		$form_settings = $record->get( 'form_settings' );
		$send_status = true;
		if( $form_settings[$this->controler_id( 'cfef_logic' )] == "yes" ){
            $display_mode = $form_settings[$this->controler_id( 'cfef_logic_mode' )];
            $fire_action = $form_settings[$this->controler_id( 'cfef_logic_meet' )];
            $repeater_data = $form_settings[$this->controler_id( 'cfef_repeater_data' )];

            $condition_pass_fail = array();
            $form_fields = $record->get("fields");
            foreach ( $repeater_data as $field_key => $field_values ) {
                if(isset($form_fields[$field_values["cfef_logic_field_id"]])){
                    $value_id = $form_fields[$field_values["cfef_logic_field_id"]]["value"];
                    if( is_array($value_id) ){
                        $value_id = implode(", ",$value_id);
                    }
                }else{
                   $value_id = $field_values["cfef_logic_field_id"];
                }
                $operator = $field_values["cfef_logic_field_is"];
                $value = $field_values["cfef_logic_compare_value"];
                $condition_pass_fail[] = $this->cfefp_check_field_redirection_logic($value_id,$operator,$value);
            }

        $check_rs = $fire_action == "All" ? !in_array(false, $condition_pass_fail) : in_array(true, $condition_pass_fail);
        $send_status = ($display_mode == "show") ? $check_rs : !$check_rs;

		}
		if( $send_status ==  true ){
			$cfef_redirection_to = $form_settings[$this->controler_id( 'cfef_redirection_to' )];
            
            if(!empty($cfef_redirection_to)){
                $cfef_redirection_to = $record->replace_setting_shortcodes( $cfef_redirection_to, true );
                if ( ! empty( $cfef_redirection_to ) && filter_var( $cfef_redirection_to, FILTER_VALIDATE_URL ) ) {
                    $form_settings['redirect_to']=$cfef_redirection_to;
                    $record->set('form_settings',$form_settings);
                    $ajax_handler->add_response_data( 'redirect_url', $cfef_redirection_to );
                }
            }
		}
		
	}
    
}

/**
 * Class Cfkef_Conditional_Fields_Redirection_Two_Pro
 */
class Cfkef_Conditional_Fields_Redirection_Two_Pro extends Cfkef_Conditional_Fields_Redirection_Pro {
	public function get_name() {
		return 'conditional_fields_redirection_two_pro';
	}

	public function get_label() {
		return esc_html__( 'Redirect Conditionally 2', 'cool-formkit' );
	}
	public function controler_id( $control_id ) {
		return $control_id . '_cfefp_conditional_fields_two';
	}
}

/**
 * Class Cfkef_Conditional_Fields_Redirection_Three_Pro
 */
class Cfkef_Conditional_Fields_Redirection_Three_Pro extends Cfkef_Conditional_Fields_Redirection_Pro {
	public function get_name() {
		return 'conditional_fields_redirection_three_pro';
	}

	public function get_label() {
		return esc_html__( 'Redirect Conditionally 3', 'cool-formkit' );
	}
	public function controler_id( $control_id ) {
		return $control_id . '_cfefp_conditional_fields_three';
	}
}

/**
 * Class Cfkef_Conditional_Fields_Redirection_Four_Pro
 */
class Cfkef_Conditional_Fields_Redirection_Four_Pro extends Cfkef_Conditional_Fields_Redirection_Pro {
	public function get_name() {
		return 'conditional_fields_redirection_four_pro';
	}

	public function get_label() {
		return esc_html__( 'Redirect Conditionally 4', 'cool-formkit' );
	}
	public function controler_id( $control_id ) {
		return $control_id . '_cfefp_conditional_fields_four';
	}
}

/**
 * Get the redirect conditional key value and loop the rest of the based on that. 
 */

$redirect_conditionally = get_option('cfefp_redirect_conditionally', '');

for ($i = 5; $i <= $redirect_conditionally; $i++) {
    $class_name = sprintf('Cfkef_Conditional_Fields_Redirection_%s_Pro', $i);
    if (!class_exists($class_name)) {
        eval("
            class $class_name extends Cfkef_Conditional_Fields_Redirection_Pro {
                public function get_name() {
                    return 'conditional_fields_redirection_{$i}_pro';
                }

                public function get_label() {
                    return esc_html__('Redirect Conditionally {$i}', 'cool-formkit');
                }

                public function controler_id(\$control_id) {
                    return \$control_id . '_cfefp_conditional_fields_{$i}';
                }
            }
        ");
    }
}
}