<?php

namespace HulkPlugins\ElementorPro\Forms\AdvancedFields\Utils;

use Elementor\Core\Utils\Svg\Svg_Sanitizer;
use Elementor\Icons_Manager;
use Elementor\Utils;

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

class Helper {

	/**
	 * Get elementor icon
	 * @param array $icon
	 *
	 * @return string
	 */
	public static function getIcon( array $icon ): string {
		ob_start();
		Icons_Manager::render_icon( $icon, [ 'aria-hidden' => 'true' ] );
		$data = (string) ob_get_clean();
		return rawurlencode( $data );
	}

	/**
	 * Check array of values in options
	 * @param array $options
	 * @param array $values
	 *
	 * @return array
	 */
	public static function checkValuesInOptions( array $options, array $values ): array {
		$results = [];
		foreach ( $values as $val ) {
			$found = false;
			foreach ( $options as $option ) {
				if ( strcasecmp( $option['value'], $val ) === 0 || strcasecmp( $option['label'], $val ) === 0 ) {
					$found = true;
					break;
				}
			}
			$results[ $val ] = $found;
		}

		return $results;
	}

	/**
	 * Filters a nested array to include only items with unique slugs.
	 *
	 * @param array $data The input array with nested items containing a 'slug' key.
	 * @return array The filtered array with only unique slugs.
	 */
	public static function getUniqueBySlug( array $data ): array {
		$seen = [];
		$uniqueData = [];

		foreach ( $data as $item ) {
			$slug = trim( $item['slug'] );
			if ( ! in_array( $slug, $seen, true ) ) {
				$seen[] = $slug;
				$uniqueData[] = $item;
			}
		}

		return $uniqueData;
	}

	/**
	 * Allowed avg tags
	 * @return array
	 */
	public static function getAllowedSvgTags(): array {
		return [
			'svg'            => [
				'xmlns'       => true,
				'width'       => true,
				'height'      => true,
				'aria-hidden' => true,
				'viewbox'     => true,
				'fill'        => true,
				'style'       => true,
				'class'       => true,
				'id'          => true,
			],
			'g'              => [
				'id'    => true,
				'class' => true,
				'style' => true,
			],
			'defs'           => [],
			'linearGradient' => [
				'id' => true,
				'x1' => true,
				'x2' => true,
				'y1' => true,
				'y2' => true,
			],
			'radialGradient' => [
				'id' => true,
				'cx' => true,
				'cy' => true,
				'r'  => true,
				'fx' => true,
				'fy' => true,
			],
			'stop'           => [
				'offset'       => true,
				'stop-color'   => true,
				'stop-opacity' => true,
			],
			'path'           => [
				'd'            => true,
				'fill'         => true,
				'fill-rule'    => true,
				'stroke'       => true,
				'stroke-width' => true,
				'opacity'      => true,
			],
			'circle'         => [
				'cx'           => true,
				'cy'           => true,
				'r'            => true,
				'fill'         => true,
				'stroke'       => true,
				'stroke-width' => true,
				'opacity'      => true,
			],
			'rect'           => [
				'x'            => true,
				'y'            => true,
				'width'        => true,
				'height'       => true,
				'fill'         => true,
				'stroke'       => true,
				'stroke-width' => true,
				'opacity'      => true,
			],
			'ellipse'        => [
				'cx'           => true,
				'cy'           => true,
				'rx'           => true,
				'ry'           => true,
				'fill'         => true,
				'stroke'       => true,
				'stroke-width' => true,
				'opacity'      => true,
			],
			'line'           => [
				'x1'           => true,
				'y1'           => true,
				'x2'           => true,
				'y2'           => true,
				'stroke'       => true,
				'stroke-width' => true,
			],
			'polyline'       => [
				'points'       => true,
				'fill'         => true,
				'stroke'       => true,
				'stroke-width' => true,
			],
			'polygon'        => [
				'points'       => true,
				'fill'         => true,
				'stroke'       => true,
				'stroke-width' => true,
			],
			'text'           => [
				'x'           => true,
				'y'           => true,
				'fill'        => true,
				'font-family' => true,
				'font-size'   => true,
				'text-anchor' => true,
				'opacity'     => true,
			],
			'tspan'          => [
				'x'           => true,
				'y'           => true,
				'fill'        => true,
				'font-family' => true,
				'font-size'   => true,
				'opacity'     => true,
			],
		];
	}

