<?php

namespace HulkPlugins\ElementorPro\Forms\InternationalTelephoneField\Utils;

use Elementor\Plugin;
use function HulkPlugins\ElementorPro\Forms\InternationalTelephoneField\hulk_epfitf_fs;
use const HulkPlugins\ElementorPro\Forms\InternationalTelephoneField\PLUGIN_DIR_PATH;
use const HulkPlugins\ElementorPro\Forms\InternationalTelephoneField\SETTINGS_URL;

defined( 'ABSPATH' ) || exit;

class Helper {

	private static array $cache = [];

	/**
	 * Get main ID
	 * @return int
	 */
	public static function get_main_id(): int {
		return Plugin::instance()->documents->get_current()->get_main_id();
	}

	/**
	 * Get countries list
	 * @return mixed|null
	 */
	public static function getCountries() {
		if ( empty( self::$cache['countries'] ) ) {
			self::$cache['countries'] = apply_filters(
				'hulk_epfitf_countries',
				require PLUGIN_DIR_PATH . 'includes/countries.php'
			);
		}
		return self::$cache['countries'];
	}

	/**
	 * Get i18n languages list
	 * @return mixed|null
	 */
	public static function getI18nLanguages() {
		if ( empty( self::$cache['i18n'] ) ) {
			self::$cache['i18n'] = apply_filters(
				'hulk_epfitf_i18n',
				require PLUGIN_DIR_PATH . 'includes/i18nLanguages.php'
			);
		}
		return self::$cache['i18n'];
	}

	/**
	 * Notice
	 * @param string $url
	 *
	 * @return string
	 */
	public static function docNoticeControlContent( string $url ): string {
		return sprintf(
		// Translators: %s is the documentation link.
			esc_attr__( 'Not sure how to set this? Check our step by step %s.', 'international-telephone-field-for-elementor-form' ),
			/** @lang text */ '<a href="' . esc_url( $url ) . '" target="_blank">' . esc_attr__( 'documentation', 'international-telephone-field-for-elementor-form' ) . '</a>'
		);
	}

	/**
	 * Check whether is not premium or not paying
	 * @return bool
	 */
	public static function isFsNotice(): bool {
		return ! hulk_epfitf_fs()->can_use_premium_code();
	}

	/**
	 * Freemius Notice
	 * @return string
	 */
	public static function fsNotice(): string {
		$fs = hulk_epfitf_fs();
		if ( ! $fs->is_premium() ) {

			// Adds a direct checkout link in the free version.
			return sprintf(
			/** @lang text */                '%s&nbsp;-&nbsp;<a href="%s" target="_blank">%s</a>',
				esc_attr__( 'To use', 'international-telephone-field-for-elementor-form' ),
				$fs->checkout_url(),
				esc_attr__( 'UNLOCK PRO', 'international-telephone-field-for-elementor-form' )
			);
		}

		if ( $fs->is_not_paying() ) {

			// If not activate free or paid version (License activation screen)
			if ( $fs->is_activation_mode() ) {
				// Adds an activation link
				return sprintf(
				/** @lang text */                    '%s&nbsp;-&nbsp;<a href="%s" target="_blank">%s</a>',
					esc_attr__( 'To use', 'international-telephone-field-for-elementor-form' ),
					$fs->get_activation_url(),
					esc_attr__( 'ACTIVATE NOW', 'international-telephone-field-for-elementor-form' )
				);
			}

			// Adds a upgrade link
			return sprintf(
			/** @lang text */                '%s&nbsp;-&nbsp;<a href="%s" target="_blank">%s</a>',
				esc_attr__( 'To use', 'international-telephone-field-for-elementor-form' ),
				$fs->get_upgrade_url(),
				esc_attr__( 'UPGRADE NOW!', 'international-telephone-field-for-elementor-form' )
			);
		}

		return '';
	}

	/**
	 * Todo: not using
	 * @return string
	 */
	public static function fsFieldNotice(): string {
		return sprintf(
			wp_kses_post(
			// translators: 1: license upgrade URL, 2: link text, 3: plugin name.
				__( /** @lang text */ 'Your license for <strong>%2$s</strong> is <strong>inactive or expired</strong>. Please <a href="%1$s">renew or upgrade your license</a> to continue receiving updates and support.', 'international-telephone-field-for-elementor-form' )
			),
			esc_url( SETTINGS_URL ),
			esc_html( hulk_epfitf_fs()->get_plugin_name() )
		);
	}

	/**
	 * Get field classes
	 * @param $item
	 *
	 * @return array
	 */
	public static function get_attribute_class( $item ): array {
		return [
			'elementor-field',
			'elementor-size-' . $item['input_size'],
			empty( $item['css_classes'] ) ? '' : esc_attr( $item['css_classes'] ),
			'elementor-field-textual',
		];
	}

	/**
	 * Get field class string
	 * @param $item
	 *
	 * @return string
	 */
	public static function get_attribute_class_string( $item ): string {
		return implode( ' ', self::get_attribute_class( $item ) );
	}

	/**
	 * Get error messages
	 * @return array
	 */
	public static function getErrorMessages(): array {
		if ( empty( self::$cache['error_messages'] ) ) {
			self::$cache['error_messages'] = [
				'TOO_SHORT'            => esc_attr__( 'The phone number is too short.', 'international-telephone-field-for-elementor-form' ),
				'TOO_LONG'             => esc_attr__( 'The phone number is too long.', 'international-telephone-field-for-elementor-form' ),
				'INVALID_BUT_POSSIBLE' => esc_attr__( 'The phone number is invalid but might still be possible.', 'international-telephone-field-for-elementor-form' ),
				'INVALID_COUNTRY_CODE' => esc_attr__( 'The phone number has an invalid country code.', 'international-telephone-field-for-elementor-form' ),
				'INVALID_LENGTH'       => esc_attr__( 'The phone number has an invalid length.', 'international-telephone-field-for-elementor-form' ),
				'NOT_A_NUMBER'         => esc_attr__( 'The input is not a valid phone number.', 'international-telephone-field-for-elementor-form' ),
				'UNKNOWN'              => esc_attr__( 'Unknown error.', 'international-telephone-field-for-elementor-form' ),
			];
		}
		return self::$cache['error_messages'];
	}

	/**
	 * Sanitizes settings
	 *
	 * @param array $input
	 *
	 * @return array Sanitized associative array
	 */
	public static function sanitizeSettings( array $input ): array {
		$sanitized = [];
		foreach ( $input as $key => $value ) {
			switch ( $key ) {
				case 'required':
				case 'autoCountry':
				case 'showFlags':
				case 'separateDialCode':
				case 'nationalMode':
				case 'strictMode':
				case 'enableValidation':
				case 'customMessages':
				case 'fullPhone':
					$sanitized[ $key ] = filter_var( $value, FILTER_VALIDATE_BOOLEAN );
					break;
				case 'onlyCountries':
				case 'excludeCountries':
					$sanitized[ $key ] = array_map( 'sanitize_text_field', (array) $value );
					break;
				case 'countryOrder':
					$sanitized[ $key ] = self::sanitizeCommaSeperated( $value );
					break;
				default:
					$sanitized[ $key ] = sanitize_text_field( $value );
					break;
			}
		}
		return $sanitized;
	}

	public static function sanitizeCommaSeperated( $value ): array {
		$value = sanitize_text_field( $value );
		$data = explode( ',', $value );
		if ( is_array( $data ) ) {
			$data = array_map( 'trim', $data );
			return array_filter( $data, fn( $item ) => ! empty( $item ) );
		}
		return [];
	}
}
