<?php

require_once  __DIR__ . '/../config/config.php';
require_once  VENDOR_AUTOLOAD;

use GuzzleHttp\Client;

function getSiigoToken(): string
{
    static $token = null;

    // Reusar token si existe en memoria
    if ($token) {
        return $token;
    }

    // Verifica si hay token cacheado
    $cachePath = __DIR__ . '/token_siigo.json';
    if (file_exists($cachePath)) {
        $data = json_decode(file_get_contents($cachePath), true);
        if (isset($data['token']) && time() < $data['expires_at']) {
            return $token = $data['token'];
        }
    }

    // Pedir nuevo token
    $http = new Client(['base_uri' => SIIGO_BASE_URL, 'timeout' => 30]);
    $resp = $http->post('/auth', [
        'json' => [
            'username'   => SIIGO_USERNAME,
            'access_key' => SIIGO_ACCESS_KEY,
        ],
    ]);

    $data = json_decode((string)$resp->getBody(), true);
    if (empty($data['access_token'])) {
        throw new \Exception('Token inválido');
    }

    $token = $data['access_token'];

    // Guardar token en archivo
    file_put_contents($cachePath, json_encode([
        'token' => $token,
        'expires_at' => time() + 1700 // 28 minutos
    ]));

    return $token;
}
