<?php
// backend/api/apply-joining-bonus.php
// Jab bhi deposit success hota hai yeh call karo
// 5% bonus investment pe add hota hai

error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
require_once '../config/db.php';

$input  = json_decode(file_get_contents('php://input'), true);
$wallet = trim($input['wallet'] ?? '');

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

// ── Check user exists ──
$uRes = $conn->query("SELECT account_id, name FROM users WHERE wallet='$wallet' LIMIT 1");
$user = $uRes->fetch_assoc();
if (!$user) {
    echo json_encode(["status" => "error", "message" => "User not found"]);
    exit;
}

// ── Check if bonus already given ──
$bonusCheck = $conn->query("SELECT id FROM deposits WHERE wallet='$wallet' AND notes='5% Joining Bonus' LIMIT 1");
if ($bonusCheck && $bonusCheck->num_rows > 0) {
    echo json_encode(["status" => "already", "message" => "Bonus already credited"]);
    exit;
}

// ── Get total investment ──
$invRes    = $conn->query("SELECT COALESCE(SUM(amount),0) AS amt FROM deposits WHERE wallet='$wallet' AND status='success'");
$total_inv = floatval($invRes->fetch_assoc()['amt']);

if ($total_inv <= 0) {
    echo json_encode(["status" => "error", "message" => "No investment found"]);
    exit;
}

// ── Calculate 5% bonus ──
$bonus   = round($total_inv * 0.05, 4);
$tx_hash = 'BONUS_5PCT_' . time() . '_' . rand(1000,9999);
$now     = date('Y-m-d H:i:s');

// ── Insert bonus deposit ──
$ins = $conn->prepare("
    INSERT INTO deposits (wallet, amount, status, tx_hash, notes, approved_by, approved_at, created_at)
    VALUES (?, ?, 'success', ?, '5% Joining Bonus', 'system', ?, ?)
");
$ins->bind_param("sdsss", $wallet, $bonus, $tx_hash, $now, $now);
$ins->execute();
$ins->close();

// ── Update user balance ──
$conn->query("UPDATE users SET balance = balance + $bonus WHERE wallet='$wallet'");

echo json_encode([
    "status"       => "success",
    "message"      => "5% joining bonus of \$$bonus credited!",
    "bonus_amount" => $bonus,
    "total_after"  => $total_inv + $bonus
]);
?>