<?php
/**
 * POST JSON: { idToken, clientId, targetUid }
 * Removes a staff admin from the store (RTDB + Auth delete). 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']) : '';

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);
if ($actor['uid'] === $targetUid) {
    tenant_admin_json_response(400, ['status' => 'error', 'message' => 'You cannot remove your own account this way.']);
}

$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 remove admins.']);
}

$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 accounts can be removed here.']);
}

$email = isset($targetNode['email']) ? trim(strtolower((string) $targetNode['email'])) : '';
$emailKey = $email !== '' ? tenant_admin_sanitize_email_key($email) : '';

// Delete RTDB admin node first (so user can't access dashboard even if Auth delete fails later).
$del = firebase_rtdb_delete($dbUrl, 'clients/' . $clientId . '/admins/' . $targetUid, $accessToken);
if (isset($del['error']) || (($del['http'] ?? 500) >= 400)) {
    tenant_admin_json_response(500, ['status' => 'error', 'message' => 'Failed to remove admin: ' . ($del['error'] ?? '')]);
}

if ($emailKey !== '') {
    firebase_rtdb_delete($dbUrl, 'usersByEmail/' . $emailKey . '/' . $clientId, $accessToken);
}
firebase_rtdb_delete($dbUrl, 'userSites/' . $targetUid . '/' . $clientId, $accessToken);

// Best-effort: delete Firebase Auth user (requires recent idToken of target — not available).
// Document: staff should be removed via this endpoint; Auth user may remain orphaned unless cleaned in console.
// Optional improvement: use service account Admin SDK REST to delete user by uid (not in current helpers).

tenant_admin_json_response(200, ['status' => 'success', 'message' => 'Staff admin removed from this store. If they still exist in Firebase Auth, delete the user from Firebase Console if needed.']);
