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

use Elementor\Controls_Manager;
use ElementorPro\Modules\Forms\Actions\Getresponse;
use ElementorPro\Modules\Forms\Classes\Form_Record;
use ElementorPro\Modules\Forms\Classes\Integration_Base;
use ElementorPro\Modules\Forms\Classes\Ajax_Handler;
use ElementorPro\Modules\Forms\Classes\Getresponse_Handler;
use Cool_FormKit_Pro\Includes\Utils;



class Conditional_Getresponse extends Getresponse {

	const OPTION_NAME_API_KEY = 'pro_getresponse_api_key';

    private function get_global_api_key() {
		return get_option( 'elementor_' . self::OPTION_NAME_API_KEY, '' );
	}

	private $api_key;

    public function get_name() {
        return 'conditional_getresponse';
    }

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

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

    /**
     * Add extra controls for conditions like you did in redirection
     */
    public function register_settings_section( $widget ) {

        $widget->start_controls_section(
            $this->controler_id('section_getresponse'),
			[
				'label' => $this->get_label(),
				'condition' => [
					'submit_actions' => $this->get_name(),
				],
			]
		);

		self::global_api_control(
			$widget,
			$this->get_global_api_key(),
			'GetResponse API key',
			[
				$this->controler_id('getresponse_api_key_source') => 'default',
			],
			$this->get_name()
		);		

		$widget->add_control(
			$this->controler_id( 'getresponse_conflict_notice' ),
			[
				'type' => Controls_Manager::RAW_HTML,
				'raw'  => '<div><strong>⚠️ Notice:</strong> You are using both Elementor Default <strong>GetResponse</strong> and <strong>' . esc_html( $this->get_label() ) . '</strong>. Please remove one — only one can be active at a time.</div>',
				'content_classes' => 'elementor-panel-alert',
				'separator' => 'before',
				'conditions' => [
					'relation' => 'and',
					'terms' => [
						[ 'name' => 'submit_actions', 'operator' => 'contains', 'value' => 'getresponse' ],
						[ 'name' => 'submit_actions', 'operator' => 'contains', 'value' => $this->get_name() ],
					],
				],
			]
		);

		$widget->add_control(
			$this->controler_id('getresponse_api_key_source'),
			[
				'label' => esc_html__( 'API Key', 'cool-formkit' ),
				'type' => Controls_Manager::SELECT,
				'label_block' => false,
				'options' => [
					'default' => esc_html__( 'Default', 'cool-formkit' ),
					'custom' => esc_html__( 'Custom', 'cool-formkit' ),
				],
				'default' => 'default',
			]
		);

		$widget->add_control(
			$this->controler_id('getresponse_custom_api_key'),
			[
				'label' => esc_html__( 'Custom API Key', 'cool-formkit' ),
				'type' => Controls_Manager::TEXT,
				'condition' => [
					$this->controler_id('getresponse_api_key_source') => 'custom',
				],
				'description' => esc_html__( 'Use this field to set a custom API Key for the current form', 'cool-formkit' ),
				'ai' => [
					'active' => false,
				],
			]
		);

		$widget->add_control(
			$this->controler_id('getresponse_list'),
			[
				'label' => esc_html__( 'List', 'cool-formkit' ),
				'type' => Controls_Manager::SELECT,
				'options' => [],
				'render_type' => 'none',
				'conditions' => [
					'relation' => 'or',
					'terms' => [
						[
							'name' => $this->controler_id('getresponse_custom_api_key'),
							'operator' => '!==',
							'value' => '',
						],
						[
							'name' => $this->controler_id('getresponse_api_key_source'),
							'operator' => '=',
							'value' => 'default',
						],
					],
				],
			]
		);

		$widget->add_control(
			$this->controler_id('getresponse_dayofcycle'),
			[
				'label' => esc_html__( 'Day Of Cycle', 'elementor-pro' ),
				'type' => Controls_Manager::NUMBER,
				'min' => 0,
				'condition' => [
					'getresponse_list!' => '',
				],
			]
		);

		$this->register_fields_map_control( $widget );


		$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_getresponse_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_getresponse_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_getresponse_fields_datas' ),
			array(
				'name' => 'conditional_getresponse_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();
    }


    public function on_export( $element ) {
		unset(
			$element['settings'][$this->controler_id('getresponse_api_key_source')],
			$element['settings'][$this->controler_id('getresponse_custom_api_key')],
			$element['settings'][$this->controler_id('getresponse_list')],
			$element['settings']['conditional_getresponse_fields_map']
		);
		return $element;
	}


    /**
     * Conditional logic before getresponse is triggered
     */
    public function run( $record, $ajax_handler ) {
       	$form_settings = $record->get( 'form_settings' );

		$subscriber = $this->create_subscriber_object( $record );

		$send_to_getresponse = true;

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

			$send_mode   = $form_settings[ $this->controler_id( 'conditional_getresponse_field_display' ) ]; // 'show' or 'hide'
			$logic_match = $form_settings[ $this->controler_id( 'conditional_getresponse_field_trigger' ) ]; // 'All' or 'Any'
			$conditions  = $form_settings[ $this->controler_id( 'conditional_getresponse_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_getresponse_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_getresponse = ($send_mode === 'show') ? $conditions_pass : ! $conditions_pass;
		}

		if(!$send_to_getresponse){
			return;
		}

		if ( 'default' === $form_settings[$this->controler_id('getresponse_api_key_source')] ) {
			$this->api_key = $this->get_global_api_key();
		} else {
			$this->api_key = $form_settings[$this->controler_id('getresponse_custom_api_key')];
		}



        try {
			$handler = new Getresponse_Handler( $this->api_key );
			$handler->create_subscriber( $subscriber );
		} catch ( \Exception $exception ) {
			foreach ( (array) $handler->rest_client->request_cache as $response ) {
				if ( isset( $response['parsed'] ) || ! isset( $response['raw'] ) || ! isset( $response['raw']['response'] ) || ! isset( $response['raw']['response']['code'] ) ) {
					continue;
				}
				if ( ! in_array( $response['raw']['response']['code'], [ 200, 202, 409 ] ) ) {
					throw new \Exception( $exception->getMessage() );
				}
			}
		}

    }


    function cfefp_check_getresponse_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
			}
    }



