<?php
// =============================================================
//  POST /api/v1/admin_rbac/role_permissions_update
//
//  Mobile equivalent of include/update_role_permissions.php: a full
//  REPLACE of a role's permission set, not a delta — every existing
//  role_permissions row for this role is deleted, then the submitted
//  IDs are re-inserted. Matches the desktop page's own documented
//  behaviour and its "takes effect next login" caveat (permissions are
//  cached in $_SESSION at login time by hydrateRequestContext(), so an
//  already-logged-in affected user isn't immediately re-scoped).
//
//  Body: { "role_id": 7, "permission_ids": [3, 7, 12] }
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Api::error(405, 'MethodNotAllowed', 'Use POST');
}

$account = api_authenticate();
api_require_permission('manage_permissions');

$body   = Api::body();
$roleId = (int)($body['role_id'] ?? 0);
if ($roleId <= 0) Api::error(422, 'ValidationError', 'A valid role_id is required.');

$roleCheck = $conn->prepare("SELECT display_name FROM roles WHERE id = ?");
$roleCheck->bind_param('i', $roleId);
$roleCheck->execute();
$role = $roleCheck->get_result()->fetch_assoc();
$roleCheck->close();
if (!$role) Api::error(404, 'NotFound', 'Role not found.');

$rawIds = $body['permission_ids'] ?? [];
if (!is_array($rawIds)) Api::error(422, 'ValidationError', 'permission_ids must be an array.');
$permissionIds = array_values(array_unique(array_map('intval', $rawIds)));

$conn->begin_transaction();
try {
    $del = $conn->prepare("DELETE FROM role_permissions WHERE role_id = ?");
    $del->bind_param('i', $roleId);
    $del->execute();
    $del->close();

    $insertCount = 0;
    if (!empty($permissionIds)) {
        $ins = $conn->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
        foreach ($permissionIds as $permId) {
            if ($permId <= 0) continue;
            $ins->bind_param('ii', $roleId, $permId);
            if ($ins->execute()) $insertCount++;
        }
        $ins->close();
    }

    $conn->commit();
} catch (Throwable $e) {
    $conn->rollback();
    Api::error(500, 'ServerError', 'Database error while saving permissions: ' . $e->getMessage());
}

$permManager = new PermissionManager($conn);
$permManager->logAudit(
    $account->getId(),
    'update_role_permissions',
    'role',
    $roleId,
    null,
    json_encode(['role_display_name' => $role['display_name'], 'permission_ids' => $permissionIds])
);

Api::success([
    'message'      => "Permissions saved successfully. Saved $insertCount permission(s) for \"{$role['display_name']}\".",
    'saved_count'  => $insertCount,
]);
