<?php
namespace Cool_FormKit_Pro\Widgets\Addons;

use Cool_FormKit_Pro\Modules\Forms\Fields\Field_Base;

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

if(!class_exists('CoolForm_Cfkef_Country_Field')) {	
class CoolForm_Cfkef_Country_Field extends Field_Base {

	private $validate_form = false;


	public $depended_scripts = array(
		'coolform-intlTelInput-cdn-js',
		'coolform-country-field-script',
	);

	public $depended_styles = array(
		'coolform-intlTelInput-cdn-css',
		'coolform-defaultcustom',
		'coolform-country-field-css',
	);

	public function get_type() {
		return 'country';
	}

	public function get_name() {
		return __( 'Country', 'cool-formkit' );
	}

	public function validation( $field, $record, $ajax_handler ) {

		if ( empty( $field['value'] ) && ! $field['required'] ) {
			return;
		}

		if ( $field['required'] && empty( $field['value'] ) ) {
			$ajax_handler->add_error(
				$field['id'],
				esc_html__( 'This field is required.', 'cool-formkit' )
			);
		}

		$form_settings = $record->get( 'form_settings' );
		// each field’s config is in the ['form_fields'] sub-array
		$fields_config = $form_settings['form_fields'] ?? [];
		// find the config for the field we’re validating
		$i18n_val = '';
		foreach ( $fields_config as $config ) {
			if ( isset( $config['custom_id'] ) && $config['custom_id'] === $field['id'] ) {
				// cfef-country-internationalisation is the name you gave in the form builder
				$i18n_val = $config['cfef-country-internationalisation'] ?? '';
				break;
			}
		}
		
		if($i18n_val === 'en'){
			if ( ! empty( $field['value'] ) && ! preg_match( '/^[\p{L}\s\-\.\&\'’\(\)]+$/u', $field['value'] )) {
				$ajax_handler->add_error(
					$field['id'],
					esc_html__( 'The field should only contain alphabet letters.', 'cool-formkit' )
				);
			}
		}

		if ( ! empty( $field['value'] ) && ! preg_match( '/^[\p{L}\s\-\.\&\'’\(\)]+$/u', $field['value'] ) ) {
			$ajax_handler->add_error(
				$field['id'],
				esc_html__( 'The field should only contain alphabet letters.', 'cool-formkit' )
			);
		}

	}

	/**
	 * @param      $item
	 * @param      $item_index
	 * @param Form       $form
	 */

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

		$form->add_render_attribute(
			'input' . $item_index,
			array(
				'class' => esc_attr( 'elementor-country-field elementor-field-textual ' . $item['custom_id'] ),
			)
		);
		
		$default_country      = $item['cfef-default'];
		$include_countries    = $item['cfef-include'];
		$excluded_countries   = $item['cfef-exclude'];
		$preferred_countries  = $item['cfef-preferred'];
		$auto_detect_country  = $item['cfef-auto-detect-country'];
		$internationalisation = $item['cfef-country-internationalisation'];
		$show_flags           = $item['cfef-show-flags'];
		$commonCountries      = '';

		if ( ! empty( $include_countries ) && ! empty( $excluded_countries ) ) {
			$include_array     = array_map( 'trim', explode( ',', $include_countries ) );
			$exclude_array     = array_map( 'trim', explode( ',', $excluded_countries ) );
			$intersectionArray = array_intersect( $include_array, $exclude_array );
			$commonCountries   = implode( ',', $intersectionArray );
			$filtered_include  = array_diff( $include_array, $exclude_array );
			$include_countries = implode( ',', $filtered_include );
		}
		?>
		<label class="cool-form-text mdc-text-field mdc-text-field--outlined mdc-text-field--with-trailing-icon mdc-text-field--no-label cool-field-size-<?php echo esc_attr( $form->get_settings( 'input_size' ) ); ?>">
			<span class="mdc-notched-outline">
				<span class="mdc-notched-outline__leading"></span>
				<span class="mdc-notched-outline__notch"></span>
				<span class="mdc-notched-outline__trailing"></span>
			</span>
			<input
				type="country"
				id="form-field-<?php echo esc_attr( $item['custom_id'] ); ?>"
				name="form_fields[<?php echo esc_attr( $item['custom_id'] ); ?>]"
				class="mdc-text-field__input cool-form__field <?php echo esc_attr( $item['custom_id'] ); ?>"
				title="<?php esc_attr_e( 'Country name', 'cool-formkit' ); ?>"
				<?php echo $form->get_render_attribute_string( 'input' . $item_index ); ?>
			>
			<i aria-hidden="true" class="material-icons mdc-text-field__icon mdc-text-field__icon--trailing cool-country-error-icon" style="display:none">error</i>
		</label>
		<div class="mdc-text-field-helper-line">
			<div class="mdc-text-field-helper-text" id="cool-country-error" aria-hidden="true"></div>
		</div>
		<span
			class="cfef-editor-intl-input"
			data-id="form-field-<?php echo esc_attr( $item['custom_id'] ); ?>"
			data-field-id="<?php echo esc_attr( $item['_id'] ); ?>"
			data-default-country="<?php echo esc_attr( $default_country ); ?>"
			data-include-countries="<?php echo esc_attr( $include_countries ); ?>"
			data-exclude-countries="<?php echo esc_attr( $excluded_countries ); ?>"
			data-preferred-countries="<?php echo esc_attr( $preferred_countries ); ?>"
			data-auto-detect-country="<?php echo esc_attr( $auto_detect_country ); ?>"
			data-common-countries="<?php echo esc_attr( $commonCountries ); ?>"
			data-internationalisation="<?php echo esc_attr( $internationalisation ); ?>"
			data-show-flags="<?php echo esc_attr( $show_flags ); ?>"
			style="display: none;"
		></span>
		<?php
	}
	

	public function __construct() {
		parent::__construct();
		require_once CFKEF_PLUGIN_DIR . 'includes/frontend/widgets/module-widgets-helper.php';
		add_action( 'wp_enqueue_scripts', array( $this, 'add_assets_files' ) );
		add_action( 'elementor/preview/init', array( $this, 'editor_preview_footer' ) );
		add_action( 'elementor/editor/before_enqueue_scripts', array( $this, 'add_editor_js' ) );

	}

	/**
     * Get script dependencies for this field.
     *
     * @return array
     */
    public function get_script_depends() : array {
        return $this->depended_scripts;
    }

	/**
     * Get style dependencies for this field.
     *
     * @return array
     */
    public function get_style_depends() : array {
        return $this->depended_styles;
    }

	/**
	 * Register common assets for the plugin.
	 */
	public function add_assets_files() {
		$js_common_dep = array( 'jquery', 'coolform-intlTelInput-cdn-js', 'elementor-frontend','coolform-translations' );
        if ( ! \Elementor\Plugin::$instance->preview->is_preview_mode() && is_user_logged_in() ) {
            $js_common_dep = array_merge(array( 'elementor-common' ), $js_common_dep);
        }

		wp_register_script(
			'coolform-translations',
			CFKEF_PLUGIN_URL . 'assets/js/ccfef-translations.min.js',
			[],
			CFKEF_PLUGIN_VERSION,
			false   // false so it goes in <head>
		);
		wp_register_script( 'coolform-country-field-script', CFKEF_PLUGIN_URL . 'assets/addons/js/coolform-country-field-script.js', $js_common_dep, CFKEF_PLUGIN_VERSION, true );
		wp_register_script( 'coolform-intlTelInput-cdn-js', CFKEF_PLUGIN_URL . 'assets/js/intlTelInput.js', CFKEF_PLUGIN_VERSION, 'all' );
		// wp_register_script( 'coolform-intlTelInput-cdn-js', CFKEF_PLUGIN_URL . 'assets/js/intlTelInput.min.js', CFKEF_PLUGIN_VERSION, 'all' );
		wp_register_style( 'coolform-intlTelInput-cdn-css', CFKEF_PLUGIN_URL . 'assets/css/intlTelInput.min.css', CFKEF_PLUGIN_VERSION, 'all' );
		wp_register_style( 'coolform-defaultcustom', CFKEF_PLUGIN_URL . 'assets/css/intl_panel.min.css', CFKEF_PLUGIN_VERSION, true );
		wp_register_style( 'coolform-country-field-css', CFKEF_PLUGIN_URL . 'assets/addons/css/coolform-country-field.css', CFKEF_PLUGIN_VERSION, true );

		wp_localize_script(
			'coolform-country-field-script',
			'CYFEFCustomData',
			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', '' ),
			)
		);
	}

	public function add_editor_js() {
			wp_enqueue_style( 'coolform-editorcustom', CFKEF_PLUGIN_URL . 'assets/css/cfef-editor.css', CFKEF_PLUGIN_VERSION, true );
	}

	public function editor_preview_footer() {
			add_action( 'wp_footer', array( $this, 'content_template_script' ) );
	}

	public function content_template_script() {
		?>
		<script>
		jQuery(document).ready(() => {

			elementor.hooks.addFilter(
				'cool_formkit/forms/content_template/field/<?php echo esc_attr( $this->get_type() ); ?>',
				function (inputField, item, i) {
					let intersectionArray;
					let commonCountries = '';

					const default_country = item['cfef-default'] || '';
					let include_countries = item['cfef-include'] || '';
					const excluded_countries = item['cfef-exclude'] || '';
					const preferred_countries = item['cfef-preferred'] || '';
					const auto_detect_country = item['cfef-auto-detect-country'] || '';
					const Internationalisation = item['cfef-country-internationalisation'] || '';
					const showFlags = item['cfef-show-flags'] || '';

					if (include_countries && excluded_countries) {
						let includeArray = include_countries.split(',').map(c => c.trim());
						const excludeArray = excluded_countries.split(',').map(c => c.trim());

						intersectionArray = includeArray.filter(c => excludeArray.includes(c));
						commonCountries = intersectionArray.join(',');

						includeArray = includeArray.filter(c => !excludeArray.includes(c));
						include_countries = includeArray.join(',');
					}

					const fieldType = 'country';
					const fieldId = `form-field-${item.custom_id}`;
					const fieldClass = `mdc-text-field__input elementor-field-textual ${item.css_classes} ${item.custom_id}`;
					const inputSize = item.input_size || 'medium';

					return `
					<label class="cool-form-text mdc-text-field mdc-text-field--outlined mdc-text-field--with-trailing-icon mdc-text-field--no-label cool-field-size-${inputSize}">
						<span class="mdc-notched-outline">
							<span class="mdc-notched-outline__leading"></span>
							<span class="mdc-notched-outline__notch"></span>
							<span class="mdc-notched-outline__trailing"></span>
						</span>
						<input type="${fieldType}" id="${fieldId}" class="${fieldClass}" title="<?php echo esc_html__( 'Country name', 'cool-formkit' ); ?>"
						name="form_fields[${item.custom_id}]">
						<i aria-hidden="true" class="material-icons mdc-text-field__icon mdc-text-field__icon--trailing cool-country-error-icon" style="display:none">error</i>
					</label>
					<div class="mdc-text-field-helper-line">
						<div class="mdc-text-field-helper-text" id="cool-country-error" aria-hidden="true"></div>
					</div>
					<span
						class="cfef-editor-intl-input"
						data-id="${fieldId}"
						data-field-id="${item['_id']}"
						data-default-country="${default_country}"
						data-include-countries="${include_countries}"
						data-exclude-countries="${excluded_countries}"
						data-preferred-countries="${preferred_countries}"
						data-auto-detect-country="${auto_detect_country}"
						data-common-countries="${commonCountries}"
						data-internationalisation="${Internationalisation}"
						data-show-flags="${showFlags}"
						style="display: none;"
					></span>`;
				},
				10,
				3
			);

		});
		</script>
		<?php
	}



	/**
	 * Update form widget controls to include the country field control.
	 *
	 * Adds country field control to allow users to customize the country 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' ),
		);

		$field_controls = array(
			'cfef-default'             => array(
				'name'         => 'cfef-default',
				'label'        => esc_html__( 'Default Country', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				'condition'    => array(
					'field_type' => 'country',
				),
				'default'      => 'us',
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
			'cfef-auto-detect-country' => array(
				'name'         => 'cfef-auto-detect-country',
				'label'        => esc_html__( 'Auto Detect Country', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'On', 'cool-formkit' ),
				'label_off'    => esc_html__( 'Off', 'cool-formkit' ),
				'return_value' => 'yes',
				'default'      => 'no',
				'description'  => $ccfef_auto_detect_desc,
				'condition'    => array(
					'field_type' => 'country',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
			'cfef-include'             => array(
				'name'         => 'cfef-include',
				'label'        => esc_html__( 'Only Countries', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				'description'  => $ccfef_include_desc,
				'condition'    => array(
					'field_type' => 'country',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
			'cfef-exclude'             => array(
				'name'         => 'cfef-exclude',
				'label'        => esc_html__( 'Exclude Countries', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				'description'  => $ccfef_exclude_desc,
				'condition'    => array(
					'field_type' => 'country',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
			'cfef-preferred'           => array(
				'name'         => 'cfef-preferred',
				'label'        => esc_html__( 'Preferred Countries', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				'description'  => $ccfef_prefer_desc,
				'condition'    => array(
					'field_type' => 'country',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
			'cfef-country-internationalisation'      => array(
				'name'         => 'cfef-country-internationalisation',
				'label'        => esc_html__( 'Internationalisation', 'cool-formkit' ),
				'type'        => \Elementor\Controls_Manager::SELECT2,
				'options'     => \Module_widgets_Helper::get_countries_list(),
				'condition'    => array(
					'field_type' => 'country',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
				'label_block' => false,
				'multiple'    => false,
				'default'     => 'en',
			),
			'cfef-show-flags'      => array(
				'name'         => 'cfef-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' => 'country',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
		);

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