<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

// Include config
require_once 'config.php';

// Ensure the user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$total_referrals = 0;
$referrals = [];

// Fetch Referral Data (Levels 1, 2, and 3)
try {
    // 1. Get the logged-in user's referral code
    $codeStmt = $pdo->prepare("SELECT refercode FROM users WHERE id = ?");
    $codeStmt->execute([$user_id]);
    $currentUser = $codeStmt->fetch();

    if ($currentUser && !empty($currentUser['refercode'])) {
        $my_refercode = $currentUser['refercode'];

        // --- FETCH LEVEL 1 ---
        $stmt1 = $pdo->prepare("SELECT id, number, created_at, isbanned, total_deposits, refercode FROM users WHERE referedby = ? ORDER BY created_at DESC");
        $stmt1->execute([$my_refercode]);
        $level1_users = $stmt1->fetchAll(PDO::FETCH_ASSOC);

        $l1_codes = [];
        // Removed buggy PHP references (&$u) and explicitly set levels
        foreach ($level1_users as $key => $u) {
            $level1_users[$key]['level'] = 1; 
            if (!empty($u['refercode'])) {
                $l1_codes[] = $u['refercode'];
            }
        }

        // --- FETCH LEVEL 2 ---
        $level2_users = [];
        $l2_codes = [];
        if (!empty($l1_codes)) {
            $inQuery1 = implode(',', array_fill(0, count($l1_codes), '?'));
            $stmt2 = $pdo->prepare("SELECT id, number, created_at, isbanned, total_deposits, refercode FROM users WHERE referedby IN ($inQuery1) ORDER BY created_at DESC");
            $stmt2->execute($l1_codes);
            $level2_users = $stmt2->fetchAll(PDO::FETCH_ASSOC);

            foreach ($level2_users as $key => $u) {
                $level2_users[$key]['level'] = 2; 
                if (!empty($u['refercode'])) {
                    $l2_codes[] = $u['refercode']; 
                }
            }
        }

        // --- FETCH LEVEL 3 ---
        $level3_users = [];
        if (!empty($l2_codes)) {
            $inQuery2 = implode(',', array_fill(0, count($l2_codes), '?'));
            $stmt3 = $pdo->prepare("SELECT id, number, created_at, isbanned, total_deposits, refercode FROM users WHERE referedby IN ($inQuery2) ORDER BY created_at DESC");
            $stmt3->execute($l2_codes);
            $level3_users = $stmt3->fetchAll(PDO::FETCH_ASSOC);

            foreach ($level3_users as $key => $u) {
                $level3_users[$key]['level'] = 3; 
            }
        }

        // --- COMBINE ALL LEVELS ---
        $referrals = array_merge($level1_users, $level2_users, $level3_users);
        
        // Sort everyone by date joined (newest first)
        usort($referrals, function($a, $b) {
            return strtotime($b['created_at']) - strtotime($a['created_at']);
        });

        // Total count of the whole team across all 3 levels
        $total_referrals = count($referrals);
    }
} catch (PDOException $e) {
    $error = "Database Error: " . $e->getMessage();
} catch (Exception $e) {
    $error = "General Error: " . $e->getMessage();
}

// Include external header to load scripts (WILL NOW SHOW NORMALLY)
require_once 'external/header.php';
?>

