<?php
require_once __DIR__ . '/../core/cron_guard.php';
icylab_require_cron_access();
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');

echo "FINDIC DIAGNOSTIC v8.6.2\n";
echo 'php_version: ' . PHP_VERSION . "\n";
echo 'sapi: ' . PHP_SAPI . "\n";
echo 'curl_available: ' . (function_exists('curl_init') ? 'yes' : 'no') . "\n";
echo 'allow_url_fopen: ' . (filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN) ? 'yes' : 'no') . "\n";
$resolvedHost = gethostbyname('findic.cl');
echo 'findic_dns: ' . $resolvedHost . "\n";

try {
    $pdo = db();
    $service = new ExchangeRateService($pdo);
    $probe = $service->probeRemote('USD', '2026-06-02');
    echo 'remote_probe_ok: ' . (!empty($probe['ok']) ? 'yes' : 'no') . "\n";
    if (!empty($probe['ok'])) {
        echo 'remote_rate_date: ' . $probe['rate_date'] . "\n";
        echo 'remote_rate_value: ' . $probe['rate_to_clp'] . "\n";
        echo 'remote_source_url: ' . $probe['source_url'] . "\n";
    } else {
        echo 'remote_error: ' . ($probe['message'] ?? 'unknown') . "\n";
    }

    $stmt = $pdo->query("SELECT COUNT(*) FROM facto_documents WHERE received_issued_flag=1 AND document_status=1 AND UPPER(COALESCE(currency_code,'')) IN ('USD','EUR') AND (exchange_rate_value IS NULL OR exchange_rate_value<=0 OR total_amount_clp IS NULL)");
    echo 'pending_foreign_documents: ' . (int)$stmt->fetchColumn() . "\n";

    $pending = $service->applyPendingDocuments(5000, false);
    foreach ($pending as $key => $value) {
        echo 'backfill_' . $key . ': ' . (int)$value . "\n";
    }
} catch (Throwable $e) {
    if (PHP_SAPI !== 'cli') http_response_code(500);
    echo 'diagnostic_error: ' . $e->getMessage() . "\n";
    exit(1);
}
