<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

$conn = require __DIR__ . '/../../app/config/database.php';
require_login();
csrf_verify();

$admin = current_user();

$userId  = (int)($_POST['user_id'] ?? 0);
$assetId = (int)($_POST['asset_id'] ?? 0);
$amount  = (float)($_POST['amount'] ?? 0);

if ($userId < 1 || $assetId < 1 || $amount <= 0) {
    flash('err', 'Invalid input');
    redirect('users.php');
}

try {
    $conn->begin_transaction();

    /* ENSURE WALLET */
    $st = $conn->prepare("
        INSERT IGNORE INTO crypto_wallets (user_id, asset_id, balance, locked_balance)
        VALUES (?, ?, 0, 0)
    ");
    $st->bind_param("ii", $userId, $assetId);
    $st->execute();

    /* LOCK WALLET */
    $st = $conn->prepare("
        SELECT balance
        FROM crypto_wallets
        WHERE user_id=? AND asset_id=?
        FOR UPDATE
    ");
    $st->bind_param("ii", $userId, $assetId);
    $st->execute();
    $w = $st->get_result()->fetch_assoc();

    $newBalance = ((float)$w['balance']) + $amount;

    /* UPDATE BALANCE */
    $st = $conn->prepare("
        UPDATE crypto_wallets
        SET balance=?
        WHERE user_id=? AND asset_id=?
    ");
    $st->bind_param("dii", $newBalance, $userId, $assetId);
    $st->execute();

    /* LEDGER / TRANSACTION RECORD */
    $ref = now_ref('ADMCR');

    $st = $conn->prepare("
        INSERT INTO crypto_txn
          (ref, user_id, asset_id, type, amount, fee, total_debit, status, created_at)
        VALUES
          (?, ?, ?, 'admin_credit', ?, 0, 0, 'approved', NOW())
    ");
    $st->bind_param("siid", $ref, $userId, $assetId, $amount);
    $st->execute();

    /* AUDIT */
    $meta = json_encode([
        'user_id' => $userId,
        'asset_id' => $assetId,
        'amount' => $amount
    ]);
    $ip = client_ip();

    $st = $conn->prepare("
        INSERT INTO audit_logs (actor_id, action, meta, ip)
        VALUES (?, 'ADMIN_CRYPTO_CREDIT', ?, ?)
    ");
    $st->bind_param("iss", $admin['id'], $meta, $ip);
    $st->execute();

    $conn->commit();
    flash('msg', 'Wallet credited successfully');

} catch (Throwable $e) {
    $conn->rollback();
    flash('err', $e->getMessage());
}

redirect('user_view.php?id=' . $userId);
