<?php

define('FEL_NIT_EMISOR', '120429144');
define('FEL_RAZON_SOCIAL', 'FARMACIAS Y COPROPIEDAD');
define('FEL_USUARIO', 'TESTUSER');
define('FEL_PASSWORD', 'bX$18M8&');

define('FEL_API_URL', 'https://testnucgt.digifact.com/api');
define('FEL_CERT_URL', 'https://testnucgt.digifact.com/api/v2/transform/nuc_json');

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

function getFELToken() {
    $cacheFile = __DIR__ . '/fel_token_cache.txt';

    if (file_exists($cacheFile)) {
        $cachedData = json_decode(file_get_contents($cacheFile), true);
        if ($cachedData && (time() - $cachedData['time'] < 3600)) {
            return $cachedData['token'];
        }
    }

    $url = FEL_API_URL . "/login/get_token";
    $nit_pad = str_pad(FEL_NIT_EMISOR, 12, "0", STR_PAD_LEFT);
    $username_construido = "GT." . $nit_pad . "." . FEL_USUARIO;

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
        "Username" => $username_construido,
        "Password" => FEL_PASSWORD
    ]));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    $res = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) return null;

    $data = json_decode($res, true);
    $token = $data['Token'] ?? null;

    if ($token) {
        file_put_contents($cacheFile, json_encode([
            'token' => $token,
            'time' => time()
        ]));
    }

    return $token;
}
