<?php

require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/database.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/SimplePdfWriter.php',
        'services/documents/CommercialDocumentPdfRenderer.php',
        'modules/admin/company_settings.php',
        'modules/admin/company_settings_store.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.2 instalados.');

    $pdo = db();
    $database = (string)$pdo->query('SELECT DATABASE()')->fetchColumn();
    $report($database === 'icylab_app', 'DATABASE', 'Base activa: ' . $database);

    $column = (int)$pdo->query("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='system_settings' AND column_name='commercial_document_footer'")->fetchColumn();
    $report($column === 1, 'FOOTER_COLUMN', $column === 1 ? 'Campo de pie comercial disponible.' : 'Ejecuta la migración SQL v7.2.2.');

    if ($column === 1) {
        $footer = $pdo->query('SELECT commercial_document_footer FROM system_settings WHERE id=1')->fetchColumn();
        $length = function_exists('mb_strlen') ? mb_strlen((string)$footer, 'UTF-8') : strlen((string)$footer);
        $report($length <= 500, 'FOOTER_LENGTH', 'Longitud configurada: ' . $length . ' caracteres.');
    }
} catch (Throwable $e) {
    $report(false, 'EXCEPTION', $e->getMessage());
}

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