<?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'];

// ✅ SIRF 3% DIRECT INCOME — L1 only
$DIRECT_RATE = 0.03; // 3%

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

// L1 direct referrals only
$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 = '$my_code'
        GROUP BY u.account_id
        ORDER BY u.created_at DESC";

$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_assoc($result)) {
    $invested = floatval($row['total_invested']);
    $income   = $invested * $DIRECT_RATE; // 3% of investment

    $summary['total_members']++;
    $summary['total_business'] += $invested;
    $summary['total_income']   += $income;
    if ($invested > 0) $summary['active_members']++;

    $full_team[] = [
        "level"      => "L1",
        "name"       => $row['name'],
        "account_id" => $row['account_id'],
        "wallet"     => $row['wallet'],
        "invested"   => $invested,
        "income"     => round($income, 4),
        "rate"       => "3%",
        "date"       => date("d M Y", strtotime($row['created_at']))
    ];
}

echo json_encode([
    "status"  => "success",
    "summary" => [
        "total_members"  => $summary['total_members'],
        "active_members" => $summary['active_members'],
        "total_business" => round($summary['total_business'], 4),
        "total_income"   => round($summary['total_income'], 4),
        "direct_rate"    => "3%"
    ],
    "team" => $full_team
]);
?>