<?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\Extension;

\defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Form\Form;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\Component\RadicalMart\Administrator\Helper\ParamsHelper;
use Joomla\Event\SubscriberInterface;
use RadicalMart\PhoneNumber\PhoneNumber;

class CleanPhone extends CMSPlugin implements SubscriberInterface
{
	/**
	 * Load the language file on instantiation.
	 *
	 * @var    bool
	 *
	 * @since  1.0.0
	 */
	protected $autoloadLanguage = true;

	/**
	 * Loads the application object.
	 *
	 * @var  \Joomla\CMS\Application\CMSApplication
	 *
	 * @since  1.0.0
	 */
	protected $application = null;

	/**
	 * Returns an array of events this subscriber will listen to.
	 *
	 * @return  array
	 *
	 * @since   1.0.0
	 */
	public static function getSubscribedEvents(): array
	{
		return [
			'onRadicalMartPrepareConfigForm'   => 'onRadicalMartPrepareConfigForm',
			'onRadicalMartPrepareConfigGroups' => 'onRadicalMartPrepareConfigGroups',
			'onRadicalMartCleanPhone'          => 'onRadicalMartCleanPhone'
		];
	}

	/**
	 * Trigger `onRadicalMartPrepareConfigGroups` event.
	 *
	 * @param   array  $groups  Modified groups data.
	 *
	 * @return void
	 */
	public function onRadicalMartPrepareConfigGroups(array &$groups)
	{
		Factory::getApplication()->getLanguage()->load('plg_radicalmart_cleanphone', JPATH_ADMINISTRATOR);

		$groups['cleanphone'] = [
			'title'    => 'PLG_RADICALMART_CLEANPHONE_CONFIG_TITLE',
			'key'      => 'cleanphone',
			'sections' => [
				'settings' => [
					'title'     => 'PLG_RADICALMART_CLEANPHONE_CONFIG_SETTINGS',
					'key'       => 'cleanphone_settings',
					'type'      => 'fieldsets',
					'fieldsets' => [
						'cleanphone'
					],
				]
			]
		];
	}

	/**
	 * Method to change forms.
	 *
	 * @param   Form   $form  The form to be altered.
	 * @param   mixed  $data  The associated data for the form.
	 *
	 * @throws  \Exception
	 *
	 * @since  0.0.0
	 */
	public function onRadicalMartPrepareConfigForm(Form $form, $data)
	{
		Form::addFormPath(JPATH_PLUGINS . '/' . $this->_type . '/' . $this->_name . '/forms');
		$form->loadFile('config');

		// Fix table subform layout
		$wa    = Factory::getApplication()->getDocument()->getWebAssetManager();
		$style = '
		[data-key="cleanphone_settings"] .subform-table-layout .table-responsive {
		    overflow-x: visible;
		}
		';
		$wa->addInlineStyle($style);
	}

	/**
	 * Method to clean user phone.
	 *
	 * @param   string  $phone  Use phone
	 *
	 * @since  1.0.0
	 */
	public function onRadicalMartCleanPhone(&$phone)
	{
		if (!class_exists('\\RadicalMart\\PhoneNumber\\PhoneNumber') && !@include_once(JPATH_PLUGINS . '/radicalmart/cleanphone/libraries/RadicalMart/PhoneNumber/autoload.php'))
		{
			return;
		}

		$params  = ParamsHelper::getComponentParams();
		$phones  = $params->get('cleanphone_phones');
		$app     = Factory::getApplication();
		$checked = false;

		// Check empty phones list
		if (empty($phones)) return;

		foreach ($phones as $p)
		{
			$country = $p->country;
			$format  = $p->format;

			if (empty($country)) continue;

			try
			{
				$phoneNumber = new PhoneNumber($phone, $country);
				$phone       = $phoneNumber->format(constant('libphonenumber\PhoneNumberFormat::' . $format));
				$checked     = true;
				break;
			}
			catch (\Exception $e)
			{
				$phone = '';
			}
		}

		if (!$checked && $app->getInput()->get('option') === 'com_radicalmart' && ($app->isClient('site') || $app->isClient('administrator')))
		{
			Factory::getApplication()->enqueueMessage(Text::_('PLG_RADICALMART_CLEANPHONE_ERROR_WRONG_FORMAT'), 'error');
		}

		if (!$checked) $phone = '';
	}
}