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

$isCli = php_sapi_name() === 'cli';
header('Content-Type: text/plain; charset=utf-8');

if (!$isCli) {
    $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;
    }
}

try {
    $perPage = 100;
    $environment = defined('FACTO_DEFAULT_ENVIRONMENT') ? FACTO_DEFAULT_ENVIRONMENT : 'sandbox';
    $forceFullSync = false;

    if ($isCli) {
        $options = getopt('', array('per-page::', 'env::', 'force::'));
        if (isset($options['per-page'])) {
            $perPage = (int) $options['per-page'];
        }
        if (isset($options['env'])) {
            $environment = (string) $options['env'];
        }
        if (isset($options['force'])) {
            $forceFullSync = in_array(strtolower((string) $options['force']), array('1', 'true', 'yes'), true);
        }
    } else {
        if (isset($_GET['per_page'])) {
            $perPage = (int) $_GET['per_page'];
        }
        if (isset($_GET['env']) && $_GET['env'] !== '') {
            $environment = (string) $_GET['env'];
        }
        if (isset($_GET['force'])) {
            $forceFullSync = in_array(strtolower((string) $_GET['force']), array('1', 'true', 'yes'), true);
        }
    }

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

    $sync = new FactoCustomersSyncService($environment);
    $result = $sync->syncCustomers($perPage, $forceFullSync);

    echo "OK SYNC CUSTOMERS" . PHP_EOL;
    echo "Ambiente: " . $environment . PHP_EOL;
    echo "Nuevos: " . (int) ($result['created'] ?? 0) . PHP_EOL;
    echo "Actualizados: " . (int) ($result['updated'] ?? 0) . PHP_EOL;
    echo "Omitidos: " . (int) ($result['skipped'] ?? 0) . PHP_EOL;
} catch (Throwable $e) {
    http_response_code(500);
    error_log('FACTO customers sync error: ' . $e->getMessage());
    echo "ERROR SYNC CUSTOMERS" . PHP_EOL;
    echo "Revisar el registro del servidor." . PHP_EOL;
}
