<?php
require_once __DIR__ . '/../core/cron_guard.php';
icylab_require_cron_access();
require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/database.php';
require_once __DIR__ . '/../services/finance/ExchangeRateService.php';

if (PHP_SAPI !== 'cli') header('Content-Type: text/plain; charset=utf-8');
$pdo = db();
$failures = array();
$warnings = array();
function fx_line($name, $ok, $detail='') { echo ($ok ? 'PASS' : 'FAIL') . ' | ' . $name . ($detail !== '' ? ' | ' . $detail : '') . PHP_EOL; }

$table = (int)$pdo->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='finance_exchange_rates'")->fetchColumn() === 1;
fx_line('finance_exchange_rates', $table); if (!$table) $failures[] = 'finance_exchange_rates';
$required = array(
    'facto_documents' => array('exchange_rate_date','exchange_rate_source','exchange_rate_status','net_amount_clp','taxes_amount_clp','total_amount_clp'),
    'billing_collections' => array('exchange_rate_date','exchange_rate_source','exchange_rate_status'),
    'billing_payments' => array('currency_code','exchange_rate_value','exchange_rate_date','exchange_rate_source','exchange_rate_status','foreign_amount'),
    'billing_export_operations' => array('exchange_rate_date','exchange_rate_source','exchange_rate_status'),
    'crm_quotes' => array('billing_exchange_rate_date','billing_exchange_rate_source','billing_exchange_rate_status'),
);
foreach ($required as $tableName => $columns) {
    $stmt = $pdo->prepare("SELECT column_name FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=?");
    $stmt->execute(array($tableName));
    $existing = $stmt->fetchAll(PDO::FETCH_COLUMN);
    foreach ($columns as $column) {
        $ok = in_array($column, $existing, true);
        fx_line($tableName . '.' . $column, $ok);
        if (!$ok) $failures[] = $tableName . '.' . $column;
    }
}

if (!$failures) {
    $pending = (int)$pdo->query("SELECT COUNT(*) FROM facto_documents WHERE received_issued_flag=1 AND document_status=1 AND UPPER(COALESCE(NULLIF(currency_code,''),'CLP'))<>'CLP' AND (COALESCE(exchange_rate_value,0)<=0 OR total_amount_clp IS NULL)")->fetchColumn();
    fx_line('documentos extranjeros normalizados', $pending === 0, 'pendientes=' . $pending);
    if ($pending > 0) $warnings[] = 'foreign_documents_pending';
    $sourceCount = (int)$pdo->query("SELECT COUNT(*) FROM facto_documents WHERE received_issued_flag=1 AND document_status=1 AND UPPER(COALESCE(NULLIF(currency_code,''),'CLP'))<>'CLP' AND exchange_rate_source IN ('FINDIC_BCCH','FACTO_DTE','FACTO','MANUAL_AUTHORIZED')")->fetchColumn();
    fx_line('fuente de tasa registrada', true, 'documentos=' . $sourceCount);
    $paymentPending = (int)$pdo->query("SELECT COUNT(*) FROM billing_payments WHERE direction='received' AND UPPER(COALESCE(NULLIF(currency_code,''),'CLP'))<>'CLP' AND (COALESCE(exchange_rate_value,0)<=0 OR foreign_amount IS NULL)")->fetchColumn();
    fx_line('pagos extranjeros normalizados', $paymentPending === 0, 'pendientes=' . $paymentPending);
    if ($paymentPending > 0) $warnings[] = 'foreign_payments_pending';
    $collectionMismatch = (int)$pdo->query("SELECT COUNT(*) FROM billing_collections c WHERE c.direction='receivable' AND UPPER(COALESCE(NULLIF(c.currency_code,''),'CLP'))<>'CLP' AND ABS(COALESCE(c.total_amount,0)-COALESCE(c.paid_amount,0)-COALESCE(c.balance_amount,0))>1")->fetchColumn();
    fx_line('saldos CxC reconciliados', $collectionMismatch === 0, 'diferencias=' . $collectionMismatch);
    if ($collectionMismatch > 0) $warnings[] = 'foreign_collections_mismatch';
    try {
        $rate = (new ExchangeRateService($pdo))->resolve('USD', date('Y-m-d'), true, 7);
        $ok = !empty($rate['ok']);
        fx_line('consulta Findic USD', $ok, $ok ? ('fecha=' . $rate['rate_date'] . ', tasa=' . $rate['rate_to_clp']) : ($rate['message'] ?? 'sin respuesta'));
        if (!$ok) $warnings[] = 'findic_unavailable';
    } catch (Throwable $e) {
        fx_line('consulta Findic USD', false, $e->getMessage());
        $warnings[] = 'findic_unavailable';
    }
}

echo PHP_EOL;
if ($failures) { echo 'PREFLIGHT FAIL | ' . implode(', ', $failures) . PHP_EOL; exit(1); }
if ($warnings) { echo 'PREFLIGHT PASS WITH WARNINGS | ' . implode(', ', array_unique($warnings)) . PHP_EOL; exit(0); }
echo "PREFLIGHT PASS | Findic y normalización CLP operativos.\n";
