<?php
// POST /api/roles/:id/permissions

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendError('Method not allowed', 405);
}

$role_id = (int)($GLOBALS['route_params'][0] ?? 0);
if (!$role_id) sendError('Invalid role ID');

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

if (!is_array($permissions)) sendError('permissions must be an array');

$db = getDB();

// Verify role exists
$stmt = $db->prepare("SELECT id FROM roles WHERE id = ?");
$stmt->bind_param("i", $role_id);
$stmt->execute();
if (!$stmt->get_result()->fetch_assoc()) {
    $stmt->close(); $db->close();
    sendError('Role not found', 404);
}
$stmt->close();

// Clear existing permissions for this role
$stmt = $db->prepare("DELETE FROM role_permissions WHERE role_id = ?");
$stmt->bind_param("i", $role_id);
$stmt->execute();
$stmt->close();

// Insert new permissions
if (!empty($permissions)) {
    $stmt = $db->prepare("
        INSERT IGNORE INTO role_permissions (role_id, permission_id)
        SELECT ?, id FROM permissions WHERE name = ?
    ");
    foreach ($permissions as $perm) {
        $perm = trim($perm);
        $stmt->bind_param("is", $role_id, $perm);
        $stmt->execute();
    }
    $stmt->close();
}

$db->close();
sendSuccess([], 'Permissions assigned successfully');
