<?php
/**
 * POST JSON: { idToken, clientId, targetUid, permissions: object }
 * Updates permissions for an existing staff admin. Store owners only.
 */
require_once __DIR__ . '/tenant-admin-common.php';

$body = tenant_admin_require_post_json();
$clientId = tenant_admin_require_client_id($body);
$idToken = isset($body['idToken']) ? trim((string) $body['idToken']) : '';
$targetUid = isset($body['targetUid']) ? trim((string) $body['targetUid']) : '';
$permsIn = $body['permissions'] ?? [];

if ($targetUid === '' || !preg_match('/^[a-zA-Z0-9]{1,128}$/', $targetUid)) {
    tenant_admin_json_response(400, ['status' => 'error', 'message' => 'Invalid targetUid.']);
}

$ctx = tenant_admin_require_bootstrap();
$dbUrl = $ctx['dbUrl'];
$accessToken = $ctx['accessToken'];
$webKey = $ctx['webKey'];

$actor = tenant_admin_lookup_id_token($idToken, $webKey);
$actorNode = tenant_admin_get_admin_node($dbUrl, $accessToken, $clientId, $actor['uid']);
if (!tenant_admin_is_store_owner($actorNode)) {
    tenant_admin_json_response(403, ['status' => 'error', 'message' => 'Only the store owner can update permissions.']);
}

$targetNode = tenant_admin_get_admin_node($dbUrl, $accessToken, $clientId, $targetUid);
if (!tenant_admin_is_truthy_member($targetNode)) {
    tenant_admin_json_response(404, ['status' => 'error', 'message' => 'Admin not found.']);
}
$tRole = isset($targetNode['role']) && (string) $targetNode['role'] !== '' ? (string) $targetNode['role'] : 'owner';
if ($tRole !== 'staff') {
    tenant_admin_json_response(400, ['status' => 'error', 'message' => 'Only invited staff permissions can be edited here.']);
}

$perms = tenant_admin_normalize_permissions_map($permsIn);
$hasNonHome = false;
foreach ($perms as $k => $v) {
    if ($v && (string) $k !== 'home') {
        $hasNonHome = true;
        break;
    }
}
if (!$hasNonHome) {
    tenant_admin_json_response(400, ['status' => 'error', 'message' => 'Select at least one section besides Home.']);
}

$patch = [
    'permissions' => $perms,
    'permissionsUpdatedAt' => time() * 1000,
    'permissionsUpdatedBy' => $actor['uid'],
];
$put = firebase_rtdb_patch($dbUrl, 'clients/' . $clientId . '/admins/' . $targetUid, $accessToken, $patch);
if (isset($put['error']) || (($put['http'] ?? 500) >= 400)) {
    tenant_admin_json_response(500, ['status' => 'error', 'message' => 'Update failed: ' . ($put['error'] ?? 'HTTP ' . ($put['http'] ?? ''))]);
}

tenant_admin_json_response(200, ['status' => 'success', 'message' => 'Permissions updated.']);
