<?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/crm/OpportunityLifecycleService.php';

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

try {
    $service = new OpportunityLifecycleService(db());
    $result = $service->archiveEligibleInvoiced('month_end');
    echo 'archive_invoiced_opportunities OK' . PHP_EOL;
    echo 'Elegibles: ' . (int)($result['eligible'] ?? 0) . PHP_EOL;
    echo 'Archivadas: ' . (int)($result['archived'] ?? 0) . PHP_EOL;
    echo 'Omitidas por DTE invalido: ' . (int)($result['skipped_invalid_dte'] ?? 0) . PHP_EOL;
} catch (Throwable $e) {
    error_log('archive_invoiced_opportunities error: ' . $e->getMessage());
    if (PHP_SAPI !== 'cli') http_response_code(500);
    echo 'archive_invoiced_opportunities ERROR' . PHP_EOL;
    echo $e->getMessage() . PHP_EOL;
}
