<?php
require_once '../../../config/cors.php';
require_once '../../../config/db.php';
require_once '../../../helpers/response.php';
require_once '../../../helpers/request.php';
require_once '../../../helpers/auth.php';

$token = getBearerToken();
if (!$token) {
    sendError('No token provided', 401);
}

global $pdo;
$stmt = $pdo->prepare("\n    SELECT u.*, t.token \n    FROM public_users u\n    JOIN public_user_tokens t ON t.user_id = u.id\n    WHERE t.token = ? AND (t.expires_at IS NULL OR t.expires_at > NOW()) AND u.status = 'active'\n");
$stmt->execute([$token]);
$publicUser = $stmt->fetch();

$result = [
    'token_short' => strlen($token) > 24 ? substr($token,0,24) . '...' : $token,
    'public_user' => null,
    'jwt' => null
];

if ($publicUser) {
    $result['public_user'] = $publicUser;
} else {
    try {
        $decoded = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(JWT_SECRET, 'HS256'));
        $result['jwt'] = (array)$decoded;
    } catch (Exception $e) {
        $result['jwt_error'] = $e->getMessage();
    }
}

sendSuccess($result, 'Token validation result');

?>