	/**
	 * Get list of countries
	 * @return array
	 */
	public static function getCountries(): array {
		return [
			'af' => 'Afghanistan',
			'al' => 'Albania',
			'dz' => 'Algeria',
			'as' => 'American Samoa',
			'ad' => 'Andorra',
			'ao' => 'Angola',
			'ai' => 'Anguilla',
			'ag' => 'Antigua &amp; Barbuda',
			'ar' => 'Argentina',
			'am' => 'Armenia',
			'aw' => 'Aruba',
			'ac' => 'Ascension Island',
			'au' => 'Australia',
			'at' => 'Austria',
			'az' => 'Azerbaijan',
			'bs' => 'Bahamas',
			'bh' => 'Bahrain',
			'bd' => 'Bangladesh',
			'bb' => 'Barbados',
			'by' => 'Belarus',
			'be' => 'Belgium',
			'bz' => 'Belize',
			'bj' => 'Benin',
			'bm' => 'Bermuda',
			'bt' => 'Bhutan',
			'bo' => 'Bolivia',
			'ba' => 'Bosnia &amp; Herzegovina',
			'bw' => 'Botswana',
			'br' => 'Brazil',
			'io' => 'British Indian Ocean Territory',
			'vg' => 'British Virgin Islands',
			'bn' => 'Brunei',
			'bg' => 'Bulgaria',
			'bf' => 'Burkina Faso',
			'bi' => 'Burundi',
			'kh' => 'Cambodia',
			'cm' => 'Cameroon',
			'ca' => 'Canada',
			'cv' => 'Cape Verde',
			'bq' => 'Caribbean Netherlands',
			'ky' => 'Cayman Islands',
			'cf' => 'Central African Republic',
			'td' => 'Chad',
			'cl' => 'Chile',
			'cn' => 'China',
			'cx' => 'Christmas Island',
			'cc' => 'Cocos (Keeling) Islands',
			'co' => 'Colombia',
			'km' => 'Comoros',
			'cg' => 'Congo - Brazzaville',
			'cd' => 'Congo - Kinshasa',
			'ck' => 'Cook Islands',
			'cr' => 'Costa Rica',
			'hr' => 'Croatia',
			'cu' => 'Cuba',
			'cw' => 'Curaçao',
			'cy' => 'Cyprus',
			'cz' => 'Czechia',
			'ci' => 'Côte d’Ivoire',
			'dk' => 'Denmark',
			'dj' => 'Djibouti',
			'dm' => 'Dominica',
			'do' => 'Dominican Republic',
			'ec' => 'Ecuador',
			'eg' => 'Egypt',
			'sv' => 'El Salvador',
			'gq' => 'Equatorial Guinea',
			'er' => 'Eritrea',
			'ee' => 'Estonia',
			'sz' => 'Eswatini',
			'et' => 'Ethiopia',
			'fk' => 'Falkland Islands',
			'fo' => 'Faroe Islands',
			'fj' => 'Fiji',
			'fi' => 'Finland',
			'fr' => 'France',
			'gf' => 'French Guiana',
			'pf' => 'French Polynesia',
			'ga' => 'Gabon',
			'gm' => 'Gambia',
			'ge' => 'Georgia',
			'de' => 'Germany',
			'gh' => 'Ghana',
			'gi' => 'Gibraltar',
			'gr' => 'Greece',
			'gl' => 'Greenland',
			'gd' => 'Grenada',
			'gp' => 'Guadeloupe',
			'gu' => 'Guam',
			'gt' => 'Guatemala',
			'gg' => 'Guernsey',
			'gn' => 'Guinea',
			'gw' => 'Guinea-Bissau',
			'gy' => 'Guyana',
			'ht' => 'Haiti',
			'hn' => 'Honduras',
			'hk' => 'Hong Kong SAR China',
			'hu' => 'Hungary',
			'is' => 'Iceland',
			'in' => 'India',
			'id' => 'Indonesia',
			'ir' => 'Iran',
			'iq' => 'Iraq',
			'ie' => 'Ireland',
			'im' => 'Isle of Man',
			'il' => 'Israel',
			'it' => 'Italy',
			'jm' => 'Jamaica',
			'jp' => 'Japan',
			'je' => 'Jersey',
			'jo' => 'Jordan',
			'kz' => 'Kazakhstan',
			'ke' => 'Kenya',
			'ki' => 'Kiribati',
			'xk' => 'Kosovo',
			'kw' => 'Kuwait',
			'kg' => 'Kyrgyzstan',
			'la' => 'Laos',
			'lv' => 'Latvia',
			'lb' => 'Lebanon',
			'ls' => 'Lesotho',
			'lr' => 'Liberia',
			'ly' => 'Libya',
			'li' => 'Liechtenstein',
			'lt' => 'Lithuania',
			'lu' => 'Luxembourg',
			'mo' => 'Macao SAR China',
			'mg' => 'Madagascar',
			'mw' => 'Malawi',
			'my' => 'Malaysia',
			'mv' => 'Maldives',
			'ml' => 'Mali',
			'mt' => 'Malta',
			'mh' => 'Marshall Islands',
			'mq' => 'Martinique',
			'mr' => 'Mauritania',
			'mu' => 'Mauritius',
			'yt' => 'Mayotte',
			'mx' => 'Mexico',
			'fm' => 'Micronesia',
			'md' => 'Moldova',
			'mc' => 'Monaco',
			'mn' => 'Mongolia',
			'me' => 'Montenegro',
			'ms' => 'Montserrat',
			'ma' => 'Morocco',
			'mz' => 'Mozambique',
			'mm' => 'Myanmar (Burma)',
			'na' => 'Namibia',
			'nr' => 'Nauru',
			'np' => 'Nepal',
			'nl' => 'Netherlands',
			'nc' => 'New Caledonia',
			'nz' => 'New Zealand',
			'ni' => 'Nicaragua',
			'ne' => 'Niger',
			'ng' => 'Nigeria',
			'nu' => 'Niue',
			'nf' => 'Norfolk Island',
			'kp' => 'North Korea',
			'mk' => 'North Macedonia',
			'mp' => 'Northern Mariana Islands',
			'no' => 'Norway',
			'om' => 'Oman',
			'pk' => 'Pakistan',
			'pw' => 'Palau',
			'ps' => 'Palestinian Territories',
			'pa' => 'Panama',
			'pg' => 'Papua New Guinea',
			'py' => 'Paraguay',
			'pe' => 'Peru',
			'ph' => 'Philippines',
			'pl' => 'Poland',
			'pt' => 'Portugal',
			'pr' => 'Puerto Rico',
			'qa' => 'Qatar',
			'ro' => 'Romania',
			'ru' => 'Russia',
			'rw' => 'Rwanda',
			're' => 'Réunion',
			'ws' => 'Samoa',
			'sm' => 'San Marino',
			'sa' => 'Saudi Arabia',
			'sn' => 'Senegal',
			'rs' => 'Serbia',
			'sc' => 'Seychelles',
			'sl' => 'Sierra Leone',
			'sg' => 'Singapore',
			'sx' => 'Sint Maarten',
			'sk' => 'Slovakia',
			'si' => 'Slovenia',
			'sb' => 'Solomon Islands',
			'so' => 'Somalia',
			'za' => 'South Africa',
			'kr' => 'South Korea',
			'ss' => 'South Sudan',
			'es' => 'Spain',
			'lk' => 'Sri Lanka',
			'bl' => 'St. Barthélemy',
			'sh' => 'St. Helena',
			'kn' => 'St. Kitts &amp; Nevis',
			'lc' => 'St. Lucia',
			'mf' => 'St. Martin',
			'pm' => 'St. Pierre &amp; Miquelon',
			'vc' => 'St. Vincent &amp; Grenadines',
			'sd' => 'Sudan',
			'sr' => 'Suriname',
			'sj' => 'Svalbard &amp; Jan Mayen',
			'se' => 'Sweden',
			'ch' => 'Switzerland',
			'sy' => 'Syria',
			'st' => 'São Tomé &amp; Príncipe',
			'tw' => 'Taiwan',
			'tj' => 'Tajikistan',
			'tz' => 'Tanzania',
			'th' => 'Thailand',
			'tl' => 'Timor-Leste',
			'tg' => 'Togo',
			'tk' => 'Tokelau',
			'to' => 'Tonga',
			'tt' => 'Trinidad &amp; Tobago',
			'tn' => 'Tunisia',
			'tr' => 'Turkey',
			'tm' => 'Turkmenistan',
			'tc' => 'Turks &amp; Caicos Islands',
			'tv' => 'Tuvalu',
			'vi' => 'U.S. Virgin Islands',
			'ug' => 'Uganda',
			'ua' => 'Ukraine',
			'ae' => 'United Arab Emirates',
			'gb' => 'United Kingdom',
			'us' => 'United States',
			'uy' => 'Uruguay',
			'uz' => 'Uzbekistan',
			'vu' => 'Vanuatu',
			'va' => 'Vatican City',
			've' => 'Venezuela',
			'vn' => 'Vietnam',
			'wf' => 'Wallis &amp; Futuna',
			'eh' => 'Western Sahara',
			'ye' => 'Yemen',
			'zm' => 'Zambia',
			'zw' => 'Zimbabwe',
			'ax' => 'Åland Islands',
		];
	}

