<?php

require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/database.php';

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

$checks = array();
$failed = false;
$add = static function (string $status, string $code, string $message) use (&$checks, &$failed): void {
    $checks[] = array('status' => $status, 'code' => $code, 'message' => $message);
    if ($status === 'FAIL') $failed = true;
};

try {
    $pdo = db();
    $database = (string)$pdo->query('SELECT DATABASE()')->fetchColumn();
    $add($database === 'icylab_app' ? 'PASS' : 'FAIL', 'DATABASE', 'Base activa: ' . $database);

    $required = array('billing_purchase_order_sequences', 'billing_purchase_orders', 'billing_purchase_order_items', 'billing_purchase_order_emails');
    $stmt = $pdo->prepare('SELECT table_name FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name IN (?,?,?,?)');
    $stmt->execute($required);
    $found = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $missing = array_values(array_diff($required, $found));
    $add(!$missing ? 'PASS' : 'FAIL', 'PURCHASE_ORDER_TABLES', $missing ? 'Faltan: ' . implode(', ', $missing) : 'Las cuatro tablas de órdenes de compra están disponibles.');

    $root = realpath(dirname(__DIR__));
    $storage = $root . '/storage/billing/purchase_orders';
    if (!is_dir($storage)) @mkdir($storage, 0770, true);
    $add(is_dir($storage) && is_writable($storage) ? 'PASS' : 'FAIL', 'PDF_STORAGE', 'Ruta PDF: ' . $storage);

    $environment = defined('FACTO_DEFAULT_ENVIRONMENT') ? FACTO_DEFAULT_ENVIRONMENT : 'no definido';
    $add(in_array($environment, array('sandbox', 'production'), true) ? 'PASS' : 'FAIL', 'FACTO_ENVIRONMENT', 'Ambiente configurado en servidor: ' . $environment);
    $add(function_exists('iconv') ? 'PASS' : 'WARN', 'ICONV', function_exists('iconv') ? 'iconv disponible para caracteres españoles en PDF.' : 'iconv no disponible; el PDF reemplazará caracteres fuera de ASCII.');

    $smtp = defined('SMTP_HOST') ? trim((string)SMTP_HOST) : '';
    $add($smtp !== '' ? 'PASS' : 'WARN', 'SMTP', $smtp !== '' ? 'SMTP configurado para enviar OC.' : 'SMTP no configurado; la descarga PDF funciona, pero el envío dependerá de mail().');
} catch (Throwable $e) {
    $add('FAIL', 'EXCEPTION', $e->getMessage());
}

foreach ($checks as $check) {
    echo '[' . $check['status'] . '] ' . $check['code'] . ': ' . $check['message'] . PHP_EOL;
}
echo $failed ? 'BLOCKED: BILLING V7.2 NOT READY' . PHP_EOL : 'READY: BILLING V7.2' . PHP_EOL;
exit($failed ? 1 : 0);