<style>
    /* Give bottom spacing for your native footer */
    #promo-page-wrapper {
        padding-bottom: 80px; 
        font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
    }

    /* --- CONTENT AREA STYLING --- */
    .promo-container {
        padding: 20px;
        max-width: 600px;
        margin: 0 auto;
    }

    /* --- HERO CARD --- */
    .stats-card {
        background-color: #1e1511; /* Accurately matches your screenshot */
        border: 1px solid #2a1e17; 
        border-radius: 12px;
        padding: 30px 20px;
        text-align: center;
        margin-bottom: 25px;
    }

    .stats-card h2 {
        color: #ffffff; 
        margin: 0;
        font-size: 42px;
        font-weight: 700;
    }

    .stats-card p {
        color: #9b8e85; 
        margin: 8px 0 0;
        font-size: 13px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

    /* --- LEVEL PILLS --- */
    .level-tabs {
        display: flex;
        gap: 12px;
        margin-bottom: 25px;
    }

    .level-btn {
        flex: 1;
        background-color: transparent;
        border: 1px solid #35251c;
        color: #ffffff;
        padding: 12px 0;
        border-radius: 25px; 
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .level-btn.active {
        background-color: #d29938; /* Gold app accent */
        border-color: #d29938;
        color: #ffffff; 
        box-shadow: 0 0 15px rgba(210, 153, 56, 0.25); /* Subtle gold glow */
    }

    .section-title {
        font-size: 14px;
        margin-bottom: 15px;
        color: #d29938; 
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

    /* --- EXPANDABLE LIST STYLING --- */
    .referral-list {
        display: flex;
        flex-direction: column;
        gap: 12px;
    }

    .referral-card {
        background-color: #1e1511; 
        border-radius: 10px;
        border: 1px solid #2a1e17; 
        overflow: hidden; 
    }

    .ref-header {
        padding: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        cursor: pointer;
        user-select: none;
    }

    .ref-info h4 {
        margin: 0 0 6px 0;
        font-size: 15px;
        color: #ffffff;
    }

    .ref-info p {
        margin: 0;
        font-size: 12px;
        color: #9b8e85; 
    }

    .ref-right-side {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .ref-status {
        font-size: 12px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .status-active { color: #5cba60; }
    .status-banned { color: #e5534b; }

    .chevron-icon {
        color: #9b8e85;
        transition: transform 0.3s ease;
    }

    .referral-card.open .chevron-icon {
        transform: rotate(180deg);
        color: #d29938;
    }

    .ref-details {
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.3s ease-out, padding 0.3s ease;
        background-color: rgba(0, 0, 0, 0.2); 
        padding: 0 16px;
    }

    .referral-card.open .ref-details {
        max-height: 150px; 
        padding: 15px 16px;
        border-top: 1px solid #2a1e17;
    }

    .detail-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        font-size: 13px;
    }

    .detail-row:last-child {
        margin-bottom: 0;
    }

    .detail-label {
        color: #9b8e85;
    }

    .detail-value {
        color: #ffffff;
        font-weight: 600;
    }

    .detail-value.highlight {
        color: #d29938; 
    }

    .no-data {
        text-align: center;
        padding: 40px 20px;
        color: #9b8e85;
        background-color: #1e1511;
        border-radius: 10px;
        border: 1px dashed #2a1e17;
    }
</style>

<div id="promo-page-wrapper">
    <div class="promo-container">
        
        <?php if(isset($error)): ?>
            <div style="color: #ff4444; background: #2a1111; padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid #552222;">
                <strong>Error:</strong> <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <div class="stats-card">
            <h2><?php echo $total_referrals; ?></h2>
            <p>Total Team Members</p>
        </div>

        <div class="level-tabs">
            <button class="level-btn active" onclick="filterLevel(1, this)">Level 1</button>
            <button class="level-btn" onclick="filterLevel(2, this)">Level 2</button>
            <button class="level-btn" onclick="filterLevel(3, this)">Level 3</button>
        </div>

        <div class="section-title">Team History</div>
        
        <div class="referral-list" id="referral-list-container">
            <?php if (!empty($referrals)): ?>
                <?php foreach ($referrals as $ref): ?>
                    <?php 
                        $is_banned = isset($ref['isbanned']) && $ref['isbanned'] == 1; 
                        $user_level = $ref['level']; 
                        $total_dep = isset($ref['total_deposits']) ? number_format((float)$ref['total_deposits'], 2) : "0.00";
                    ?>
                    <div class="referral-card user-item" data-level="<?php echo $user_level; ?>">
                        <div class="ref-header" onclick="toggleDropdown(this)">
                            <div class="ref-info">
                                <h4>ID: <?php echo htmlspecialchars($ref['id'] ?? 'N/A'); ?> | <?php echo isset($ref['number']) ? htmlspecialchars(substr($ref['number'], 0, 4) . '***' . substr($ref['number'], -4)) : 'N/A'; ?></h4>
                                <p>Joined: <?php echo isset($ref['created_at']) ? date('d M Y, h:i A', strtotime($ref['created_at'])) : 'Unknown'; ?></p>
                            </div>
                            <div class="ref-right-side">
                                <span class="ref-status <?php echo $is_banned ? 'status-banned' : 'status-active'; ?>">
                                    <?php echo $is_banned ? 'Banned' : 'Active'; ?>
                                </span>
                                <svg class="chevron-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <polyline points="6 9 12 15 18 9"></polyline>
                                </svg>
                            </div>
                        </div>
                        
                        <div class="ref-details">
                            <div class="detail-row">
                                <span class="detail-label">Total Deposits</span>
                                <span class="detail-value highlight">Rs <?php echo $total_dep; ?></span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Status</span>
                                <span class="detail-value"><?php echo $is_banned ? 'Account Restricted' : 'Account Normal'; ?></span>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="no-data" id="empty-state">
                    No team data found yet.
                </div>
            <?php endif; ?>
        </div>

    </div>
</div>
<script>
    // 1. Accordion Dropdown Logic
    function toggleDropdown(headerElement) {
        const card = headerElement.closest('.referral-card');
        const isOpen = card.classList.contains('open');
        
        document.querySelectorAll('.referral-card').forEach(c => {
            c.classList.remove('open');
        });

        if (!isOpen) {
            card.classList.add('open');
        }
    }

    // 2. Tab Filtering Logic
    function filterLevel(level, btnElement) {
        document.querySelectorAll('.level-btn').forEach(btn => btn.classList.remove('active'));
        btnElement.classList.add('active');

        let visibleCount = 0;
        document.querySelectorAll('.user-item').forEach(item => {
            if (item.getAttribute('data-level') == level) {
                item.style.display = 'block';
                visibleCount++;
            } else {
                item.style.display = 'none';
            }
        });
        
        // Handle Empty State if a level has no users
        let noDataMsg = document.getElementById('no-level-data');
        if (visibleCount === 0) {
            if (!noDataMsg) {
                const list = document.getElementById('referral-list-container');
                list.insertAdjacentHTML('beforeend', '<div id="no-level-data" class="no-data">No users found in Level ' + level + '.</div>');
            } else {
                noDataMsg.innerHTML = 'No users found in Level ' + level + '.';
                noDataMsg.style.display = 'block';
            }
        } else if (noDataMsg) {
            noDataMsg.style.display = 'none';
        }
        
        // Hide initial empty state if data exists
        let initialEmpty = document.getElementById('empty-state');
        if(initialEmpty) initialEmpty.style.display = 'none';
    }

    // Run the filter on page load so Level 1 is selected by default
    document.addEventListener("DOMContentLoaded", function() {
        const firstBtn = document.querySelector('.level-btn');
        if(firstBtn) filterLevel(1, firstBtn);
    });
</script>

<?php 
// Include Footer
require_once 'external/footer.php'; 
?>