<?php
namespace Cool_FormKit_Pro\Widgets\HelloPlusAddons;

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

use Elementor\Controls_Manager;
use HelloPlus\Modules\Forms\Classes\Form_Record;
use HelloPlus\Modules\Forms\Components\Ajax_Handler;
use Cool_FormKit_Pro\Widgets\HelloPlusAddons\Action\Mailchimp;
use Cool_FormKit_Pro\Widgets\HelloPlusAddons\Action\Integration_Base;
use Cool_FormKit_Pro\Widgets\HelloPlusAddons\Action\Mailchimp_Handler;


class HelloPlus_Conditional_Mailchimp extends Mailchimp {

    const OPTION_NAME_API_KEY = 'cfl_mailchimp_api_key';

    /**
	 * @var string - Mailchimp API key.
	 */
	private $api_key;

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

    public function get_global_api_key() {
		return get_option( self::OPTION_NAME_API_KEY );
	}

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

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

	private static $registered_actions = [];

    /**
     * Add extra controls for conditions like you did in redirection
     */
    public function register_settings_section( $widget ) {
		$control_id = $this->controler_id( 'section_mailchimp' );
        
        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_mailchimp'),
			[
				'label' => $this->get_label(),
				'condition' => array(
                    'cool_formkit_submit_actions' => $this->get_name(),
				),
			]
		);

		self::global_api_control(
			$widget,
			$this->get_global_api_key(),
			'MailChimp API Key',
			[
				$this->controler_id('mailchimp_api_key_source') => 'default',
			],
			$this->get_name()
		);

