<?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__));
    $requiredFiles = array(
        'modules/crm/quote_pdf.php',
        'services/crm/CrmQuotePdfService.php',
        'services/documents/CommercialDocumentPdfRenderer.php',
        'services/documents/PurchaseOrderPdfRenderer.php',
        'services/documents/SimplePdfWriter.php',
        'assets/img/icylab_document_logo.jpg',
    );
    $missing = array();
    foreach ($requiredFiles as $file) if (!$root || !is_file($root . '/' . $file)) $missing[] = $file;
    $report(!$missing, 'FILES', $missing ? 'Faltan: ' . implode(', ', $missing) : 'Plantilla y endpoints PDF instalados.');

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

    $legacy = (int)$pdo->query("SELECT COUNT(*) FROM crm_documents WHERE document_type='cotizacion' AND file_path LIKE '/modules/crm/quote_view.php?id=%'")->fetchColumn();
    $report($legacy === 0, 'QUOTE_PATHS', $legacy === 0 ? 'Todas las cotizaciones apuntan al PDF descargable.' : 'Persisten ' . $legacy . ' referencias a la vista de impresión; ejecuta la migración v7.2.1.');

    $hasOrders = (int)$pdo->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='billing_purchase_orders'")->fetchColumn() === 1;
    $report($hasOrders, 'PURCHASE_ORDERS', $hasOrders ? 'Órdenes de compra disponibles.' : 'Falta desplegar la migración v7.2 de órdenes de compra.');
} catch (Throwable $e) {
    $report(false, 'EXCEPTION', $e->getMessage());
}

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