<?php

ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');
error_reporting(E_ALL);

require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../services/facto/FactoDocumentsSyncService.php';
require_once __DIR__ . '/../services/analytics/AnalyticsEngine.php';

$isCli = php_sapi_name() === 'cli';

if (!$isCli) {
    header('Content-Type: text/plain; charset=utf-8');
    $configuredSecret = defined('ICYLAB_CRON_SECRET') ? (string) ICYLAB_CRON_SECRET : (getenv('ICYLAB_CRON_SECRET') ?: '');
    $providedSecret = isset($_GET['token']) ? (string) $_GET['token'] : '';

    if ($configuredSecret === '' || !hash_equals($configuredSecret, $providedSecret)) {
        http_response_code(403);
        echo "Forbidden" . PHP_EOL;
        exit;
    }
} else {
    header('Content-Type: text/plain; charset=utf-8');
}

try {
    $fromDate = date('Y-m-d', strtotime('-30 days'));
    $toDate = date('Y-m-d');
    $perPage = 100;
    $environment = FACTO_DEFAULT_ENVIRONMENT;
    $fetchFiles = false;

    if ($isCli) {
        $options = getopt('', array('from::', 'to::', 'per-page::', 'env::', 'fetch-files::'));
        if (isset($options['from'])) {
            $fromDate = $options['from'];
        }
        if (isset($options['to'])) {
            $toDate = $options['to'];
        }
        if (isset($options['per-page'])) {
            $perPage = (int) $options['per-page'];
        }
        if (isset($options['env'])) {
            $environment = $options['env'];
        }
        if (isset($options['fetch-files'])) {
            $fetchFiles = in_array((string) $options['fetch-files'], array('1', 'true', 'yes'), true);
        }
    } else {
        if (isset($_GET['from']) && $_GET['from'] !== '') {
            $fromDate = $_GET['from'];
        }
        if (isset($_GET['to']) && $_GET['to'] !== '') {
            $toDate = $_GET['to'];
        }
        if (isset($_GET['per_page']) && (int) $_GET['per_page'] > 0) {
            $perPage = (int) $_GET['per_page'];
        }
        if (isset($_GET['env']) && $_GET['env'] !== '') {
            $environment = $_GET['env'];
        }
        if (isset($_GET['fetch_files'])) {
            $fetchFiles = in_array((string) $_GET['fetch_files'], array('1', 'true', 'yes'), true);
        }
    }

    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $fromDate) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $toDate)) {
        throw new Exception('Formato de fecha invalido. Usar YYYY-MM-DD.');
    }

    $perPage = max(1, min(100, $perPage));

    $sync = new FactoDocumentsSyncService($environment);
    $count = $sync->syncIssuedDocuments($fromDate, $toDate, $perPage, $fetchFiles);

    $engine = new AnalyticsEngine();
    $engine->rebuild();

    echo "OK SYNC FACTO DOCUMENTS" . PHP_EOL;
    echo "Ambiente: " . icylab_facto_normalize_environment($environment) . PHP_EOL;
    echo "Desde: " . $fromDate . PHP_EOL;
    echo "Hasta: " . $toDate . PHP_EOL;
    echo "Documentos guardados/actualizados: " . $count . PHP_EOL;
    echo "Analytics reconstruido." . PHP_EOL;
} catch (Exception $e) {
    http_response_code(500);
    echo "ERROR SYNC FACTO DOCUMENTS" . PHP_EOL;
    echo $e->getMessage() . PHP_EOL;
}
