<?php

/**
 * Documentation for the BaseFieldManager class.
 *
 * @package FormEnhancer\FluentForm\Fields
 */

namespace FormEnhancer\FluentForm\Fields;

use FluentForm\App\Services\FormBuilder\Components\Text;
use FormEnhancer\FluentForm\Fields\Abstracts\BasedOnExistingField;
use FormEnhancerDeps\DragonBe\Vies\Vies;
use Exception;

/**
 * Class EuVat
 *
 * @package FormEnhancer\FluentForm\Fields
 */
class EuVat extends BasedOnExistingField
{
	/**
	 * IcoCZField constructor.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct(
			'formenhancer_eu_vat',
			'EU VAT - Form Enhancer',
			['vat', 'company', 'vat number', 'vat number', 'form', 'formenahncer', 'dič'],
			'advanced',
			'input_text',
			'general'
		);

		\add_filter('fluentform/validate_input_item_' . $this->key, [$this, 'validateInput'], 10, 5);
	}

	/**
	 * Render the field.
	 *
	 * @param array $data The field data.
	 * @param array $form The form data.
	 * @return void
	 */
	public function render($data, $form)
	{
		$text = new Text();

		// Add class to the input field.
		$data['attributes']['class'] = !empty($data['attributes']['class']) ? $data['attributes']['class'] . ' formenhancer-el-eu-vat' : 'formenhancer-el-eu-vat';

		$text->compile($data, $form);
	}

	/**
	 * Get the field component.
	 *
	 * @return array
	 */
	public function getComponent()
	{
		$component = parent::getComponent();
		$component['settings']['label'] = \__('EU VAT', 'formenhancer');
		$component['editor_options']['icon_class'] = 'el-icon-office-building';

		return $component;
	}

	/**
	 * Validate the input.
	 *
	 * @param array $errorMessage The error message.
	 * @param array $field The field data.
	 * @param array $formData The form data.
	 * @param array $fields The fields data.
	 * @param array $form The form data.
	 * @return array
	 */
	public function validateInput($errorMessage, $field, $formData, $fields, $form)
	{
		// Normalize error message to array.
		if (\is_string($errorMessage)) {
			$errorMessage = empty($errorMessage) ? [] : [$errorMessage];
		}

		// Return early if field is empty.
		$fieldName = $field['name'];
		if (empty($formData[$fieldName])) {
			return $errorMessage;
		}

		$dic = \trim($formData[$fieldName]); // This is the user input value.

		// Check if the dic as 2 letters and than only numbers.
		if (!\preg_match('/^[A-Z]{2}\d+$/', $dic)) {
			$errorMessage[] = \__('VAT number must be 2 letters and then only numbers.', 'formenhancer');
			return $errorMessage;
		}

		$current_country = \substr($dic, 0, 2);
		$current_vat_no  = \substr($dic, 2);

		$vies = new Vies();

		try {
			if ($vies->getHeartBeat()) {
				$valid = $vies->validateVat($current_country, $current_vat_no)->isValid();
			} else {
				$valid = $vies->validateVatSum($current_country, $current_vat_no);
			}
		} catch (Exception $e) {
			$errorMessage[] = \__('VAT number can\'t be validated in VIES service. Please try again later.', 'formenhancer');
		}

		if (!$valid) {
			$errorMessage[] = \__('VAT number is not valid. Please check the number.', 'formenhancer');
		}

		return !empty($errorMessage) ? $errorMessage : [];
	}
}
