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

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

$clientId = trim((string)($body['clientId'] ?? ''));
$amount = (float)($body['amount'] ?? 0);
$note = trim((string)($body['note'] ?? ''));
if ($clientId === '' || $amount == 0.0) sa_json_response(400, ['status' => 'error', 'message' => 'clientId and non-zero amount required']);

$lockId = preg_replace('/[^a-zA-Z0-9_-]/', '_', $clientId);
$lockPath = sys_get_temp_dir() . '/sa_wallet_' . $lockId . '.lock';
$lockFp = fopen($lockPath, 'c+');
if ($lockFp === false) {
    sa_json_response(503, ['status' => 'error', 'message' => 'Could not acquire wallet lock']);
}
if (!flock($lockFp, LOCK_EX)) {
    fclose($lockFp);
    sa_json_response(503, ['status' => 'error', 'message' => 'Could not lock wallet']);
}

$walletSnap = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/wallet', $accessToken);
if (isset($walletSnap['error'])) {
    flock($lockFp, LOCK_UN);
    fclose($lockFp);
    sa_json_response(500, ['status' => 'error', 'message' => 'Failed to read wallet']);
}
$wallet = is_array($walletSnap['data'] ?? null) ? $walletSnap['data'] : [];
$current = (float)($wallet['balance'] ?? 0);
$next = $current + $amount;

$txId = 'tx_' . time() . '_' . substr(bin2hex(random_bytes(6)), 0, 8);
$updates = [
    'balance' => $next,
    'updatedAt' => time() * 1000,
    'transactions/' . $txId => [
        'type' => 'super_admin_adjustment',
        'amount' => $amount,
        'previousBalance' => $current,
        'newBalance' => $next,
        'note' => $note,
        'actorUid' => $uid,
        'actorEmail' => $email,
        'createdAt' => time() * 1000,
    ],
];

$write = firebase_rtdb_patch($dbUrl, 'clients/' . $clientId . '/wallet', $accessToken, $updates);
if (isset($write['error'])) {
    flock($lockFp, LOCK_UN);
    fclose($lockFp);
    sa_json_response(500, ['status' => 'error', 'message' => 'Wallet adjustment failed']);
}

flock($lockFp, LOCK_UN);
fclose($lockFp);

sa_audit_log($dbUrl, $accessToken, $uid, $email, 'wallet_adjust', $clientId, [
    'amount' => $amount, 'previousBalance' => $current, 'newBalance' => $next, 'note' => $note
]);
sa_json_response(200, ['status' => 'success', 'message' => 'Wallet adjusted', 'balance' => $next]);
