<?php
require '../element/connection.php';
session_start();

$user_id = $_SESSION['user_id'] ?? 0;

if ($user_id == 0) {
    header("Location: ../login.php");
    exit;
}

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

// Get direct count
$directCount = $conn->query("SELECT COUNT(*) as count FROM users WHERE sponsor_id = $user_id")->fetch_assoc()['count'];

// Get completed levels
$completedLevels = [];
$result = $conn->query("SELECT level FROM level_rewards WHERE user_id = $user_id AND paid = 1 ORDER BY level");
while ($row = $result->fetch_assoc()) {
    $completedLevels[] = $row['level'];
}

// Get next level to complete
$nextLevel = 1;
while (in_array($nextLevel, $completedLevels)) {
    $nextLevel++;
}

// Get expected users at next level
$expectedUsers = pow(4, $nextLevel);
$currentUsersAtLevel = 0;
$levelComplete = false;

if ($nextLevel <= 7) {
    $usersAtLevel = getUsersAtLevel($conn, $user_id, $nextLevel);
    $currentUsersAtLevel = count($usersAtLevel);
    
    // Check if all users at this level have 4 directs
    $allHaveFourDirects = true;
    foreach ($usersAtLevel as $uid) {
        $dirCount = $conn->query("SELECT COUNT(*) as count FROM users WHERE sponsor_id = $uid")->fetch_assoc()['count'];
        if ($dirCount < 4) {
            $allHaveFourDirects = false;
            break;
        }
    }
    
    $levelComplete = ($currentUsersAtLevel >= $expectedUsers && $allHaveFourDirects);
}

function getUsersAtLevel($conn, $user_id, $targetLevel) {
    $currentLevelUsers = [$user_id];
    $currentDepth = 0;
    
    while ($currentDepth < $targetLevel && !empty($currentLevelUsers)) {
        $nextLevelUsers = [];
        
        foreach ($currentLevelUsers as $uid) {
            $user = $conn->query("SELECT left_1_id, left_2_id, right_1_id, right_2_id FROM users WHERE user_id = $uid")->fetch_assoc();
            
            if ($user) {
                if ($user['left_1_id'] != 0) $nextLevelUsers[] = $user['left_1_id'];
                if ($user['left_2_id'] != 0) $nextLevelUsers[] = $user['left_2_id'];
                if ($user['right_1_id'] != 0) $nextLevelUsers[] = $user['right_1_id'];
                if ($user['right_2_id'] != 0) $nextLevelUsers[] = $user['right_2_id'];
            }
        }
        
        $currentLevelUsers = $nextLevelUsers;
        $currentDepth++;
    }
    
    return ($currentDepth == $targetLevel) ? $currentLevelUsers : [];
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>C1 Status Check</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h3>Your Progress Status</h3>
                    </div>
                    <div class="card-body">
                        <h5>User ID: <?php echo $user_id; ?></h5>
                        <h5>Name: <?php echo $user['name']; ?></h5>
                        <h5>Current Rank: <?php echo $user['rank']; ?></h5>
                        
                        <hr>
                        
                        <div class="alert <?php echo ($directCount >= 4) ? 'alert-success' : 'alert-warning'; ?>">
                            <h5>C1 Status: <?php echo ($directCount >= 4) ? '✅ COMPLETED' : '❌ NOT COMPLETED'; ?></h5>
                            <p>Direct Users: <?php echo $directCount; ?> / 4</p>
                        </div>
                        
                        <hr>
                        
                        <h4>Level Progress</h4>
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Level</th>
                                    <th>Rank</th>
                                    <th>Income</th>
                                    <th>Status</th>
                                    <th>Progress</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $levels = [
                                    1 => ['STARTER', 1000],
                                    2 => ['BRONZE', 1600],
                                    3 => ['SILVER', 6500],
                                    4 => ['GOLD', 28000],
                                    5 => ['PLATINUM', 130000],
                                    6 => ['DIAMOND', 540000],
                                    7 => ['BLACK DIAMOND', 2250000]
                                ];
                                
                                for ($i = 1; $i <= 7; $i++):
                                    $completed = in_array($i, $completedLevels);
                                    $isNext = ($i == $nextLevel);
                                    
                                    if ($i == $nextLevel):
                                        $usersAtLevel = getUsersAtLevel($conn, $user_id, $i);
                                        $current = count($usersAtLevel);
                                        $expected = pow(4, $i);
                                        $progress = ($current / $expected) * 100;
                                        
                                        // Check if all have 4 directs
                                        $allHaveFour = true;
                                        foreach ($usersAtLevel as $uid) {
                                            $dc = $conn->query("SELECT COUNT(*) as count FROM users WHERE sponsor_id = $uid")->fetch_assoc()['count'];
                                            if ($dc < 4) {
                                                $allHaveFour = false;
                                                break;
                                            }
                                        }
                                    endif;
                                ?>
                                <tr class="<?php 
                                    if ($completed) echo 'table-success';
                                    elseif ($isNext) echo 'table-info';
                                ?>">
                                    <td>Level <?php echo $i; ?></td>
                                    <td><?php echo $levels[$i][0]; ?></td>
                                    <td>₹<?php echo number_format($levels[$i][1]); ?></td>
                                    <td>
                                        <?php if ($completed): ?>
                                            <span class="badge bg-success">Completed</span>
                                        <?php elseif ($isNext && $directCount >= 4): ?>
                                            <span class="badge bg-primary">In Progress</span>
                                        <?php elseif ($isNext && $directCount < 4): ?>
                                            <span class="badge bg-warning">Need C1 First</span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">Locked</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($isNext && $directCount >= 4): ?>
                                            <div class="progress">
                                                <div class="progress-bar" style="width: <?php echo $progress; ?>%">
                                                    <?php echo $current; ?>/<?php echo $expected; ?> users
                                                </div>
                                            </div>
                                            <?php if (!$allHaveFour): ?>
                                                <small class="text-danger">⚠️ Some users need 4 directs</small>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endfor; ?>
                            </tbody>
                        </table>
                        
                        <?php if ($nextLevel <= 7 && $directCount >= 4 && $levelComplete): ?>
                            <div class="alert alert-success">
                                <h5>🎉 Congratulations! Level <?php echo $nextLevel; ?> is complete!</h5>
                                <p>Click the button below to claim your reward of ₹<?php echo number_format($levels[$nextLevel][1]); ?></p>
                                <button class="btn btn-success" onclick="claimReward()">Claim Reward</button>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
    function claimReward() {
        fetch('process_rewards.php')
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success' && data.paid_levels.length > 0) {
                    alert('✅ ' + data.message);
                    location.reload();
                } else {
                    alert('❌ ' + data.message);
                }
            })
            .catch(error => {
                alert('Error: ' + error);
            });
    }
    </script>
</body>
</html>