<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Diagnostic\Service;

use Paysera\PrestashopPayments\Diagnostic\Config\DiagnosticConfig;

if (!defined('_PS_VERSION_')) {
    exit;
}

class TlsVersionProbeService
{
    /**
     * @return array<string, bool|null> Keyed by TLS version label. true = supported, false = probe failed, null = compile-time unavailable.
     */
    public function probe(string $url, int $timeoutSeconds): array
    {
        $results = [];

        foreach (DiagnosticConfig::getTlsVersions() as $versionName => $sslVersionConstant) {
            if ($sslVersionConstant === null) {
                $results[$versionName] = null;
                continue;
            }

            $results[$versionName] = $this->probeSingle($url, $timeoutSeconds, $sslVersionConstant);
        }

        return $results;
    }

    private function probeSingle(string $url, int $timeoutSeconds, int $sslVersion): bool
    {
        if (!function_exists('curl_init')) {
            return false;
        }

        $handle = curl_init($url);
        if ($handle === false) {
            return false;
        }

        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($handle, CURLOPT_TIMEOUT, $timeoutSeconds);
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, $timeoutSeconds);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($handle, CURLOPT_SSLVERSION, $sslVersion);

        $body = curl_exec($handle);
        $errno = curl_errno($handle);
        curl_close($handle);

        return $errno === 0 && $body !== false;
    }
}
