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

// Testing ke liye aap yahan manual wallet address bhi daal sakte hain
$user_wallet = $_POST['wallet']; // Jis user ko active karna hai (e.g. Boss)
$amount = 20; // Plan Joining Amount

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

if($updateStatus) {
    // 2. Sponsor (Upline) ki ID nikalein
    $res = mysqli_query($conn, "SELECT referral_id FROM users WHERE wallet='$user_wallet'");
    $user = mysqli_fetch_assoc($res);
    $upline_id = $user['referral_id'];

    if(!empty($upline_id)) {
        // 3. Sponsor ke business columns update karein (Taaki dashboard par data dikhe)
        mysqli_query($conn, "UPDATE users SET 
            total_directs = total_directs + 1, 
            direct_business = direct_business + $amount,
            team_business = team_business + $amount 
            WHERE account_id = '$upline_id'");

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

        // 5. Income Log entry (Taaki user history mein dekh sake)
        mysqli_query($conn, "INSERT INTO income_logs (wallet, amount, type, description) 
                            VALUES ((SELECT wallet FROM users WHERE account_id='$upline_id'), $income, 'direct', 'Direct Income from $user_wallet')");

        echo json_encode(["status" => "success", "message" => "User Activated & Business Updated"]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "Update Failed"]);
}
?>