<?php

/**
 * Validator class for Slovak IČO (Company ID) validation.
 *
 * @package FormEnhancer\FluentForm\Fields\Validate
 */

namespace FormEnhancer\FluentForm\Fields\Validate;

/**
 * Class IcoSk
 *
 * Validates Slovak company IDs (IČO) against Finstat.sk registry.
 */
class IcoSk
{
	/**
	 * Get Finstat.sk response code for an IČO lookup.
	 *
	 * @param string $ico The IČO (company ID) to validate.
	 * @return int|false Response code from Finstat.sk or false on error.
	 */
	private function getFinstatResponseCode(string $ico)
	{
		// Try to validate IČO in SK registry.
		$url = 'https://finstat.sk/' . $ico;
		$response = \wp_remote_get($url);

		if (\is_wp_error($response)) {
			return false;
		}

		// https://finstat.sk/42234077 existující IČO -> HTTP 200.
		// https://finstat.sk/42234017 neexistující IČO -> HTTP 404.
		$responseCode = \wp_remote_retrieve_response_code($response);
		return $responseCode;
	}

	/**
	 * Check if IČO exists in SK registry.
	 *
	 * @param string $ico The IČO (company ID) to validate.
	 * @return bool True if IČO exists, false otherwise.
	 */
	public function isValidIco(string $ico)
	{
		return $this->getFinstatResponseCode($ico) === 200;
	}
}
