<?php

/**
 * Field for validating Slovak company registration numbers (IČO).
 *
 * @package FormEnhancer\FluentForm\Fields
 */

namespace FormEnhancer\FluentForm\Fields;

use FormEnhancer\FluentForm\Fields\Abstracts\BasedOnExistingField;
use FluentForm\App\Services\FormBuilder\Components\Text;
use FormEnhancer\FluentForm\Fields\Validate\IcoSk;

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

		if ($finstat->isValidIco($ico) === false) {
			$errorMessage[] = \__('IČO is not valid - doesn\'t exist in FinStat.sk database. Please check the number.', 'formenhancer');
		}

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