<?php
// GET  /api/roles       — list roles
// POST /api/roles       — create role
// PUT  /api/roles/:id   — update role name

$method = $_SERVER['REQUEST_METHOD'];
$id     = (int)($GLOBALS['route_params'][0] ?? 0);

$db = getDB();

if ($method === 'GET') {
    $rows = $db->query("SELECT id, name FROM roles ORDER BY id ASC")->fetch_all(MYSQLI_ASSOC);
    $db->close();
    sendSuccess(['data' => $rows]);
}

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $name  = trim($input['name'] ?? '');

    if (!$name) sendError('name is required');

    $stmt = $db->prepare("INSERT INTO roles (name) VALUES (?)");
    $stmt->bind_param("s", $name);
    if (!$stmt->execute()) sendError('Role already exists', 409);
    $roleId = $db->insert_id;
    $stmt->close();
    $db->close();

    sendSuccess(['id' => $roleId], 'Role created successfully');
}

if ($method === 'PUT') {
    if (!$id) sendError('Invalid role ID');

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

    if (!$name) sendError('name is required');

    $stmt = $db->prepare("UPDATE roles SET name = ? WHERE id = ?");
    $stmt->bind_param("si", $name, $id);
    $stmt->execute();
    if ($stmt->affected_rows === 0) sendError('Role not found', 404);
    $stmt->close();
    $db->close();

    sendSuccess([], 'Role updated successfully');
}

sendError('Method not allowed', 405);
