<?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/facto/ExportDocumentReconciliationService.php';
require_once __DIR__ . '/../services/analytics/AnalyticsEngine.php';

if (PHP_SAPI !== 'cli') header('Content-Type: text/plain; charset=utf-8');

try {
    $pdo = db();
    $result = (new ExportDocumentReconciliationService($pdo, 'production'))->reconcileHistoricalExports(5000);
    (new AnalyticsEngine($pdo))->rebuild();

    echo "EXPORT FX RECONCILIATION OK\n";
    foreach ($result as $key => $value) {
        if ($key === 'fx_messages') continue;
        echo $key . ': ' . (int)$value . "\n";
    }
    if (!empty($result['fx_messages'])) {
        echo "fx_messages:\n";
        foreach ($result['fx_messages'] as $item) {
            echo '- DTE ' . ($item['document_number'] ?: $item['document_id'])
                . ' | ' . $item['issue_date']
                . ' | ' . $item['currency_code']
                . ' | ' . $item['message'] . "\n";
        }
    }
    echo "analytics_rebuilt: 1\n";
} catch (Throwable $e) {
    if (PHP_SAPI !== 'cli') http_response_code(500);
    echo 'EXPORT FX RECONCILIATION ERROR: ' . $e->getMessage() . "\n";
    exit(1);
}
