<?php
require_once __DIR__ . '/_super_admin_common.php';

$body = sa_require_post_json();
[, , $dbUrl, $accessToken] = sa_require_super_admin_session_with_db();

$snap = firebase_rtdb_get($dbUrl, 'clients', $accessToken);
if (isset($snap['error'])) sa_json_response(500, ['status' => 'error', 'message' => 'Failed to load clients']);

$clients = [];
$all = is_array($snap['data'] ?? null) ? $snap['data'] : [];
foreach ($all as $clientId => $node) {
    if (!is_array($node)) continue;
    $settings = is_array($node['settings'] ?? null) ? $node['settings'] : [];
    $siteSettings = is_array($node['siteSettings'] ?? null) ? $node['siteSettings'] : [];
    $wallet = is_array($node['wallet'] ?? null) ? $node['wallet'] : [];
    $displayName = (string) ($node['siteName'] ?? $siteSettings['siteName'] ?? $settings['businessName'] ?? '');
    $clients[] = [
        'clientId' => (string)$clientId,
        'siteName' => (string)$displayName,
        'subdomain' => (string)($node['subdomain'] ?? ''),
        'status' => (string)($node['status'] ?? 'active'),
        'balance' => (float)($wallet['balance'] ?? 0),
    ];
}

usort($clients, static function ($a, $b) {
    return strcmp($a['siteName'] . $a['clientId'], $b['siteName'] . $b['clientId']);
});

sa_json_response(200, ['status' => 'success', 'clients' => $clients]);
