<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
// Reusable function to get wallet balance (wallet - pending withdrawals)
function getWalletBalance($conn, $userId) {
    $walletResult = $conn->query("SELECT wallet FROM users WHERE user_id = $userId");
    $wallet = $walletResult->fetch_assoc()['wallet'] ?? 0;

    $reqResult = $conn->query("SELECT SUM(amount) as requested FROM withdrawal_requests WHERE user_id = $userId AND status = 'pending'");
    $requested = $reqResult->fetch_assoc()['requested'] ?? 0;

    return $wallet - $requested;
}

// Process level-based rewards
function processLevelPayments($conn, $userId, $levelAmounts) {
    $rewardsGiven = [];

    // Get already paid levels
    $paidLevels = [];
    $check = $conn->query("SELECT level FROM level_rewards WHERE user_id = $userId");
    while ($r = $check->fetch_assoc()) {
        $paidLevels[] = $r['level'];
    }

    // Build user tree
    $tree = buildTreeArray($conn, $userId, 11);

    // Count members per level
    $levelCounts = [];
    foreach ($tree as $node) {
        $level = $node['level'];
        if (!isset($levelCounts[$level])) $levelCounts[$level] = 0;
        $levelCounts[$level]++;
    }

    // Check if any level is fully completed
    for ($lvl = 1; $lvl <= 11; $lvl++) {
        $required = pow(2, $lvl);
        $has = $levelCounts[$lvl] ?? 0;

        if ($has == $required && !in_array($lvl, $paidLevels)) {
            $amount = $levelAmounts[$lvl] ?? 0;

            // Update user's wallet
            $conn->query("UPDATE users SET wallet = wallet + $amount WHERE user_id = $userId");

            // Mark level as rewarded
            $conn->query("INSERT INTO level_rewards (user_id, level, amount, paid_at) VALUES ($userId, $lvl, $amount, NOW())");

            $rewardsGiven[] = ['level' => $lvl, 'amount' => $amount];
        }
    }

    return $rewardsGiven;
}

// Build tree recursively and return flat array
function buildTreeArray($conn, $parentId, $maxDepth = 11, $level = 1, &$result = []) {
    if ($level > $maxDepth) return $result;

    $res = $conn->query("SELECT user_id, placement_id FROM users WHERE placement_id = $parentId");
    while ($row = $res->fetch_assoc()) {
        $result[] = [
            'id' => $row['user_id'],
            'parent_id' => $row['placement_id'],
            'level' => $level
        ];

        buildTreeArray($conn, $row['user_id'], $maxDepth, $level + 1, $result);
    }

    return $result;
}

// Count completed levels (number of rows in level_rewards table)
function getCompletedLevels($conn, $userId) {
    $res = $conn->query("SELECT COUNT(*) as total FROM level_rewards WHERE user_id = $userId");
    $row = $res->fetch_assoc();
    return $row ? $row['total'] : 0;
}
?>
