<?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');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

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

$body     = json_decode(file_get_contents('php://input'), true);
$usuario  = trim($body['usuario']  ?? '');
$password = trim($body['password'] ?? '');

if (empty($usuario) || empty($password)) {
    echo json_encode(['success' => false, 'message' => 'Datos requeridos']);
    exit;
}

$db   = getDB();
$stmt = $db->prepare("SELECT idusuarios_sist, nombre_usr, rango_idrango FROM usuarios_sist WHERE nombre_usr = ? AND passwd = MD5(?) LIMIT 1");
$stmt->execute([$usuario, $password]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    echo json_encode(['success' => false, 'message' => 'Usuario o contraseña incorrectos']);
    exit;
}

// Sesión simple con session_id
$token = bin2hex(random_bytes(32));
echo json_encode(['success' => true, 'data' => ['token' => $token, 'usuario' => $user['nombre_usr'], 'rango' => $user['rango_idrango']]]);
