<?php

error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");

require_once '../config/db.php';

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

$safeWallet = mysqli_real_escape_string($conn, $wallet);

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

$acc_id = $user_data['account_id'];

// ── First successful deposit date
$first_dep_row = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT MIN(created_at) AS fd FROM deposits WHERE wallet='$safeWallet' AND status='success'"));
$first_deposit_date = $first_dep_row['fd'] ?? null;

// ── Total investment
$total_inv = floatval(mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT COALESCE(SUM(amount),0) AS amt FROM deposits
     WHERE wallet='$safeWallet' AND status='success'"))['amt']);

// ── Active directs (deposit >= 60)
$adResult = mysqli_query($conn,
    "SELECT u.wallet, u.name, MIN(d.created_at) AS joined_at
     FROM users u JOIN deposits d ON u.wallet = d.wallet
     WHERE u.referral_id = '$acc_id' AND d.status = 'success' AND d.amount >= 60
     GROUP BY u.wallet ORDER BY joined_at ASC");

$active_direct_rows = [];
while ($r = mysqli_fetch_assoc($adResult)) { $active_direct_rows[] = $r; }
$total_active_directs = count($active_direct_rows);
$tier_window_anchor   = !empty($active_direct_rows) ? $active_direct_rows[0]['joined_at'] : null;

// ════════════════════════════════════════════════════════════
// HELPERS
// ════════════════════════════════════════════════════════════
// ════════════════════════════════════════════════════════════
// ADMIN BALANCE OVERRIDE CHECK
// ════════════════════════════════════════════════════════════
$override_row     = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT * FROM balance_overrides WHERE wallet = '$safeWallet' LIMIT 1"));
$admin_direct_bal = ($override_row && $override_row['direct_balance'] !== null)
                    ? (float)$override_row['direct_balance']
                    : null;
$has_override     = $admin_direct_bal !== null;

function countInWindow($rows, $windowStartTs, $hours) {
    $endTs = $windowStartTs + ($hours * 3600);
    $cnt   = 0;
    foreach ($rows as $r) {
        $t = strtotime($r['joined_at']);
        if ($t >= $windowStartTs && $t <= $endTs) $cnt++;
    }
    return $cnt;
}

function getNextDirectAfter($rows, $afterTs) {
    foreach ($rows as $i => $r) {
        if (strtotime($r['joined_at']) > $afterTs)
            return ['joined_at' => $r['joined_at'], 'index' => $i];
    }
    return null;
}

// ════════════════════════════════════════════════════════════
// READ TIER STATE FROM DB
// ════════════════════════════════════════════════════════════
$reward_tier_1      = intval($user_data['reward_tier_1']      ?? 0);
$reward_tier_2      = intval($user_data['reward_tier_2']      ?? 0);
$reward_tier_3      = intval($user_data['reward_tier_3']      ?? 0);
$tier2_window_start = $user_data['tier2_window_start']        ?? null;
$tier3_window_start = $user_data['tier3_window_start']        ?? null;
$tier2_window_index = intval($user_data['tier2_window_index'] ?? 0);
$tier3_window_index = intval($user_data['tier3_window_index'] ?? 0);
$nowTs = time();

// ════════════════════════════════════════════════════════════
// TIER 1 — 3 directs in 24h (one-time window)
// ════════════════════════════════════════════════════════════
if ($reward_tier_1 == 0 && !empty($tier_window_anchor)) {
    $inWin = countInWindow($active_direct_rows, strtotime($tier_window_anchor), 24);
    if ($inWin >= 3) {
        mysqli_query($conn, "UPDATE users SET reward_tier_1 = 1 WHERE account_id = '$acc_id'");
        $reward_tier_1 = 1;
    }
}

// ════════════════════════════════════════════════════════════
// TIER 2 — 9 directs in 3 days (72h), rolling window
// ════════════════════════════════════════════════════════════
if ($reward_tier_2 == 0 && !empty($tier_window_anchor)) {
    if (empty($tier2_window_start)) {
        $tier2_window_start = $tier_window_anchor;
        $tier2_window_index = 0;
        $s = mysqli_real_escape_string($conn, $tier2_window_start);
        mysqli_query($conn, "UPDATE users SET tier2_window_start='$s', tier2_window_index=0 WHERE account_id='$acc_id'");
    }
    $loopLimit = 100; $loops = 0;
    while ($loops++ < $loopLimit) {
        $wsTs  = strtotime($tier2_window_start);
        $endTs = $wsTs + (3 * 24 * 3600);
        $inWin = countInWindow($active_direct_rows, $wsTs, 72);
        if ($inWin >= 9) {
            mysqli_query($conn, "UPDATE users SET reward_tier_2 = 1 WHERE account_id='$acc_id'");
            $reward_tier_2 = 1; break;
        }
        if ($nowTs < $endTs) break;
        $next = getNextDirectAfter($active_direct_rows, $endTs);
        if ($next === null) break;
        $tier2_window_start = $next['joined_at'];
        $tier2_window_index = $next['index'];
        $s = mysqli_real_escape_string($conn, $tier2_window_start);
        mysqli_query($conn, "UPDATE users SET tier2_window_start='$s', tier2_window_index={$next['index']} WHERE account_id='$acc_id'");
    }
}

// ════════════════════════════════════════════════════════════
// TIER 3 — 27 directs in 9 days (216h), rolling window
// ════════════════════════════════════════════════════════════
if ($reward_tier_3 == 0 && !empty($tier_window_anchor)) {
    if (empty($tier3_window_start)) {
        $tier3_window_start = $tier_window_anchor;
        $tier3_window_index = 0;
        $s = mysqli_real_escape_string($conn, $tier3_window_start);
        mysqli_query($conn, "UPDATE users SET tier3_window_start='$s', tier3_window_index=0 WHERE account_id='$acc_id'");
    }
    $loopLimit = 100; $loops = 0;
    while ($loops++ < $loopLimit) {
        $wsTs  = strtotime($tier3_window_start);
        $endTs = $wsTs + (9 * 24 * 3600);                       // ✅ 9 days
        $inWin = countInWindow($active_direct_rows, $wsTs, 216); // ✅ 216h = 9 days
        if ($inWin >= 27) {
            mysqli_query($conn, "UPDATE users SET reward_tier_3 = 1 WHERE account_id='$acc_id'");
            $reward_tier_3 = 1; break;
        }
        if ($nowTs < $endTs) break;
        $next = getNextDirectAfter($active_direct_rows, $endTs);
        if ($next === null) break;
        $tier3_window_start = $next['joined_at'];
        $tier3_window_index = $next['index'];
        $s = mysqli_real_escape_string($conn, $tier3_window_start);
        mysqli_query($conn, "UPDATE users SET tier3_window_start='$s', tier3_window_index={$next['index']} WHERE account_id='$acc_id'");
    }
}

// ════════════════════════════════════════════════════════════
// TRADE RATE & REWARD BONUS  — Tier1:$12 | Tier2:$36 | Tier3:$81
// ════════════════════════════════════════════════════════════
$user_trade_rate = 4; $reward_bonus = 0;
if     ($reward_tier_3 == 1) { $user_trade_rate = 7; $reward_bonus = 81; }
elseif ($reward_tier_2 == 1) { $user_trade_rate = 6; $reward_bonus = 36; }
elseif ($reward_tier_1 == 1) { $user_trade_rate = 5; $reward_bonus = 12; }

// ════════════════════════════════════════════════════════════
// TIER PROGRESS for frontend
// ════════════════════════════════════════════════════════════

// Tier 1 progress
$tier1_count = 0; $tier1_expired = false; $tier1_secs_left = 0;
if (!empty($tier_window_anchor)) {
    $t1WsTs        = strtotime($tier_window_anchor);
    $t1WeTs        = $t1WsTs + (24 * 3600);
    $tier1_count   = countInWindow($active_direct_rows, $t1WsTs, 24);
    $tier1_expired = ($reward_tier_1 == 0 && $nowTs >= $t1WeTs);
    $tier1_secs_left = ($reward_tier_1 == 0 && !$tier1_expired) ? max(0, $t1WeTs - $nowTs) : 0;
}

// Tier 2 progress
$tier2_count = 0; $tier2_secs_left = 0; $tier2_expired = false;
if ($reward_tier_2 == 1) {
    $tier2_count = 9;
} elseif (!empty($tier2_window_start)) {
    $t2WsTs  = strtotime($tier2_window_start);
    $t2EndTs = $t2WsTs + (3 * 24 * 3600);
    if ($nowTs >= $t2EndTs) {
        $tier2_expired = true;
    } else {
        $tier2_count     = countInWindow($active_direct_rows, $t2WsTs, 72);
        $tier2_secs_left = max(0, $t2EndTs - $nowTs);
    }
}

// Tier 3 progress
$tier3_count = 0; $tier3_secs_left = 0; $tier3_expired = false;
if ($reward_tier_3 == 1) {
    $tier3_count = 27;
} elseif (!empty($tier3_window_start)) {
    $t3WsTs  = strtotime($tier3_window_start);
    $t3EndTs = $t3WsTs + (9 * 24 * 3600);                       // ✅ 9 days
    if ($nowTs >= $t3EndTs) {
        $tier3_expired = true;
    } else {
        $tier3_count     = countInWindow($active_direct_rows, $t3WsTs, 216); // ✅ 216h
        $tier3_secs_left = max(0, $t3EndTs - $nowTs);
    }
}

// ════════════════════════════════════════════════════════════
// STOP FLAGS
// ════════════════════════════════════════════════════════════
$stop_roi   = intval($user_data['stop_roi']   ?? 0);
$stop_level = intval($user_data['stop_level'] ?? 0);
$stop_all   = intval($user_data['stop_all']   ?? 0);

// ════════════════════════════════════════════════════════════
// MULTI-LEVEL NETWORK COUNT (Level 1–6, active deposit >= 60)
// ════════════════════════════════════════════════════════════
function getActiveMembersAtLevel($conn, $parentIds, $depth, $maxDepth, &$levelCounts) {
    if ($depth > $maxDepth || empty($parentIds)) return;
    $escaped  = array_map(fn($id) => "'" . mysqli_real_escape_string($conn, $id) . "'", $parentIds);
    $inClause = implode(',', $escaped);
    $res      = mysqli_query($conn,
        "SELECT u.account_id, u.wallet FROM users u WHERE u.referral_id IN ($inClause)");
    $nextLevelIds = []; $childWallets = [];
    while ($row = mysqli_fetch_assoc($res)) {
        $nextLevelIds[] = $row['account_id'];
        $childWallets[] = "'" . mysqli_real_escape_string($conn, $row['wallet']) . "'";
    }
    if (empty($nextLevelIds)) { $levelCounts[$depth] = 0; return; }
    $walletIn  = implode(',', $childWallets);
    $activeRes = mysqli_query($conn,
        "SELECT wallet FROM deposits WHERE wallet IN ($walletIn)
         AND status='success' AND amount >= 60 GROUP BY wallet");
    $levelCounts[$depth] = mysqli_num_rows($activeRes);
    getActiveMembersAtLevel($conn, $nextLevelIds, $depth + 1, $maxDepth, $levelCounts);
}

$levelCounts = [];
getActiveMembersAtLevel($conn, [$acc_id], 1, 6, $levelCounts);
for ($i = 1; $i <= 6; $i++) { if (!isset($levelCounts[$i])) $levelCounts[$i] = 0; }

// ════════════════════════════════════════════════════════════
// DIRECT INCOME + REFERRALS LIST
// ════════════════════════════════════════════════════════════
$direct_income = 0; $referrals_list = [];
$ref_query = mysqli_query($conn,
    "SELECT u.name, u.wallet, u.created_at FROM users u WHERE u.referral_id='$acc_id' ORDER BY u.id DESC");
while ($row = mysqli_fetch_assoc($ref_query)) {
    $rw      = mysqli_real_escape_string($conn, $row['wallet']);
    $ref_inv = floatval(mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT COALESCE(SUM(amount),0) AS amt FROM deposits
         WHERE wallet='$rw' AND status='success'"))['amt']);
    if ($ref_inv > 0) $direct_income += $ref_inv * 0.03;
    $rw_dep = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT MIN(created_at) AS fd FROM deposits WHERE wallet='$rw' AND status='success' AND amount >= 60"));
    $referrals_list[] = [
        "name"         => $row['name'],
        "wallet"       => $row['wallet'],
        "status"       => ($ref_inv >= 60) ? 'active' : 'inactive',
        "investment"   => $ref_inv,
        "l1_earn"      => round($ref_inv * 0.03, 2),
        "created_at"   => date('d M Y', strtotime($row['created_at'])),
        "deposit_date" => $rw_dep['fd'] ?? null
    ];
}

// ════════════════════════════════════════════════════════════
// ROI, LEVEL, JOINING BONUS
// ════════════════════════════════════════════════════════════
$roi_income = floatval(mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT COALESCE(SUM(pnl_amount),0) AS total FROM trade_logs WHERE wallet='$safeWallet'"))['total']);
$latest_trade_row = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT created_at FROM trade_logs WHERE wallet='$safeWallet' ORDER BY id DESC LIMIT 1"));
$latest_trade_ts  = $latest_trade_row ? strtotime($latest_trade_row['created_at']) * 1000 : 0;
$level_income  = floatval(mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT COALESCE(SUM(amount),0) AS total FROM level_logs WHERE wallet='$safeWallet'"))['total']);
$joining_bonus = $total_inv * 0.05;

// ════════════════════════════════════════════════════════════
// WITHDRAWAL TRACKING
// ════════════════════════════════════════════════════════════

// Income withdrawals
$profit_withdrawn = floatval(mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT COALESCE(SUM(amount),0) AS total FROM withdrawals
     WHERE wallet='$safeWallet' AND type='income' AND status='completed'"))['total']);
$profit_pending   = floatval(mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT COALESCE(SUM(amount),0) AS total FROM withdrawals
     WHERE wallet='$safeWallet' AND type='income' AND status='pending'"))['total']);
$total_profit_claimed = $profit_withdrawn + $profit_pending;

// Trading withdrawals
$trading_withdrawn = floatval(mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT COALESCE(SUM(amount),0) AS total FROM withdrawals
     WHERE wallet='$safeWallet' AND type='trading' AND status='completed'"))['total']);
$trading_pending   = floatval(mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT COALESCE(SUM(amount),0) AS total FROM withdrawals
     WHERE wallet='$safeWallet' AND type='trading' AND status='pending'"))['total']);
$total_trading_claimed = $trading_withdrawn + $trading_pending;

// Principal withdrawals
$principal_withdrawn = floatval(mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT COALESCE(SUM(amount),0) AS total FROM withdrawals
     WHERE wallet='$safeWallet' AND type='principal' AND status='completed'"))['total']);
$principal_pending   = floatval(mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT COALESCE(SUM(amount),0) AS total FROM withdrawals
     WHERE wallet='$safeWallet' AND type='principal' AND status='pending'"))['total']);
$total_principal_claimed = $principal_withdrawn + $principal_pending;

// Grand total
$grand_total_withdrawn = $profit_withdrawn + $trading_withdrawn + $principal_withdrawn;

// ════════════════════════════════════════════════════════════
// BALANCE CALCULATIONS
// ════════════════════════════════════════════════════════════
$gross_profit          = $roi_income + $direct_income + $reward_bonus + $joining_bonus + $level_income;
$profit_available      = max(0, $gross_profit - $total_profit_claimed);
$principal_available   = max(0, $total_inv - $total_principal_claimed);
$total_earned          = $direct_income + $level_income + $joining_bonus + $reward_bonus;
$earned_after_withdraw = max(0, $total_earned - $profit_withdrawn);
$balance               = max(0,
    $total_inv + max(0, $roi_income) + $direct_income + $level_income + $joining_bonus + $reward_bonus
    - $total_profit_claimed - $total_principal_claimed
);

// ════════════════════════════════════════════════════════════
// RESPONSE
// ════════════════════════════════════════════════════════════
echo json_encode([
    "status"             => "success",
    "name"               => $user_data['name'],
    "account_id"         => $acc_id,
    "user_joined"        => $user_data['created_at'],
    "first_deposit_date" => $first_deposit_date,
    "first_active_direct_time" => $tier_window_anchor,
    "user_status"        => ($total_inv >= 60) ? 'active' : 'inactive',
    "user_trade_rate"    => $user_trade_rate,

    "stop_roi"           => $stop_roi,
    "stop_level"         => $stop_level,
    "stop_all"           => $stop_all,

    "reward_tier_1"      => $reward_tier_1,
    "reward_tier_2"      => $reward_tier_2,
    "reward_tier_3"      => $reward_tier_3,
    "reward_bonus"       => $reward_bonus,

    "tier1_count"        => $tier1_count,
    "tier1_goal"         => 3,
    "tier1_secs_left"    => $tier1_secs_left,
    "tier1_expired"      => $tier1_expired,

    "tier2_count"        => $tier2_count,
    "tier2_goal"         => 9,
    "tier2_secs_left"    => $tier2_secs_left,
    "tier2_expired"      => $tier2_expired,
    "tier2_window_start" => $tier2_window_start,
    "tier2_window_index" => $tier2_window_index,

    "tier3_count"        => $tier3_count,
    "tier3_goal"         => 27,
    "tier3_secs_left"    => $tier3_secs_left,
    "tier3_expired"      => $tier3_expired,
    "tier3_window_start" => $tier3_window_start,
    "tier3_window_index" => $tier3_window_index,

    "active_directs"     => $total_active_directs,

    "roi_income"         => round($roi_income, 4),
    "direct_income"      => round($direct_income, 4),
    "level_income"       => round($level_income, 4),
    "joining_bonus"      => round($joining_bonus, 4),
    "latest_trade_ts"    => $latest_trade_ts,

    "profit_withdrawn"       => round($profit_withdrawn, 2),
    "profit_pending"         => round($profit_pending, 2),
    "trading_withdrawn"      => round($trading_withdrawn, 2),
    "trading_pending"        => round($trading_pending, 2),
    "principal_withdrawn"    => round($principal_withdrawn, 2),
    "principal_pending"      => round($principal_pending, 2),
    "total_withdrawal"       => round($grand_total_withdrawn, 2), // ✅ single key — income+trading+principal

    "profit_available"       => round($profit_available, 2),
    "principal_available"    => round($principal_available, 2),
    "total_trading_claimed"  => round($total_trading_claimed, 2),

    "total_investment"       => round($total_inv, 2),
    "total_earned"           => round($total_earned, 4),
    "earned_minus_withdrawn" => round($earned_after_withdraw, 2),
    "balance"                => round($balance, 4),
    "gross_profit"           => round($gross_profit, 4),

    "referrals"              => $referrals_list,
    "has_balance_override"   => $has_override,
"override_amount"        => $admin_direct_bal,
"override_reason"        => $override_row['reason'] ?? null,

    "level_counts"           => [
        $levelCounts[1],
        $levelCounts[2],
        $levelCounts[3],
        $levelCounts[4],
        $levelCounts[5],
        $levelCounts[6],
    ],
]);
?>