<?php
require '../element/connection.php';
require '../config/rewards_config.php';

$rewardsConfig = include '../config/rewards_config.php';
$userId = (int)$_GET['user_id'];

// Get user details
$user = $conn->query("SELECT * FROM users WHERE user_id = $userId")->fetch_assoc();

if (!$user) {
    echo json_encode(['error' => 'User not found']);
    exit;
}

// Calculate additional data
$currentLevel = getCurrentLevel($conn, $userId);
$teamSize = calculateTeamSize($conn, $userId);
$totalEarnings = calculateTotalEarnings($conn, $userId);
$completedLevels = calculateUserLevels($conn, $userId);

// Count direct downline
$directCount = 0;
$positions = ['left_1_id', 'left_2_id', 'right_1_id', 'right_2_id'];
foreach ($positions as $pos) {
    if (!empty($user[$pos]) && $user[$pos] != 0) $directCount++;
}

// Format joining date
$joiningDate = date('d M Y', strtotime($user['joining_date'] ?? 'now'));

// Prepare response
$response = [
    'user_id' => $user['user_id'],
    'name' => $user['name'],
    'rank' => $user['rank'] ?? 'Bronze',
    'wallet' => number_format($user['wallet'] ?? 0),
    'status' => (int)($user['status'] ?? 1),
    'current_level' => $currentLevel,
    'max_levels' => $rewardsConfig['max_levels'] ?? 10,
    'direct_count' => $directCount,
    'team_size' => $teamSize,
    'completed_levels' => $completedLevels,
    'total_earnings' => number_format($totalEarnings),
    'joining_date' => $joiningDate,
    'last_active' => $user['last_active'] ?? 'N/A'
];

header('Content-Type: application/json');
echo json_encode($response);

// Include the helper functions
function getCurrentLevel($conn, $user_id) {
    $result = $conn->query("SELECT MAX(level) as current_level FROM level_rewards WHERE user_id = $user_id AND paid = 1");
    $row = $result->fetch_assoc();
    return $row['current_level'] ?? 0;
}

function calculateTeamSize($conn, $user_id) {
    $teamSize = 0;
    $queue = [$user_id];
    $visited = [];
    
    while (!empty($queue)) {
        $current = array_shift($queue);
        if (in_array($current, $visited)) continue;
        $visited[] = $current;
        
        $user = $conn->query("SELECT left_1_id, left_2_id, right_1_id, right_2_id FROM users WHERE user_id = $current")->fetch_assoc();
        
        $positions = ['left_1_id', 'left_2_id', 'right_1_id', 'right_2_id'];
        foreach ($positions as $pos) {
            if (!empty($user[$pos]) && $user[$pos] != 0) {
                $teamSize++;
                $queue[] = $user[$pos];
            }
        }
    }
    
    return $teamSize;
}

function calculateTotalEarnings($conn, $user_id) {
    $result = $conn->query("SELECT SUM(amount) as total FROM level_rewards WHERE user_id = $user_id AND paid = 1");
    $row = $result->fetch_assoc();
    return $row['total'] ?? 0;
}

function calculateUserLevels($conn, $userId) {
    $currentLevelUsers = [$userId];
    $completedLevels = 0;

    while (!empty($currentLevelUsers)) {
        $nextLevelUsers = [];
        $allUsersHaveFourChildren = true;

        foreach ($currentLevelUsers as $uid) {
            $query = "SELECT left_1_id, left_2_id, right_1_id, right_2_id FROM users WHERE user_id = $uid";
            $result = $conn->query($query);

            if ($row = $result->fetch_assoc()) {
                if (
                    empty($row['left_1_id']) || $row['left_1_id'] == 0 ||
                    empty($row['left_2_id']) || $row['left_2_id'] == 0 ||
                    empty($row['right_1_id']) || $row['right_1_id'] == 0 ||
                    empty($row['right_2_id']) || $row['right_2_id'] == 0
                ) {
                    $allUsersHaveFourChildren = false;
                    break;
                }

                $nextLevelUsers[] = $row['left_1_id'];
                $nextLevelUsers[] = $row['left_2_id'];
                $nextLevelUsers[] = $row['right_1_id'];
                $nextLevelUsers[] = $row['right_2_id'];
            } else {
                $allUsersHaveFourChildren = false;
                break;
            }
        }

        if ($allUsersHaveFourChildren) {
            $completedLevels++;
            $currentLevelUsers = $nextLevelUsers;
        } else {
            break;
        }
    }

    return $completedLevels;
}
?>