    /**
	 * @param Form_Record $record
	 *
	 * @return array
	 */
	private function map_fields( Form_Record $record ) {
		$subscriber = [];
		$custom_fields = [];
		$fields = $record->get( 'fields' );

		// Other form has a field mapping
		foreach ( $record->get_form_settings( $this->get_name().'_fields_map' ) as $map_item ) {


			if ( empty( $fields[ $map_item['local_id'] ]['value'] ) ) {
				continue;
			}

			$value = $fields[ $map_item['local_id'] ]['value'];

			if ( in_array( $map_item['remote_id'], [ 'name', 'email' ] ) ) {
				$subscriber[ $map_item['remote_id'] ] = $value;
				continue;
			}

			$custom_fields[] = [
				'customFieldId' => $map_item['remote_id'],
				'value' => [ $value ],
			];
		}
		$subscriber['customFieldValues'] = $custom_fields;

		return $subscriber;
	}



    /**
	 * Create subscriber array from submitted data and form settings
	 * returns a subscriber array or false on error
	 * 
	 *
	 * @param Form_Record $record
	 *
	 * @return array|bool
	 */
	private function create_subscriber_object( Form_Record $record ) {
		$form_settings = $record->get( 'form_settings' );

		$subscriber = $this->map_fields( $record );

		if ( ! isset( $subscriber['email'] ) ) {
			return false;
		}

		if ( isset( $form_settings['getresponse_dayofcycle'] ) ) {
			$subscriber['dayOfCycle'] = intval( $form_settings['getresponse_dayofcycle'] );
		}
		$subscriber['ipAddress'] = Utils::get_client_ip();
		$subscriber['campaign'] = [ 'campaignId' => $form_settings[$this->controler_id('getresponse_list')] ];

		return $subscriber;
	}


    /**
	 * @param array $data
	 *
	 * @return array
	 * @throws \Exception
	 */
	public function handle_panel_request( array $data ) {
		if ( ! empty( $data['api_key'] ) && 'default' === $data['api_key'] ) {
			$api_key = $this->get_global_api_key();
		} elseif ( ! empty( $data['custom_api_key'] ) ) {
			$api_key = $data['custom_api_key'];
		}

		if ( empty( $api_key ) ) {
			throw new \Exception( '`api_key` is required.', 400 );
		}

		$handler = new Getresponse_Handler( $api_key );

		if ( 'lists' === $data['getresponse_action'] ) {
			return $handler->get_lists();
		}

		return $handler->get_fields();
	}

	protected function get_fields_map_control_options() {
		return [
			'condition' => [
				$this->controler_id('getresponse_list').'!' => '',
			],
		];
	}

}

class Conditional_Getresponse_2 extends Conditional_Getresponse {
    public function get_name() {
		return 'conditional_getresponse_2';
	}
    public function get_label() { 
		return esc_html__( 'Conditional GetResponse 2', 'cool-formkit' );
	}
    public function controler_id( $control_id ) { 
		return $control_id . '_cond_rp_2';
	}
}
class Conditional_Getresponse_3 extends Conditional_Getresponse {                                    
    public function get_name() {
		return 'conditional_getresponse_3';
	}
    public function get_label() { 
		return esc_html__( 'Conditional GetResponse 3', 'cool-formkit' );
	}
    public function controler_id( $control_id ) { 
		return $control_id . '_cond_rp_3';
	}
}
class Conditional_Getresponse_4 extends Conditional_Getresponse {
    public function get_name() {
		return 'conditional_getresponse_4';
	}
    public function get_label() { 
		return esc_html__( 'Conditional GetResponse 4', 'cool-formkit' );
	}
    public function controler_id( $control_id ) { 
		return $control_id . '_cond_rp_4';
	}
}

$getresponse_conditionally = get_option('cfefp_getresponse_conditionally', 5);

for ($i = 5; $i <= $getresponse_conditionally; $i++) {
    $class_name = sprintf('Conditional_Getresponse_%s', $i);
    if (!class_exists($class_name)) {
        eval("
            class $class_name extends Conditional_Getresponse {
                public function get_name() {
                    return 'conditional_getresponse_{$i}';
                }

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

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