<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
/**
 * Class for managing the country code field in Elementor forms.
 *
 * This class adds functionality to include country codes in the telephone input fields of Elementor forms.
 *
 * @package Cool_FormKit
 *
 * @version 1.1.7
 */
if(!class_exists('Cfkef_COUNTRY_CODE_FIELD')) { 
class Cfkef_COUNTRY_CODE_FIELD {


	private $validate_form = false;

	/**
	 * Plugin instance.
	 *
	 * @var Cfkef_COUNTRY_CODE_FIELD
	 *
	 * @access private
	 * @var null
	 */
	private static $instance = null;

	/**
	 * Get the plugin instance.
	 *
	 * @return Cfkef_COUNTRY_CODE_FIELD
	 * @static
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor method to initialize actions and assets.
	 */
	public function __construct() {
		require_once CFKEF_PLUGIN_DIR . 'includes/frontend/widgets/module-widgets-helper.php';
		// $this->register_common_assets();

		add_action('wp_enqueue_scripts', array($this, 'register_styles'));
        add_action('wp_enqueue_scripts', array($this, 'register_scripts'));
		
		add_action( 'elementor_pro/forms/render_field/tel', array( $this, 'elementor_form_tel_field_rendering' ), 9, 3 );
		add_action( 'elementor/element/form/section_form_fields/before_section_end', array( $this, 'update_controls' ), 100, 2 );
		add_action( 'elementor/preview/init', array( $this, 'editor_inline_JS' ) );
		add_action( 'wp_ajax_cfef_elementor_review_notice', array( $this, 'cfef_elementor_review_notice' ) );
        add_action( 'elementor_pro/forms/validation', array($this,'submit_validation'),9,3);
	}

	public function register_styles(){
		wp_register_style( 'ccfef-country-code-library-style', CFKEF_PLUGIN_URL . 'assets/css/intlTelInput.min.css', array(), CFKEF_PLUGIN_VERSION, 'all' );
		wp_register_style( 'ccfef-country-code-style', CFKEF_PLUGIN_URL . 'assets/css/country-code-style.min.css', array(), CFKEF_PLUGIN_VERSION, 'all' );
	}

	public function register_scripts(){
		$dependency_array = array( 'elementor-frontend', 'jquery', 'ccfef-country-code-library-script','ccfef-translations' );
		
		$error_map = [
			__("The phone number you entered is not valid. Please check the format and try again.", "cool-formkit"),
			__("The country code you entered is not recognized. Please ensure it is correct and try again.", "cool-formkit"),
			__("The phone number you entered is too short. Please enter a complete phone number, including the country code.", "cool-formkit"),
			__("The phone number you entered is too long. Please ensure it is in the correct format and try again.", "cool-formkit"),
			__("The phone number you entered is not valid. Please check the format and try again.", "cool-formkit")
		];
		
		if ( ! wp_script_is( 'ccfef-country-code-library-script', 'registered' ) ) {
			wp_register_script( 'ccfef-country-code-library-script', CFKEF_PLUGIN_URL . 'assets/js/intlTelInput.js', array(), CFKEF_PLUGIN_VERSION, true );
		}
		wp_register_script(
			'ccfef-translations',
			CFKEF_PLUGIN_URL . 'assets/js/ccfef-translations.min.js',
			[],
			CFKEF_PLUGIN_VERSION,
			false   // false so it goes in <head>
		);

		// wp_register_script( 'ccfef-country-code-script', CFKEF_PLUGIN_URL . 'assets/js/country-code-script.min.js', $dependency_array, CFKEF_PLUGIN_VERSION, true );
		wp_register_script( 'ccfef-country-code-script', CFKEF_PLUGIN_URL . 'assets/js/country-code-script.js', $dependency_array, CFKEF_PLUGIN_VERSION, true );

		wp_localize_script(
			'ccfef-country-code-script',
			'CCFEFCustomData',
			array(
				'pluginDir'      => CFKEF_PLUGIN_URL,
				'geo_lookup_provider'  => get_option( 'cfkef_geo_provider', 'ipapi' ),
				'geo_lookup_key' => get_option('cfkef_country_code_api_key',''),
				'geo_lookup_api_key'   => get_option( 'cfkef_country_code_non_ipapi_api_key', '' ),
				'errorMap'  => $error_map, 
			)
		);
	}
	
	public function submit_validation( $record, $ajax_handler ) {

		if ( false === $this->validate_form ) {


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

			$form_fields = $form_settings['form_fields'];


			foreach($form_fields as $fields){


				if($fields["field_type"] == 'tel' && $fields["ccfef-country-code-field"] == 'yes'){
					$field_id = $fields["custom_id"];


					foreach($raw_fields as $fields){


						if($fields['id'] == $field_id){

							if(!empty($fields['value'])){

								if (!preg_match('/^\+/', $fields['value'])) {
									$ajax_handler->add_error(
										$field_id,
										esc_html__( 'country code missing!', 'cool-formkit' )
									);
								}else{
									if (preg_match_all('/\+/', $fields['value'], $matches) > 1) {
										$ajax_handler->add_error(
											$field_id,
											esc_html__( 'Invalid Number!', 'cool-formkit' )
										);
									}
								}
							}

						}

					}
				}
			}

		}

		$this->validate_form = true;

	}

	public function elementor_form_tel_field_rendering( $item, $item_index, $form ) {

		if ( 'tel' === $item['field_type'] && 'yes' === $item['ccfef-country-code-field'] ) {
						// Get and sanitize the default country.
						$default_country = $item['ccfef-country-code-default'];
						if ( preg_match( '/[^a-zA-Z]/', $default_country ) ) {
							$default_country = 'NAN';
						}
						
						$include_countries  = $item['ccfef-country-code-include'];
						$excluded_countries = $item['ccfef-country-code-exclude'];
						$auto_detect_country = $item['ccfef-country-code-auto-detect'];
						$prefer_countries = $item['ccfef-country-code-prefer'];
						$dial_code_visibility = $item['ccfef-dial-code-visibility'];
						$strict_mode = $item['ccfef-strict-mode'];
						$internationalisation = $item['ccfef-country-internationalisation'];
						$show_flags = $item['ccfef-show-flags'];

						
						if ( is_string( $prefer_countries ) ) {
							$prefer_countries = array_map( 'trim', explode( ',', $prefer_countries ) );
						}
						$prefer_countries_str = implode( ',', $prefer_countries );

					
						// Convert comma-separated strings to arrays if needed.
						if ( is_string( $include_countries ) ) {
							$include_countries = array_map( 'trim', explode( ',', $include_countries ) );
						}
						if ( is_string( $excluded_countries ) ) {
							$excluded_countries = array_map( 'trim', explode( ',', $excluded_countries ) );
						}
						
						// --- Added code to set data-common-countries ---
						$include_countries_orig  = $include_countries;
						$excluded_countries_orig = $excluded_countries;
						sort( $include_countries_orig );
						sort( $excluded_countries_orig );
						$commonAttr = ( $include_countries_orig === $excluded_countries_orig ) ? 'same' : '';
						// --- End of added code ---
					
						// Convert the include countries array back to a comma-separated string for the data attribute.
						$include_countries_str = implode( ',', $include_countries );
											
						echo '<span class="ccfef-editor-intl-input" data-id="form-field-' . esc_attr( $item['custom_id'] ) . '" data-field-id="' . esc_attr( $item['_id'] ) . '" data-default-country="' . esc_attr( $default_country ) . '" data-include-countries="' . esc_attr( $include_countries_str ) . '" data-exclude-countries="' . esc_attr( implode( ',', $excluded_countries ) ) . '" data-common-countries="' . esc_attr( $commonAttr ) . '" data-prefer-countries="' . esc_attr( $prefer_countries_str ) . '" data-auto-detect-country="'.esc_attr($auto_detect_country).'" data-strict-mode="'.esc_attr($strict_mode).'" data-internationalisation="'.esc_attr($internationalisation).'"
						data-show-flags="'.esc_attr($show_flags).'" data-dial-code-visibility="' . esc_attr( $dial_code_visibility ) . '" style="display: none;"></span>';

						$this->register_common_assets();
		}
	}


	public function editor_inline_JS() {
		// wp_enqueue_script( 'ccfef-country-code-editor-script', CFKEF_PLUGIN_URL . 'assets/js/ccfef-editor.min.js', array(), CFKEF_PLUGIN_VERSION, true ); // for AOS animation
		wp_enqueue_script( 'ccfef-country-code-editor-script', CFKEF_PLUGIN_URL . 'assets/js/ccfef-editor.js', array(), CFKEF_PLUGIN_VERSION, true ); // for AOS animation
		$this->register_common_assets();
	}

	/**
	 * Register common assets for the plugin.
	 */
	public function register_common_assets() {
		if ( ! wp_script_is( 'ccfef-country-code-library-script', 'enqueued' ) ) {
			wp_enqueue_script( 'ccfef-country-code-library-script' );
		}
		wp_enqueue_script( 'ccfef-country-code-script' );
		wp_enqueue_style( 'ccfef-country-code-library-style' );
		
		if ( get_option( 'cfefp_cdn_image' ) ) {
			$inline_css = '
			.cfefp-intl-container .iti__country-container .iti__flag:not(.iti__globe)  {
				background-image: url("'.esc_url("https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/23.8.1/img/flags@2x.png").'");
			}';
			wp_add_inline_style( 'ccfef-country-code-library-style', $inline_css );
		}

		wp_enqueue_style( 'ccfef-country-code-style' );
	}

	/**
	 * Update form widget controls to include the country code control in tel field.
	 *
	 * Adds country code control to allow users to customize the country code field.
	 *
	 * @since 1.0.0
	 * @access public
	 * @param \Elementor\Widget_Base $widget The form widget instance.
	 * @return void
	 */
	public function update_controls( $widget ) {
		$elementor    = \Elementor\Plugin::instance();
		$control_data = $elementor->controls_manager->get_control_from_stack( $widget->get_unique_name(), 'form_fields' );
		if ( is_wp_error( $control_data ) ) {
				return;
		}

		$ccfef_auto_detect_desc = sprintf(
			'%s - <a href="admin.php?page=cool-formkit&tab=settings" target="__blank">%s</a> %s.',
			esc_html__( 'Auto select user country using ipapi.co', 'cool-formkit' ),
			esc_html__( 'Add API key', 'cool-formkit' ),
			esc_html__( 'to use it', 'cool-formkit' ),
		);

		$ccfef_include_desc = sprintf(
			'%s - <b>%s</b>,<b>%s</b>,<b>%s</b>,<b>%s</b>',
			esc_html__( 'Display only these countries, add comma separated', 'cool-formkit' ),
			esc_html__( 'ca', 'cool-formkit' ),
			esc_html__( 'in', 'cool-formkit' ),
			esc_html__( 'us', 'cool-formkit' ),
			esc_html__( 'gb', 'cool-formkit' ),
		);

		$ccfef_exclude_desc = sprintf(
			'%s - <b>%s</b>,<b>%s</b>',
			esc_html__( 'Exclude some countries, add comma separated', 'cool-formkit' ),
			esc_html__( 'af', 'cool-formkit' ),
			esc_html__( 'pk', 'cool-formkit' ),
		);

		$ccfef_prefer_desc = sprintf(
			'%s - <b>%s</b>,<b>%s</b><br><br>%s - <a target="__blank" href="' . esc_url( 'https://www.iban.com/country-codes' ) . '">https://www.iban.com/country-codes</a>',
			esc_html__( 'These countries will appear at the top of the list', 'cool-formkit' ),
			esc_html__( 'in', 'cool-formkit' ),
			esc_html__( 'us', 'cool-formkit' ),
			esc_html__( 'Check country codes alpha-2 list here', 'cool-formkit' ),
		);

		$ccfef_strict_mode = sprintf(
			'%s',
			esc_html__( 'As the user types in the input, ignore any irrelevant characters. Basically, the user can only enter numeric characters, and an optional plus at the beginning. Cap the length at the maximum valid number length.', 'cool-formkit' ),
		);

		$field_controls = array(
			'ccfef-country-code-field'       => array(
				'name'         => 'ccfef-country-code-field',
				'label'        => esc_html__( 'Country Code', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Show', 'cool-formkit' ),
				'label_off'    => esc_html__( 'Hide', 'cool-formkit' ),
				'return_value' => 'yes',
				'default'      => 'no',
				'condition'    => array(
					'field_type' => 'tel',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
			),

			'ccfef-country-code-default'     => array(
				'name'         => 'ccfef-country-code-default',
				'label'        => esc_html__( 'Default Country', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				'condition'    => array(
					'field_type'               => 'tel',
					'ccfef-country-code-field' => 'yes',
				),
				'default'      => 'us',
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),

			'ccfef-country-code-auto-detect' => array(
				'name'         => 'ccfef-country-code-auto-detect',
				'label'        => esc_html__( 'Auto Detect Country', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'cool-formkit' ),
				'label_off'    => esc_html__( 'No', 'cool-formkit' ),
				'return_value' => 'yes',
				'default'      => 'no',
				'description'  => $ccfef_auto_detect_desc,
				'condition'    => array(
					'field_type'               => 'tel',
					'ccfef-country-code-field' => 'yes',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),

			'ccfef-country-code-include'     => array(
				'name'         => 'ccfef-country-code-include',
				'label'        => esc_html__( 'Only Countries', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				// 'placeholder'  => esc_html__( 'Only countries, separated by commas', 'cool-formkit' ),
				'description'  => $ccfef_include_desc,
				'condition'    => array(
					'field_type'               => 'tel',
					'ccfef-country-code-field' => 'yes',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
			'ccfef-country-code-exclude'     => array(
				'name'         => 'ccfef-country-code-exclude',
				'label'        => esc_html__( 'Exclude Countries', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				'description'  => $ccfef_exclude_desc,
				'condition'    => array(
					'field_type'               => 'tel',
					'ccfef-country-code-field' => 'yes',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),

			'ccfef-country-code-prefer'      => array(
				'name'         => 'ccfef-country-code-prefer',
				'label'        => esc_html__( 'Preferred Countries', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				// 'placeholder'  => esc_html__( 'Preferred countries, separated by commas', 'cool-formkit' ),
				'description'  => $ccfef_prefer_desc,
				'condition'    => array(
					'field_type'               => 'tel',
					'ccfef-country-code-field' => 'yes',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
			'ccfef-dial-code-visibility' => array(
				'name'         => 'ccfef-dial-code-visibility',
				'label'        => esc_html__( 'Dial Code Visibility', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::CHOOSE,
				'options'      => array(
					'show'     => array(
						'title' => esc_html__( 'Show', 'cool-formkit' ),
						'icon'  => 'far fa-eye',
					),
					'hide'     => array(
						'title' => esc_html__( 'Hide', 'cool-formkit' ),
						'icon'  => 'far fa-eye-slash',
					),
					'separate' => array(
						'title' => esc_html__( 'Separate', 'cool-formkit' ),
						'icon'  => 'fas fa-arrows-alt-h',
					),
				),
				'default'      => 'show',
				'condition'    => array(
					'field_type'               => array('tel', 'ehp-tel'),
					'ccfef-country-code-field' => 'yes',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
			'ccfef-strict-mode'      => array(
				'name'         => 'ccfef-strict-mode',
				'label'        => esc_html__( 'Strict Mode', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'cool-formkit' ),
				'label_off'    => esc_html__( 'No', 'cool-formkit' ),
				'return_value' => 'yes',
				'default'      => 'no',
				'description'  => $ccfef_strict_mode,
				'condition'    => array(
					'field_type'               => 'tel',
					'ccfef-country-code-field' => 'yes',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
			'ccfef-country-internationalisation'      => array(
				'name'         => 'ccfef-country-internationalisation',
				'label'        => esc_html__( 'Internationalisation', 'cool-formkit' ),
				'type'        => \Elementor\Controls_Manager::SELECT2,
				'options'     => Module_widgets_Helper::get_countries_list(),
				'condition'    => array(
					'field_type'               => 'tel',
					'ccfef-country-code-field' => 'yes',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
				'label_block' => false,
				'multiple'    => false,
				'default'     => 'en',
			),
			'ccfef-show-flags'      => array(
				'name'         => 'ccfef-show-flags',
				'label'        => esc_html__( 'Show Flags', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'cool-formkit' ),
				'label_off'    => esc_html__( 'No', 'cool-formkit' ),
				'return_value' => 'yes',
				'default'      => 'yes',
				'condition'    => array(
					'field_type'               => 'tel',
					'ccfef-country-code-field' => 'yes',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
		);

		if ( ! get_option( 'cfkef_elementor_notice_dismiss' ) ) {
			$review_nonce = wp_create_nonce( 'cfef_elementor_review' );
			$url          = admin_url( 'admin-ajax.php' );
			$html         = '<div class="cfef_elementor_review_wrapper cfef_custom_html">';
			$html        .=	'<div id="cfef_elementor_review_dismiss" data-url="' . esc_url( $url ) . '" data-nonce="' . esc_attr( $review_nonce ) . '">Close Notice X</div>
							<div class="cfef_elementor_review_msg">Hope this addon solved your problem! <br><a href="https://wordpress.org/support/plugin/country-code-field-for-elementor-form/reviews/#new-post" target="_blank"">Share the love with a ⭐⭐⭐⭐⭐ rating.</a><br><br></div>
							<div class="cfef_elementor_demo_btn"><a href="https://wordpress.org/support/plugin/country-code-field-for-elementor-form/reviews/#new-post" target="_blank">Submit Review</a></div>
							</div>';

			$field_controls['cfkef_countary_box'] = array(
				'name'            => 'cfkef_countary_box',
				'type'            => \Elementor\Controls_Manager::RAW_HTML,
				'raw'             => $html,
				'content_classes' => 'cfef_elementor_review_notice',
				'tab'             => 'content',
				'condition'       => array(
					'field_type' => 'tel'
				),
				'inner_tab'       => 'form_fields_content_tab',
				'tabs_wrapper'    => 'form_fields_tabs',
			);
		}

		$control_data['fields'] = \array_merge( $control_data['fields'], $field_controls );
		$widget->update_control( 'form_fields', $control_data );
	}

	// Elementor Review notice ajax request function
	public function cfef_elementor_review_notice() {
		
		if ( ! check_ajax_referer( 'cfef_elementor_review', 'nonce', false ) ) {
			wp_send_json_error( __( 'Invalid security token sent.', 'cool-formkit' ) );
			wp_die( '0', 400 );
		}

		if ( isset( $_POST['cfef_notice_dismiss'] ) && 'true' === $_POST['cfef_notice_dismiss'] ) {
			update_option( 'cfkef_elementor_notice_dismiss', 'yes' );
		}
		exit;
	}
}
}