<?php
header('Content-Type: application/json');
require '../includes/config.php';

if (!is_logged_in() || $_SESSION['user']['rol'] !== 'admin') {
    http_response_code(403);
    echo json_encode(['error' => 'Acceso no autorizado']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        $stmt = $pdo->query("SELECT id, username, nombre, email, rol FROM usuarios");
        echo json_encode($stmt->fetchAll());
        break;
        
    case 'POST':
        $data = json_decode(file_get_contents('php://input'), true);
        $hashedPassword = password_hash($data['password'], PASSWORD_DEFAULT);
        
        $stmt = $pdo->prepare("
            INSERT INTO usuarios (username, password, nombre, email, rol) 
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $data['username'],
            $hashedPassword,
            $data['nombre'],
            $data['email'],
            $data['rol'] ?? 'user'
        ]);
        
        echo json_encode(['success' => true, 'id' => $pdo->lastInsertId()]);
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Método no permitido']);
}
?>