<?php
// backend/admin/admin-add-fund.php
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');

$servername = "localhost";
$username   = "kdsmf_eppd";
$password   = "8DL!AesMeEt(%mgc";
$dbname     = "kdsmf_epd";

try {
    mysqli_report(MYSQLI_REPORT_OFF);
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) throw new Exception("DB Connection Failed: " . $conn->connect_error);
} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => "DB Error: " . $e->getMessage()]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(["status" => "error", "message" => "Invalid Request"]);
    exit;
}

$account_id = trim($_POST['account_id'] ?? '');
$amount     = floatval($_POST['amount'] ?? 0);

if (empty($account_id)) {
    echo json_encode(["status" => "error", "message" => "Account ID required"]);
    exit;
}

// ✅ Sirf minimum check - koi maximum nahi
if ($amount < 1) {
    echo json_encode(["status" => "error", "message" => "Minimum amount is \$1"]);
    exit;
}

$safe_acc = $conn->real_escape_string($account_id);

$uRes = $conn->query("SELECT wallet, name FROM users WHERE account_id = '$safe_acc' LIMIT 1");
if (!$uRes || $uRes->num_rows === 0) {
    echo json_encode(["status" => "error", "message" => "User not found — Account ID '$account_id'"]);
    exit;
}

$user   = $uRes->fetch_assoc();
$wallet = $user['wallet'];
$name   = $user['name'];

try {
    // 1. Insert deposit
    $txHash = "ADMIN_" . time() . "_" . rand(1000,9999);
    $ins = $conn->prepare("
        INSERT INTO deposits (wallet, amount, status, tx_hash, notes, approved_by, approved_at)
        VALUES (?, ?, 'success', ?, 'Manual fund by admin', 'admin', NOW())
    ");
    $ins->bind_param("sds", $wallet, $amount, $txHash);
    $ins->execute();
    $ins->close();

    // 2. Update balance
    $conn->query("UPDATE users SET balance = balance + $amount WHERE wallet='$wallet'");

    // 3. LEOCXX Coins
    $coin_reward = 0;
    if ($amount >= 20) $coin_reward = $amount * 0.50;
    if ($coin_reward > 0) {
        $checkInc = $conn->query("SELECT id FROM incomes WHERE wallet='$wallet'");
        if ($checkInc && $checkInc->num_rows > 0) {
            $conn->query("UPDATE incomes SET leocxx_coin = leocxx_coin + $coin_reward WHERE wallet='$wallet'");
        } else {
            $total_coin = 10 + $coin_reward;
            $conn->query("INSERT INTO incomes (wallet, leocxx_coin) VALUES ('$wallet', '$total_coin')");
        }
    }

    echo json_encode([
        "status"      => "success",
        "message"     => "\$$amount added to $name (Account: $account_id)",
        "bonus_given" => false,
        "total_added" => $amount
    ]);

} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => "Error: " . $e->getMessage()]);
}
?>