<?php
// backend/api/get-team.php
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
require_once '../config/db.php';

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

$uQ = mysqli_query($conn, "SELECT account_id FROM users WHERE wallet = '$wallet'");
$user = mysqli_fetch_assoc($uQ);
if(!$user) { echo json_encode(["status" => "error", "message" => "User not found"]); exit; }

$my_code = $user['account_id'];

// Level wise percentages
$rates = [
    1 => 0.02,   // L1: 2%
    2 => 0.01,   // L2: 1%
    3 => 0.01,   // L3: 1%
    4 => 0.005,  // L4: 0.5%
    5 => 0.005,  // L5: 0.5%
    6 => 0.003,  // L6: 0.3%
    7 => 0.003,  // L7: 0.3%
    8 => 0.003   // L8: 0.3%
];

$full_team = [];
$summary = [
    "total_members" => 0,
    "total_business" => 0,
    "total_income" => 0,
    "active_members" => 0
];

// Function to get team members for multiple levels
function getLevelTeam($conn, $parent_ids, $level, $rates, &$full_team, &$summary) {
    if ($level > 8 || empty($parent_ids)) return;

    $ids_string = "'" . implode("','", $parent_ids) . "'";
    $sql = "SELECT u.account_id, u.name, u.wallet, u.created_at, 
            COALESCE(SUM(d.amount), 0) as total_invested 
            FROM users u 
            LEFT JOIN deposits d ON u.wallet = d.wallet AND d.status = 'success'
            WHERE u.referral_id IN ($ids_string)
            GROUP BY u.account_id";
    
    $result = mysqli_query($conn, $sql);
    $next_level_ids = [];

    while($row = mysqli_fetch_assoc($result)) {
        $invested = floatval($row['total_invested']);
        $income = $invested * $rates[$level];
        
        $summary['total_members']++;
        $summary['total_business'] += $invested;
        $summary['total_income'] += $income;
        if($invested > 0) $summary['active_members']++;

        $full_team[] = [
            "level" => "L" . $level,
            "name" => $row['name'],
            "account_id" => $row['account_id'],
            "invested" => $invested,
            "income" => $income,
            "rate" => ($rates[$level] * 100) . "%",
            "date" => date("d M Y", strtotime($row['created_at']))
        ];
        
        $next_level_ids[] = $row['account_id'];
    }

    // Call for next level
    getLevelTeam($conn, $next_level_ids, $level + 1, $rates, $full_team, $summary);
}

// Start fetching from Level 1
getLevelTeam($conn, [$my_code], 1, $rates, $full_team, $summary);

echo json_encode([
    "status" => "success",
    "summary" => $summary,
    "team" => $full_team
]);