<?php
/*
 * StrategyRating - verifica Partita IVA lato server.
 * Il browser chiama QUESTO file (stesso sito), e il server interroga i registri.
 * Cosi' non ci sono blocchi del browser/estensioni/CORS verso servizi esterni.
 *
 * Riceve (POST, JSON):  {"countryCode":"IT","vatNumber":"12345678903"}
 * Risponde (JSON):      {"ok":true,"valid":true,"name":"...","address":"...","source":"..."}
 *                       oppure {"ok":false,"errors":[...]}
 */
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
header('X-Content-Type-Options: nosniff');

function out($code, $data) { http_response_code($code); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit; }

if ($_SERVER['REQUEST_METHOD'] !== 'POST') out(405, array('ok' => false, 'errors' => array('Metodo non consentito')));

$body = json_decode(file_get_contents('php://input'), true);
if (!is_array($body)) out(400, array('ok' => false, 'errors' => array('Richiesta non valida')));

$cc  = strtoupper(trim((string)($body['countryCode'] ?? '')));
$num = strtoupper(preg_replace('/[\s.\-]/', '', (string)($body['vatNumber'] ?? '')));
if (!preg_match('/^[A-Z]{2}$/', $cc) || !preg_match('/^[A-Z0-9]{2,14}$/', $num)) {
    out(422, array('ok' => false, 'errors' => array('Codice paese o numero non validi')));
}
if ($cc === 'GR') $cc = 'EL';

/* limite anti-abuso semplice per IP: 60 richieste/ora */
$dir = __DIR__ . '/sr-contact-data';
if (!is_dir($dir)) { @mkdir($dir, 0755, true); }
if (is_dir($dir)) {
    $ht = $dir . '/.htaccess';
    if (!file_exists($ht)) { @file_put_contents($ht, "Require all denied\n"); }
    $f = $dir . '/vies-rate.json';
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'x';
    $rate = file_exists($f) ? json_decode(@file_get_contents($f), true) : array();
    if (!is_array($rate)) $rate = array();
    $now = time(); $recent = array();
    foreach (($rate[$ip] ?? array()) as $t) { if ($t > $now - 3600) $recent[] = $t; }
    if (count($recent) >= 60) out(429, array('ok' => false, 'errors' => array('Troppe richieste, riprova piu\' tardi')));
    $recent[] = $now; $rate[$ip] = $recent;
    @file_put_contents($f, json_encode($rate));
}

function http($url, $method = 'GET', $json = null) {
    if (!function_exists('curl_init')) return array(0, null, 'cURL non disponibile sul server');
    $ch = curl_init($url);
    $headers = array('Accept: application/json', 'User-Agent: StrategyRating/1.0');
    curl_setopt_array($ch, array(
        CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 12, CURLOPT_CONNECTTIMEOUT => 6,
        CURLOPT_FOLLOWLOCATION => false, CURLOPT_SSL_VERIFYPEER => true,
    ));
    if ($method === 'POST') {
        $headers[] = 'Content-Type: application/json';
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json));
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $resp = curl_exec($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);
    return array($code, $resp, $err);
}
function clean($v) {
    $v = trim((string)$v);
    return ($v === '' || $v === '---' || preg_match('/^(N\/?A|NON DISPONIBILE)$/i', $v)) ? '' : $v;
}

$errors = array();

/* 1) business press (restituisce ragione sociale e indirizzo anche per l'Italia) */
list($c, $r, $e) = http('https://vat.businesspress.io/api/vat/validation/validate', 'POST',
    array('country_code' => $cc, 'vat_number' => $num));
if ($c >= 200 && $c < 300 && $r) {
    $j = json_decode($r, true);
    $d = (is_array($j) && isset($j['data']) && is_array($j['data'])) ? $j['data'] : $j;
    if (is_array($d) && array_key_exists('valid', $d)) {
        out(200, array('ok' => true, 'valid' => ($d['valid'] === true), 'name' => clean($d['name'] ?? ''),
            'address' => clean($d['address'] ?? ''), 'source' => 'businesspress'));
    }
    $errors[] = 'businesspress: risposta non riconosciuta';
} else { $errors[] = 'businesspress: ' . ($e ?: ('HTTP ' . $c)); }

/* 2) vatcomply */
list($c, $r, $e) = http('https://api.vatcomply.com/vat?vat_number=' . rawurlencode($cc . $num));
if ($c >= 200 && $c < 300 && $r) {
    $d = json_decode($r, true);
    if (is_array($d) && array_key_exists('valid', $d)) {
        out(200, array('ok' => true, 'valid' => ($d['valid'] === true), 'name' => clean($d['name'] ?? ''),
            'address' => clean($d['address'] ?? ''), 'source' => 'vatcomply'));
    }
    $errors[] = 'vatcomply: risposta non riconosciuta';
} else { $errors[] = 'vatcomply: ' . ($e ?: ('HTTP ' . $c)); }

/* 3) VIES ufficiale UE (per l'Italia spesso non diffonde nome/indirizzo, ma conferma la validita') */
list($c, $r, $e) = http('https://ec.europa.eu/taxation_customs/vies/rest-service/check-vat-number', 'POST',
    array('countryCode' => $cc, 'vatNumber' => $num));
if ($c >= 200 && $c < 300 && $r) {
    $d = json_decode($r, true);
    if (is_array($d) && (array_key_exists('valid', $d) || array_key_exists('isValid', $d))) {
        $valid = (($d['valid'] ?? $d['isValid'] ?? false) === true);
        out(200, array('ok' => true, 'valid' => $valid, 'name' => clean($d['name'] ?? ''),
            'address' => clean($d['address'] ?? ''), 'source' => 'vies'));
    }
    $errors[] = 'vies: risposta non riconosciuta';
} else { $errors[] = 'vies: ' . ($e ?: ('HTTP ' . $c)); }

out(502, array('ok' => false, 'errors' => $errors));
