<?php
// backend/admin/trigger-roi.php
header('Content-Type: application/json');
require_once '../config/db.php';

// A. USER ROI (Standard)
$roi_slabs = [
    0=>0.50, 1=>0.75, 2=>1.00, 3=>1.50, 4=>1.75, 5=>2.25, 
    6=>2.50, 7=>3.00, 8=>3.25, 9=>3.75, 10=>4.00, 26=>10.00 
];

// B. LEVEL PERCENTAGE (Level 2 se 27 tak Fixed)
// Level 1 Dynamic hoga (Booster ke hisaab se)
$level_percent = [
    2 => 0.10, 3 => 0.5, 4 => 0.5, 5 => 0.4, 6 => 0.4, 
    7 => 0.3, 8 => 0.3, 9 => 0.2, 10 => 0.2,
    11=>0.1, 12=>0.1, 13=>0.1, 14=>0.1, 15=>0.1, 16=>0.1,
    17=>0.1, 18=>0.1, 19=>0.1, 20=>0.1, 21=>0.1, 22=>0.1, 23=>0.1,
    24=>0.2, 25=>0.3, 26=>0.4, 27=>0.5 
];

$count = 0;
$today = date('Y-m-d');

// PROCESS ALL USERS
$sql = "SELECT DISTINCT wallet, account_id, referral_id FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while ($user = $result->fetch_assoc()) {
        
        $wallet = $user['wallet'];
        $my_code = $user['account_id'];
        $upline_code = $user['referral_id'];

        // 1. SELF ROI
        $invQ = $conn->query("SELECT SUM(amount) as total FROM deposits WHERE wallet = '$wallet' AND status = 'success'");
        $invData = $invQ->fetch_assoc();
        $my_investment = floatval($invData['total'] ?? 0);

        if ($my_investment < 1) continue; 

        // Active Directs
        $directQ = $conn->query("SELECT COUNT(DISTINCT u.id) as cnt FROM users u JOIN deposits d ON u.wallet = d.wallet WHERE u.referral_id = '$my_code' AND d.status = 'success' AND d.amount >= 20");
        $dRow = $directQ->fetch_assoc();
        $active_directs = intval($dRow['cnt']);

        $roi_rate = isset($roi_slabs[$active_directs]) ? $roi_slabs[$active_directs] : 10.00;
        $roi_amount = ($my_investment * $roi_rate) / 100;

        if ($roi_amount > 0) {
            // Pay Self ROI
            $conn->query("INSERT INTO roi_logs (wallet, invested_amount, active_directs, roi_rate, roi_amount, date) VALUES ('$wallet', '$my_investment', '$active_directs', '$roi_rate', '$roi_amount', '$today')");
            
            // 2. LEVEL INCOME (With Booster Logic)
            $curr_upline = $upline_code;
            $level = 1;

            while($level <= 27 && !empty($curr_upline)) {
                
                // Get Upline Info
                $upQ = $conn->query("SELECT * FROM users WHERE account_id = '$curr_upline'");
                if($upQ->num_rows == 0) break;
                
                $uplineData = $upQ->fetch_assoc();
                $upline_wallet = $uplineData['wallet'];

                // Check Upline Investment (Must be active)
                $upInvQ = $conn->query("SELECT SUM(amount) as t FROM deposits WHERE wallet = '$upline_wallet' AND status='success'");
                $upInvR = $upInvQ->fetch_assoc();
                $upline_invest_amount = floatval($upInvR['t'] ?? 0);
                
                // Upline ko paisa tabhi milega agar usne invest kiya hai
                if($upline_invest_amount > 0) {
                    
                    $percent = 0;

                    // 🔥 BOOSTER LOGIC (SIRF LEVEL 1 KE LIYE) 🔥
                    if($level == 1) {
                        $join_time = strtotime($uplineData['created_at']);
                        
                        // Count Directs with Investment >= Upline Investment
                        $boostQ = $conn->query("
                            SELECT u.created_at, SUM(d.amount) as inv 
                            FROM users u 
                            JOIN deposits d ON u.wallet = d.wallet 
                            WHERE u.referral_id = '$curr_upline' 
                            AND d.status = 'success'
                            GROUP BY u.id
                            HAVING inv >= $upline_invest_amount
                        ");

                        $cnt24 = 0; $cnt48 = 0; $cnt72 = 0;

                        while($bRow = $boostQ->fetch_assoc()) {
                            $direct_time = strtotime($bRow['created_at']);
                            $diff_hours = ($direct_time - $join_time) / 3600;

                            if($diff_hours <= 24) $cnt24++;
                            if($diff_hours <= 48) $cnt48++;
                            if($diff_hours <= 72) $cnt72++;
                        }

                        // Determine Booster Percentage
                        $booster_stage = 0;
                        if($cnt72 >= 6) { 
                            $percent = 0.30; $booster_stage = 3; 
                        } elseif($cnt48 >= 4) { 
                            $percent = 0.25; $booster_stage = 2; 
                        } elseif($cnt24 >= 2) { 
                            $percent = 0.20; $booster_stage = 1; 
                        } else { 
                            $percent = 0.15; $booster_stage = 0; // Default Standard
                        }

                        // Update User's Booster Status (for Dashboard)
                        $conn->query("UPDATE users SET booster_level = '$booster_stage' WHERE wallet = '$upline_wallet'");

                    } else {
                        // Level 2-27 (Fixed)
                        $percent = isset($level_percent[$level]) ? $level_percent[$level] : 0;
                    }
                    
                    // Calculate Bonus
                    $bonus = ($roi_amount * $percent) / 100;

                    if($bonus > 0) {
                        $check = $conn->query("SELECT id FROM incomes WHERE wallet = '$upline_wallet'");
                        if($check->num_rows > 0) {
                            $conn->query("UPDATE incomes SET level_income = level_income + $bonus WHERE wallet = '$upline_wallet'");
                        } else {
                            $conn->query("INSERT INTO incomes (wallet, level_income) VALUES ('$upline_wallet', '$bonus')");
                        }
                        $conn->query("INSERT INTO level_logs (wallet, from_user, level, percentage, amount, date) VALUES ('$upline_wallet', '$my_code', '$level', '$percent', '$bonus', '$today')");
                    }
                }

                $curr_upline = $uplineData['referral_id']; // Next Upline
                $level++;
            }
            $count++;
        }
    }
}

// SYNC DASHBOARD
$conn->query("UPDATE incomes i JOIN (SELECT wallet, SUM(roi_amount) as total FROM roi_logs GROUP BY wallet) l ON i.wallet = l.wallet SET i.roi_income = l.total");
$conn->query("UPDATE incomes i JOIN (SELECT wallet, SUM(amount) as total FROM level_logs GROUP BY wallet) l ON i.wallet = l.wallet SET i.level_income = l.total");
$conn->query("UPDATE users u JOIN incomes i ON u.wallet = i.wallet LEFT JOIN (SELECT wallet, SUM(amount) as w FROM withdrawals WHERE status!='rejected' GROUP BY wallet) w ON u.wallet=w.wallet SET u.balance = (i.roi_income + i.level_income + i.direct_income) - COALESCE(w.w, 0)");

echo json_encode(["status" => "success", "message" => "Booster Income Generated for $count users!"]);
?>