<?php
include_once '../config/header.php';
include_once '../token/token.php';
include_once '../jwt/BeforeValidException.php';
include_once '../jwt/ExpiredException.php';
include_once '../jwt/SignatureInvalidException.php';
include_once '../jwt/JWT.php';
use \Firebase\JWT\JWT;
 
$decodedJWTData=null; //Use this variable to read data anywhere in any other endpoint
$data = json_decode(file_get_contents("php://input"));

/** 
 * Get header Authorization
 * */
function getAuthorizationHeader(){
        $headers = null;
        if (isset($_SERVER['Authorization'])) {
            $headers = trim($_SERVER["Authorization"]);
        }
        else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
            $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
        } elseif (function_exists('apache_request_headers')) {
            $requestHeaders = apache_request_headers();
            // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
            $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
            if (isset($requestHeaders['Authorization'])) {
                $headers = trim($requestHeaders['Authorization']);
            }
        }
        return $headers;
    }
/**
 * get access token from header
 * */
function getBearerToken() {
    $headers = getAuthorizationHeader();
    // HEADER: Get the access token from the header
    if (!empty($headers)) {
        if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
            return $matches[1];
        }
    }
    return null;
}

try{
    // Crear directorio de logs si no existe
    if (!file_exists('../logs')) {
        mkdir('../logs', 0777, true);
    }
    
    // Crear un archivo de log para depuración de token
    $logFile = "../logs/token_validation_" . date('Y-m-d') . ".log";
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - Iniciando validación de token\n", FILE_APPEND);
    
    // Obtener el token del encabezado
    $jwtToken = getBearerToken(); //token from header
    
    // Registrar información sobre los encabezados recibidos para depuración
    $headers = getAuthorizationHeader();
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - Encabezados de autorización: " . ($headers ? $headers : "NINGUNO") . "\n", FILE_APPEND);
    
    // Verificar todos los encabezados recibidos para depuración
    $allHeaders = function_exists('apache_request_headers') ? apache_request_headers() : $_SERVER;
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - Todos los encabezados: " . json_encode($allHeaders) . "\n", FILE_APPEND);
    
    //if header[Authorization] is coming null then set the .htaccess file with SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 
    if(!$jwtToken){
        file_put_contents($logFile, date('Y-m-d H:i:s') . " - ERROR: No se encontró token en los encabezados\n", FILE_APPEND);
        http_response_code(403);
        echo json_encode(array(
            "status" => "error", 
            "code" => 0,
            "message" => "Error No Token Found",
            "document" => "Please set .htaccess file with [SetEnvIf Authorization '(.*)' HTTP_AUTHORIZATION=$1]"
        ));
        exit();
    } else {
        file_put_contents($logFile, date('Y-m-d H:i:s') . " - Token encontrado: " . substr($jwtToken, 0, 10) . "...\n", FILE_APPEND);
        
        // Decodificar el token
        $decodedJWTData = JWT::decode($jwtToken, SECRET_KEY, array(ALGORITHM));
        file_put_contents($logFile, date('Y-m-d H:i:s') . " - Token decodificado con éxito\n", FILE_APPEND);
    }
} catch(\Firebase\JWT\ExpiredException $e) {
    // El token ha expirado
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - ERROR: Token expirado: " . $e->getMessage() . "\n", FILE_APPEND);
    http_response_code(403);
    echo json_encode(array(
        "status" => "error", 
        "code" => 0,
        "message" => "Error: Token expirado - " . $e->getMessage(),
        "document" => ""
    ));
    exit();
} catch(\Firebase\JWT\SignatureInvalidException $e) {
    // La firma del token es inválida
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - ERROR: Firma de token inválida: " . $e->getMessage() . "\n", FILE_APPEND);
    http_response_code(403);
    echo json_encode(array(
        "status" => "error", 
        "code" => 0,
        "message" => "Error: Firma de token inválida - " . $e->getMessage(),
        "document" => ""
    ));
    exit();
} catch(Exception $e) {
    // Cualquier otro error con el token
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - ERROR: Token inválido: " . $e->getMessage() . "\n", FILE_APPEND);
    http_response_code(403);
    echo json_encode(array(
        "status" => "error", 
        "code" => 0,
        "message" => "Token inválido",
        "document" => $e->getMessage()
    ));
    exit();
}
?>