<?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/FactoInboxDocumentsSyncService.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 {
    $perPage = 100;
    $environment = FACTO_DEFAULT_ENVIRONMENT;
    $fetchFiles = false;
    $params = array();

    if ($isCli) {
        $options = getopt('', array('per-page::', 'env::', 'fetch-files::', 'issuer-tax-id::', 'receiver-tax-id::', 'document-type-id::'));
        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);
        }
        if (isset($options['issuer-tax-id'])) {
            $params['issuer_tax_id_code'] = $options['issuer-tax-id'];
        }
        if (isset($options['receiver-tax-id'])) {
            $params['receiver_tax_id_code'] = $options['receiver-tax-id'];
        }
        if (isset($options['document-type-id'])) {
            $params['document_type_id'] = $options['document-type-id'];
        }
    } else {
        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);
        }
        foreach (array('issuer_tax_id_code', 'receiver_tax_id_code', 'document_type_id') as $key) {
            if (isset($_GET[$key]) && $_GET[$key] !== '') {
                $params[$key] = $_GET[$key];
            }
        }
    }

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

    $sync = new FactoInboxDocumentsSyncService($environment);
    $count = $sync->syncInboxDocuments($perPage, $params, $fetchFiles);

    echo "OK SYNC FACTO INBOX" . PHP_EOL;
    echo "Ambiente: " . icylab_facto_normalize_environment($environment) . PHP_EOL;
    echo "Documentos recibidos guardados/actualizados: " . $count . PHP_EOL;
} catch (Exception $e) {
    http_response_code(500);
    echo "ERROR SYNC FACTO INBOX" . PHP_EOL;
    echo $e->getMessage() . PHP_EOL;
}