		$widget->add_control(
			$this->controler_id('mailchimp_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('mailchimp_api_key'),
			[
				'label' => esc_html__( 'Custom API Key', 'cool-formkit' ),
				'type' => Controls_Manager::TEXT,
				'condition' => [
					$this->controler_id('mailchimp_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('mailchimp_list'),
			[
				'label' => esc_html__( 'Audience', 'cool-formkit' ),
				'type' => Controls_Manager::SELECT,
				'options' => [],
				'render_type' => 'none',
				'conditions' => [
					'relation' => 'or',
					'terms' => [
						[
							'name' => $this->controler_id('mailchimp_api_key'),
							'operator' => '!==',
							'value' => '',
						],
						[
							'name' => $this->controler_id('mailchimp_api_key_source'),
							'operator' => '=',
							'value' => 'default',
						],
					],
				],
			]
		);

		$widget->add_control(
			$this->controler_id('mailchimp_groups'),
			[
				'label' => esc_html__( 'Groups', 'cool-formkit' ),
				'type' => Controls_Manager::SELECT2,
				'options' => [],
				'label_block' => true,
				'multiple' => true,
				'render_type' => 'none',
				'condition' => [
					$this->controler_id('mailchimp_list').'!' => '',
					// 'mailchimp_list_cond_mc!' => '',
				],
			]
		);

		$widget->add_control(
			$this->controler_id('mailchimp_tags'),
			[
				'label' => esc_html__( 'Tags', 'cool-formkit' ),
				'description' => esc_html__( 'Add comma separated tags', 'cool-formkit' ),
				'type' => Controls_Manager::TEXT,
				'render_type' => 'none',
				'condition' => [
					$this->controler_id('mailchimp_list').'!' => '',
					// 'mailchimp_list_cond_mc!' => '',
				],
				'ai' => [
					'active' => false,
				],
			]
		);

		$widget->add_control(
			$this->controler_id('mailchimp_double_opt_in'),
			[
				'label' => esc_html__( 'Double Opt-In', 'cool-formkit' ),
				'type' => Controls_Manager::SWITCHER,
				'default' => '',
				'condition' => [
					$this->controler_id('mailchimp_list').'!' => '',
					// 'mailchimp_list_cond_mc!' => '',
				],
			]
		);

		$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_mailchimp_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_mailchimp_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_mailchimp_fields_datas' ),
			array(
				'name' => 'conditional_mailchimp_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('mailchimp_api_key_source')],
			$element['settings'][$this->controler_id('mailchimp_api_key')],
			$element['settings'][$this->controler_id('mailchimp_list')],
			$element['settings'][$this->controler_id('mailchimp_groups')],
			$element['settings']['conditional_mailchimp_1_fields_map']
		);
		return $element;
	}

    /**
     * Conditional logic before Mailchimp is triggered
     */
    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;
		}

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

		$send_to_mailchimp = 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_mailchimp_field_display' ) ]; // 'show' or 'hide'
			$logic_match = $form_settings[ $this->controler_id( 'conditional_mailchimp_field_trigger' ) ]; // 'All' or 'Any'
			$conditions  = $form_settings[ $this->controler_id( 'conditional_mailchimp_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_mailchimp_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_mailchimp = ($send_mode === 'show') ? $conditions_pass : ! $conditions_pass;
		}

		if(!$send_to_mailchimp){
			return;
		}

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

		// Data from the form in the frontend.
		$subscriber_data = $this->map_fields( $record );		

		// Create or update a subscriber.
		$subscriber = $this->create_or_update_subscriber( $subscriber_data, $form_settings );

		// Parse the Mailchimp tags.
		$tags = $this->parse_tags( $form_settings['mailchimp_tags'] );

		// Set the subscriber tags only if he doesn't have them already.
		if ( ! $this->subscriber_has_tags( $subscriber, $tags ) ) {
			$this->set_subscriber_tags( $subscriber, $tags );
		}
    }

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

	private function map_fields( $record ) {
		$subscriber = [];
		$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 ( 'email' === $map_item['remote_id'] ) {
				$subscriber['email_address'] = $value;
			} else {
				$subscriber['merge_fields'][ $map_item['remote_id'] ] = $value;
			}
		}

		return $subscriber;
	}

	/**
	 * @param string $tags - List of comma separated tags from the forms settings ( i.e. 'tag-1, tag-2' ).
	 *
	 * @return array|string[] - Array of tags that were extracted from the input ( i.e. [ 'tag-1', 'tag-2' ] ).
	 */
	private function parse_tags( $tags ) {
		$parsed_tags = [];

		if ( ! empty( $tags ) ) {
			$parsed_tags = explode( ',', trim( $tags ) );

			// Remove empty tags.
			$parsed_tags = array_filter( $parsed_tags );

			// Trim tags.
			$parsed_tags = array_map( 'trim', $parsed_tags );
		}

		return $parsed_tags;
	}

	/**
	 * Determine if a subscriber has specific tags, and ONLY those tags.
	 *
	 * @param array $subscriber - Subscriber data from an API response.
	 * @param array $tags - List of tags to check ( i.e. [ 'tag-1', 'tag-2' ] ).
	 *
	 * @return bool
	 */
	private function subscriber_has_tags( array $subscriber, array $tags ) {
		// Extract current tags.
		$subscriber_tags = [];

		foreach ( $subscriber['tags'] as $tag ) {
			$subscriber_tags[] = $tag['name'];
		}

		return array_diff( $tags, $subscriber_tags ) === array_diff( $subscriber_tags, $tags );
	}

	/**
	 * Set Mailchimp subscriber tags.
	 *
	 * @param array $subscriber - Subscriber data from a create/update request.
	 * @param array $tags - List of tags to set.
	 *
	 * @return void
	 */
	private function set_subscriber_tags( array $subscriber, array $tags ) {
		// Build the request tags.
		$request_tags = [];

		// Set current tags to active.
		foreach ( $subscriber['tags'] as $tag ) {
			$request_tags[] = [
				'name' => $tag['name'],
				'status' => 'active',
			];
		}

		// Set new tags to active.
		foreach ( $tags as $tag ) {
			$request_tags[] = [
				'name' => $tag,
				'status' => 'active',
			];
		}

		// Send the API request.
		$endpoint = sprintf( 'lists/%s/members/%s/tags', $subscriber['list_id'], md5( strtolower( $subscriber['email_address'] ) ) );
		$args = [
			'tags' => $request_tags,
		];

		$handler = new Mailchimp_Handler( $this->api_key );
		$response = $handler->post( $endpoint, $args );

		if ( 204 !== $response['code'] ) {
			$error = ! empty( $response['body']['detail'] ) ? $response['body']['detail'] : '';
			$code = $response['code'];

			throw new \Exception( "HTTP {$code} - {$error}" );
		}
	}

	/**
	 * Create or update a Mailchimp subscriber.
	 *
	 * @param array $subscriber - Subscriber data from the form in the frontend.
	 * @param array $form_settings - Settings from the editor.
	 *
	 * @return array - An array that contains the newly created subscriber's data.
	 */
	private function create_or_update_subscriber( array $subscriber, array $form_settings ) {
		if ( ! empty( $form_settings[$this->controler_id('mailchimp_groups')] ) ) {
			$subscriber['interests'] = [];
		}

		if ( is_array( $form_settings[$this->controler_id('mailchimp_groups')] ) ) {
			foreach ( $form_settings[$this->controler_id('mailchimp_groups')] as $mailchimp_group ) {
				$subscriber['interests'][ $mailchimp_group ] = true;
			}
		}

		if ( ! empty( $form_settings[$this->controler_id('mailchimp_tags')] ) ) {
			$subscriber['tags'] = explode( ',', trim( $form_settings[$this->controler_id('mailchimp_tags')] ) );
		}

		$list = $form_settings[$this->controler_id('mailchimp_list')];
		$email_hash = md5( strtolower( $subscriber['email_address'] ) );
		$double_opt_in = ( 'yes' === $form_settings[$this->controler_id('mailchimp_double_opt_in')] );

		$subscriber['status_if_new'] = $double_opt_in ? 'pending' : 'subscribed';

		if ( $double_opt_in ) {
			$subscriber_data = $this->get_subscriber_data( $list, $email_hash );

			// Change the current status only if the user isn't subscribed already.
			if ( $subscriber_data && 'subscribed' !== $subscriber_data['status'] ) {
				$subscriber['status'] = 'pending';
			}
		} else {
			$subscriber['status'] = 'subscribed';
		}

		return $this->set_subscriber_data( $list, $email_hash, $subscriber );
	}

	/**
	 * Get Mailchimp subscriber data.
	 *
	 * @param string $list - Mailchimp List ID.
	 * @param string $email_hash - Subscriber's email hash (lowercase + MD5).
	 *
	 * @return array|null
	 */
	private function get_subscriber_data( $list, $email_hash ) {
		$handler = new Mailchimp_Handler( $this->api_key );
		$end_point = sprintf( 'lists/%s/members/%s', $list, $email_hash );

		try {
			return $handler->query( $end_point );
		} catch ( \Exception $e ) {
			return null;
		}
	}

	/**
	 * Set Mailchimp subscriber data.
	 *
	 * @param string $list - Mailchimp List ID.
	 * @param string $email_hash - Subscriber's email hash (lowercase + MD5).
	 * @param array $data - New subscriber data to set.
	 *
	 * @return array
	 */
	private function set_subscriber_data( $list, $email_hash, $data ) {
		$handler = new Mailchimp_Handler( $this->api_key );

		$end_point = sprintf( 'lists/%s/members/%s', $list, $email_hash );

		$response = $handler->post( $end_point, $data, [
			'method' => 'PUT', // Add or Update
		] );

		if ( 200 !== $response['code'] ) {
			$error = ! empty( $response['body']['detail'] ) ? $response['body']['detail'] : '';
			$code = $response['code'];

			throw new \Exception( "HTTP {$code} - {$error}" );
		}

		return $response['body'];
	}

    public function handle_panel_request( array $data ) {
		
		if ( ! empty( $data['use_global_api_key'] ) && 'default' === $data['use_global_api_key'] ) {
			$api_key = $this->get_global_api_key();
		} elseif ( ! empty( $data['api_key'] ) ) {
			$api_key = $data['api_key'];
		}

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

		$handler = new Mailchimp_Handler( $api_key );
		
		switch ( $data['conditional_mailchimp_action'] ) {
			case 'lists':
				return $handler->get_lists();

			case 'fields':
				return $handler->get_fields( $data['mailchimp_list'] );

			case 'groups':
				return $handler->get_groups( $data['mailchimp_list'] );

			default:
				return $handler->get_list_details( $data['mailchimp_list'] );
		}
	}

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

class HelloPlus_Conditional_Mailchimp_2 extends HelloPlus_Conditional_Mailchimp {
    public function get_name(): string {
		return 'conditional_mailchimp_2';
	}
    public function get_label(): string { 
		return esc_html__( 'Conditional Mailchimp 2', 'cool-formkit' );
	}
    public function controler_id( $control_id ) { 
		return $control_id . '_cond_mc_2';
	}
}
class HelloPlus_Conditional_Mailchimp_3 extends HelloPlus_Conditional_Mailchimp {
    public function get_name(): string {
		return 'conditional_mailchimp_3';
	}
    public function get_label(): string { 
		return esc_html__( 'Conditional Mailchimp 3', 'cool-formkit' );
	}
    public function controler_id( $control_id ) { 
		return $control_id . '_cond_mc_3';
	}
}
class HelloPlus_Conditional_Mailchimp_4 extends HelloPlus_Conditional_Mailchimp {
    public function get_name(): string {
		return 'conditional_mailchimp_4';
	}
    public function get_label(): string { 
		return esc_html__( 'Conditional Mailchimp 4', 'cool-formkit' );
	}
    public function controler_id( $control_id ) { 
		return $control_id . '_cond_mc_4';
	}
}