<?php
namespace Cool_FormKit_Pro\Widgets\HelloPlusAddons;


use Elementor\Controls_Manager;
use Cool_FormKit_Pro\Widgets\HelloPlusAddons\Action\Webhook;

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

if ( ! class_exists( 'HelloPlus_Conditional_Webhook' ) ) {

	class HelloPlus_Conditional_Webhook extends Webhook {

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

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

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

        private static $registered_actions = [];


		public function register_settings_section( $widget ) {
            $control_id = $this->controler_id( 'section_webhook' );
            
            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_webhook'),
                [
    				'label' => $this->get_label(),
                    'condition' => [
                        'cool_formkit_submit_actions' => $this->get_name(),
                    ],
                ]
            );

            $widget->add_control(
                $this->controler_id('webhooks'),
                [
                    'label' => esc_html__( 'Webhook URL', 'cool-formkit' ),
                    'type' => Controls_Manager::TEXT,
                    'placeholder' => esc_html__( 'https://your-webhook-url.com', 'cool-formkit' ),
                    'ai' => [
                        'active' => false,
                    ],
                    'label_block' => true,
                    'separator' => 'before',
                    'description' => esc_html__( 'Enter the integration URL (like Zapier) that will receive the form\'s submitted data.', 'cool-formkit' ),
                    'render_type' => 'none',
                    'dynamic' => [
                        'active' => true,
                    ],
                ]
            );

            $widget->add_control(
                $this->controler_id('webhooks_advanced_data'),
                [
                    'label' => esc_html__( 'Advanced Data', 'cool-formkit' ),
                    'type' => Controls_Manager::SWITCHER,
                    'default' => 'no',
                    'render_type' => 'none',
                ]
            );

            $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_webhook_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_webhook_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_webhook_fields_datas' ),
                array(
                    'name' => 'conditional_webhook_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 cfefp_check_webhook_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
            }
        }

		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_webhook = true;

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

                $send_mode   = $settings[ $this->controler_id( 'conditional_webhook_field_display' ) ]; // 'show' or 'hide'
                $logic_match = $settings[ $this->controler_id( 'conditional_webhook_field_trigger' ) ]; // 'All' or 'Any'
                $conditions  = $settings[ $this->controler_id( 'conditional_webhook_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_webhook_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_webhook = ($send_mode === 'show') ? $conditions_pass : ! $conditions_pass;
            }

            if(!$send_to_webhook){
                return;
            }
            
            if ( empty( $settings[$this->controler_id('webhooks')] ) ) {
                return;
            }

            if ( isset( $settings[$this->controler_id('webhooks_advanced_data')] ) && 'yes' === $settings[$this->controler_id('webhooks_advanced_data')] ) {
                $body['form'] = [
                    'id' => $settings['id'],
                    'name' => $settings['form_name'],
                ];

                $body['fields'] = $record->get( 'fields' );
                $body['meta'] = $record->get( 'meta' );
            } else {
                $body = $record->get_formatted_data( true );
                $body['form_id'] = $settings['id'];
                $body['form_name'] = $settings['form_name'];
            }

            $args = [
                'body' => $body,
            ];

            $args = apply_filters( 'elementor_pro/forms/webhooks/request_args', $args, $record );

            $response = wp_safe_remote_post( $settings[$this->controler_id('webhooks')], $args );

            do_action( 'elementor_pro/forms/webhooks/response', $response, $record );

            if(404 === (int) wp_remote_retrieve_response_code( $response )){
                throw new \Exception( 'Address Not Found.' );
            }
            if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
                throw new \Exception( 'Webhook error.' );
            }
		}
	}
}

class HelloPlus_Conditional_Webhook_2 extends HelloPlus_Conditional_Webhook {
    public function get_name() : string {
		return 'conditional_webhook_2';
	}
    public function get_label() : string { 
		return esc_html__( 'Conditional Webhook 2', 'cool-formkit' );
	}
    public function controler_id( $control_id ) { 
		return $control_id . '_conditional_webhook_2';
	}
}
class HelloPlus_Conditional_Webhook_3 extends HelloPlus_Conditional_Webhook {
    public function get_name() : string {
		return 'conditional_webhook_3';
	}
    public function get_label() : string { 
		return esc_html__( 'Conditional Webhook 3', 'cool-formkit' );
	}
    public function controler_id( $control_id ) { 
		return $control_id . '_conditional_webhook_3';
	}
}
class HelloPlus_Conditional_Webhook_4 extends HelloPlus_Conditional_Webhook {
    public function get_name() : string {
		return 'conditional_webhook_4';
	}
    public function get_label() : string { 
		return esc_html__( 'Conditional Webhook 4', 'cool-formkit' );
	}
    public function controler_id( $control_id ) { 
		return $control_id . '_conditional_webhook_4';
	}
}