<?php

/**
 * This file contains the CzIco field class for validating Czech company IDs.
 *
 * @package FormEnhancer\FluentForm\Fields
 */

namespace FormEnhancer\FluentForm\Fields;

use FormEnhancer\FluentForm\Fields\Abstracts\BasedOnExistingField;
use FormEnhancerDeps\h4kuna\Ares\AresFactory;
use FormEnhancerDeps\h4kuna\Ares\Exceptions\IdentificationNumberNotFoundException;
use FormEnhancerDeps\h4kuna\Ares\Exceptions\ServerResponseException;
use FluentForm\App\Services\FormBuilder\Components\Text;

/**
 * Class IcoCZField
 *
 * @package FormEnhancer\FluentForm\Fields
 */
class CzIco extends BasedOnExistingField
{
	/**
	 * IcoCZField constructor.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct(
			'formenhancer_cz_ico',
			'IČO (CZ) - Form Enhancer',
			['ico', 'company', 'ičo', 'firma', 'form', 'formenahncer', 'cz'],
			'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-cz-ico' : 'formenhancer-el-cz-ico';

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

	/**
	 * Get the field component.
	 *
	 * @return array
	 */
	public function getComponent()
	{
		$component = parent::getComponent();
		$component['settings']['label'] = \__('IČO', '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;
		}

		$ico = \trim($formData[$fieldName]); // This is the user input value.
		$ico = \preg_replace('/\D/', '', $ico); // Strip spaces etc.

		// Bail if not numeric.
		if (!\is_numeric($ico) || \strlen($ico) !== 8) {
			$errorMessage[] = \__('IČO must be numeric and 8 digits long.', 'formenhancer');
			return $errorMessage;
		}

		// Validate IČO.
		$ares = (new AresFactory())->create();

		try {
			$ares->loadBasic($ico);
		} catch (IdentificationNumberNotFoundException $e) {
			 // log identification number, why is bad? Or make nothing.
			$errorMessage[] = \__('IČO is not valid - doesn\'t exist in ARES database. Please check the number.', 'formenhancer');
		} catch (ServerResponseException $e) {
			// no response from server or broken json.
			$errorMessage[] = \__('Can\'t connect to ARES service for validation. Please try again later.', 'formenhancer');
		}

		return !empty($errorMessage) ? $errorMessage : null;
	}
}
