<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../config.php';

$headers    = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
$token      = str_replace('Bearer ', '', $authHeader);

if (empty($token)) {
    $body  = json_decode(file_get_contents('php://input'), true);
    $token = $body['token'] ?? '';
}

if (empty($token)) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Token requerido']);
    exit;
}

$db  = getDB();
$now = date('Y-m-d H:i:s');

$stmt = $db->prepare(
    "SELECT s.idusuarios_sist, u.nombre_usr, u.rango_idrango
     FROM admin_sessions s
     INNER JOIN usuarios_sist u ON u.idusuarios_sist = s.idusuarios_sist
     WHERE s.token = ? AND s.expira > ?
     LIMIT 1"
);
$stmt->execute([$token, $now]);
$session = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$session) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Sesión expirada o inválida']);
    exit;
}

echo json_encode([
    'success' => true,
    'data' => [
        'idusuarios_sist' => $session['idusuarios_sist'],
        'usuario'         => $session['nombre_usr'],
        'rango'           => $session['rango_idrango'],
    ]
]);
