<?php

require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/database.php';
require_once __DIR__ . '/../services/documents/CommercialDocumentPdfRenderer.php';

if (PHP_SAPI !== 'cli') {
    http_response_code(404);
    exit;
}

$failed = false;
$report = static function (bool $ok, string $code, string $message) use (&$failed): void {
    echo '[' . ($ok ? 'PASS' : 'FAIL') . '] ' . $code . ': ' . $message . PHP_EOL;
    if (!$ok) $failed = true;
};

try {
    $root = realpath(dirname(__DIR__));
    $required = array(
        'services/documents/CommercialDocumentPdfRenderer.php',
        'services/documents/PurchaseOrderPdfRenderer.php',
        'services/crm/CrmQuotePdfService.php',
        'services/billing/BillingPurchaseOrderService.php',
    );
    $missing = array();
    foreach ($required as $file) if (!$root || !is_file($root . '/' . $file)) $missing[] = $file;
    $report(!$missing, 'FILES', $missing ? 'Faltan: ' . implode(', ', $missing) : 'Archivos v7.2.3 instalados.');

    $pdo = db();
    $database = (string)$pdo->query('SELECT DATABASE()')->fetchColumn();
    $report($database === 'icylab_app', 'DATABASE', 'Base activa: ' . $database);
    $countryColumn = (bool)$pdo->query("SHOW COLUMNS FROM crm_customers LIKE 'country'")->fetch(PDO::FETCH_ASSOC);
    $report($countryColumn, 'COUNTRY_COLUMN', $countryColumn ? 'País de contraparte disponible.' : 'Falta la columna crm_customers.country.');

    $national = CommercialDocumentPdfRenderer::formatTaxIdentifier('783092123', 'Chile');
    $foreign = CommercialDocumentPdfRenderer::formatTaxIdentifier('ESB12345678', 'España');
    $report($national === '78.309.212-3', 'CHILEAN_RUT', 'Resultado: ' . $national);
    $report($foreign === 'ESB12345678', 'FOREIGN_ID', 'Resultado: ' . $foreign);
} catch (Throwable $e) {
    $report(false, 'EXCEPTION', $e->getMessage());
}

echo $failed ? 'BLOCKED: BILLING V7.2.3 NOT READY' . PHP_EOL : 'READY: BILLING V7.2.3' . PHP_EOL;
exit($failed ? 1 : 0);
