<?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',
    );
    $missing = array();
    foreach ($required as $file) {
        if (!$root || !is_file($root . '/' . $file)) $missing[] = $file;
    }
    $report(!$missing, 'FILES', $missing ? 'Faltan: ' . implode(', ', $missing) : 'Archivos v7.2.4 instalados.');

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

    $renderer = new CommercialDocumentPdfRenderer();
    $pdf = $renderer->render(array(
        'type' => 'COTIZACIÓN',
        'number' => 'PREFLIGHT',
        'date' => date('d-m-Y'),
        'currency' => 'CLP',
        'company' => array('company_name' => 'ICYLAB SPA', 'company_tax_id' => '778841045'),
        'counterparty' => array('name' => 'Prueba', 'tax_id' => '783092123', 'country' => 'Chile'),
        'items' => array(array('sku' => 'TEST', 'description' => 'Prueba', 'quantity' => 1, 'unit' => 'unidad', 'unit_price' => 1000, 'taxable' => true, 'amount' => 1000)),
        'totals' => array(
            array('label' => 'Subtotal Bruto:', 'value' => 1000),
            array('label' => 'Monto Exento:', 'value' => 0, 'hide_when_zero' => true),
            array('label' => 'Total General:', 'value' => 1000, 'grand' => true),
        ),
    ));
    $report(strncmp($pdf, '%PDF-', 5) === 0, 'PDF_RENDER', 'Motor PDF comercial operativo.');
} catch (Throwable $e) {
    $report(false, 'EXCEPTION', $e->getMessage());
}

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