<?php
/*
 * @package   plg_radicalmart_cleanphone
 * @version   1.0.0
 * @author    Dmitriy Vasyukov - https://fictionlabs.ru
 * @copyright Copyright (c) 2026 Fictionlabs. All rights reserved.
 * @license   GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
 * @link      https://fictionlabs.ru/
 */

namespace Joomla\Plugin\RadicalMart\CleanPhone\Field;

\defined('_JEXEC') or die;

use Giggsey\Locale\Locale;
use Joomla\CMS\Factory;
use Joomla\CMS\Form\Field\ListField;
use libphonenumber\PhoneNumberUtil;

class CountriesField extends ListField
{
	/**
	 * The form field type.
	 *
	 * @var  string
	 *
	 * @since  1.0.0
	 */
	protected $type = 'phones';

	/**
	 * Field options array.
	 *
	 * @var  array|null
	 *
	 * @since  1.0.0
	 */
	protected ?array $_options = null;

	/**
	 * Method to get the field options.
	 *
	 * @throws  \Exception
	 *
	 * @return  array  The field option objects.
	 *
	 * @since  1.0.0
	 */
	protected function getOptions()
	{
		@include_once(JPATH_PLUGINS . '/radicalmart/cleanphone/libraries/RadicalMart/PhoneNumber/autoload.php');

		if ($this->_options === null)
		{
			$language = Factory::getApplication()->getLanguage();
			$langTag = $language->getTag();
			list($locale,) = explode('-', $langTag);

			$phoneUtil = PhoneNumberUtil::getInstance();
			$regions = $phoneUtil->getSupportedRegions();

			// Prepare options
			$options  = parent::getOptions();
			foreach ($regions as $region)
			{
				// Get the country name in the current locale
			    $countryName = Locale::getDisplayRegion('-' . $region, $locale);

			    // Get the country calling code for the region
			    $callingCode = $phoneUtil->getCountryCodeForRegion($region);

				$option        = new \stdClass();
				$option->value = $region;
				$option->text  = $countryName . ' (+' . $callingCode . ')';

				$options[] = $option;
			}

			usort($options, function($a, $b) {
			    return strcmp($a->text, $b->text);
			});

			$this->_options = $options;
		}

		return $this->_options;
	}
}