<?php
// backend/api/approve-user.php
require_once '../config/db.php';

// 1. Jis user ko active karna hai uski details
$user_wallet = "0x34573724fb9560a51d3c812fc96d025d399f7fd7"; // Boss ki wallet (image_f8d045 se)
$amount = 20; // Joining Amount

// 2. User ko 'active' status mein update karein
$updateStatus = mysqli_query($conn, "UPDATE users SET status='active', joining_date=NOW() WHERE wallet='$user_wallet'");

if($updateStatus) {
    // 3. Boss ka Sponsor (Admin) dhoondhein
    $res = mysqli_query($conn, "SELECT referral_id FROM users WHERE wallet='$user_wallet'");
    $user = mysqli_fetch_assoc($res);
    $sponsor_id = $user['referral_id']; // Ye 425078 (Admin) aayega

    if(!empty($sponsor_id)) {
        // 4. Sponsor (Admin) ke stats update karein
        // total_directs = 1, direct_business = 10000, team_business = 10000
        mysqli_query($conn, "UPDATE users SET 
            total_directs = total_directs + 1, 
            direct_business = direct_business + $amount,
            team_business = team_business + $amount 
            WHERE account_id = '$sponsor_id'");

        // 5. Sponsor ko Direct Income dein (5% of 10,000 = 500)
        $income = $amount * 0.05;
        
        // Income table mein update (Admin ki wallet ke liye)
        mysqli_query($conn, "UPDATE incomes SET direct_income = direct_income + $income 
                            WHERE wallet = (SELECT wallet FROM users WHERE account_id='$sponsor_id')");

        // 6. Income Log entry (Dashboard report ke liye)
        mysqli_query($conn, "INSERT INTO income_logs (wallet, amount, type, description) 
                            VALUES ((SELECT wallet FROM users WHERE account_id='$sponsor_id'), $income, 'direct', 'Direct Income from $user_wallet')");

        echo "✅ Success: Boss is now Active and Admin received Direct Income!";
    }
} else {
    echo "❌ Error: Could not update user status.";
}
?>