	/**
	 * Get inline svg from svg file
	 * @param string $file
	 *
	 * @return string
	 */
	public static function getInlineSvg( string $file ): string {
		$svg = Utils::file_get_contents( $file );
		$valid_svg = ( new SVG_Sanitizer() )->sanitize( $svg );
		if ( $valid_svg === false ) {
			return '';
		}
		return (string) $valid_svg;
	}

	/**
	 * Get max upload file size in MB
	 * @return float|int
	 */
	public static function getMaxFileUploadSizeInMB() {
		// Get the values from php.ini
		$uploadMaxFileSize = ini_get( 'upload_max_filesize' );
		$postMaxSize = ini_get( 'post_max_size' );

		// Convert values to bytes
		$uploadMaxFileSizeBytes = self::convertToBytes( $uploadMaxFileSize );
		$postMaxSizeBytes = self::convertToBytes( $postMaxSize );

		// Get the minimum of the two limits
		$maxFileUploadBytes = min( $uploadMaxFileSizeBytes, $postMaxSizeBytes );

		// Convert bytes to MB
		return $maxFileUploadBytes / 1024 / 1024;
	}

	public static function convertToBytes( $size ) {
		$unit = strtolower( substr( $size, -1 ) );
		$size = (int)$size;

		switch ( $unit ) {
			case 'g':
                return $size * 1024 * 1024 * 1024;
			case 'm':
                return $size * 1024 * 1024;
			case 'k':
                return $size * 1024;
			default:
                return $size;
		}
	}
}
