<style>
.hover-info {
    display: none;
    background: #fff;
    padding: 6px;
    border: 1px solid #ccc;
    position: absolute;
    z-index: 999;
    font-size: 12px;
    box-shadow: 0 0 5px rgba(0,0,0,0.2);
}
.member-view-box:hover .hover-info {
    display: block;
}
    
/* Status Icons */
.status-icon {
    display: inline-block;
    width: 24px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    border-radius: 50%;
    margin-left: 5px;
    font-size: 14px;
    font-weight: bold;
}

.status-active {
    background-color: #4caf50;
    color: white;
}

.status-inactive {
    background-color: #f44336;
    color: white;
}

.status-banned {
    background-color: #9c27b0;
    color: white;
    font-size: 16px;
}

.status-unknown {
    background-color: #ff9800;
    color: white;
}

/* Add status filter in search form */
.status-filter {
    margin: 10px 0;
    padding: 10px;
    background: #f5f5f5;
    border-radius: 5px;
}

.status-filter label {
    margin-right: 15px;
    cursor: pointer;
}

.status-filter input[type="radio"] {
    margin-right: 5px;
}

/* Cool Hover Card Styles */
.hover-card-container {
    position: relative;
    display: inline-block;
}

.member-view-box {
    cursor: pointer;
    transition: transform 0.2s, box-shadow 0.2s;
}

.member-view-box:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(0,0,0,0.15);
}

/* The hover card that appears */
.user-hover-card {
    position: fixed;
    background: white;
    border-radius: 16px;
    padding: 20px;
    width: 320px;
    box-shadow: 0 20px 40px rgba(0,0,0,0.2), 0 8px 16px rgba(0,0,0,0.1);
    z-index: 10000;
    pointer-events: none;
    opacity: 0;
    transition: opacity 0.3s ease, transform 0.3s ease;
    transform: translateY(10px) scale(0.95);
    border: 1px solid rgba(255,255,255,0.1);
    backdrop-filter: blur(10px);
    background: rgba(255,255,255,0.98);
}

.user-hover-card.show {
    opacity: 1;
    transform: translateY(0) scale(1);
    pointer-events: auto;
}

.hover-card-header {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 2px solid #f0f0f0;
}

.hover-card-avatar {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 28px;
    font-weight: bold;
    box-shadow: 0 4px 8px rgba(102, 126, 234, 0.4);
}

.hover-card-title {
    flex: 1;
}

.hover-card-title h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.hover-card-title p {
    margin: 5px 0 0;
    font-size: 13px;
    color: #666;
}

.hover-card-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    margin-top: 5px;
}

.hover-card-info {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    margin-bottom: 15px;
}

.hover-card-info-item {
    background: #f8f9fa;
    padding: 10px;
    border-radius: 12px;
    text-align: center;
}

.hover-card-info-label {
    font-size: 11px;
    color: #888;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 5px;
}

.hover-card-info-value {
    font-size: 16px;
    font-weight: 700;
    color: #333;
}

.hover-card-info-value small {
    font-size: 11px;
    color: #999;
    font-weight: normal;
}

.hover-card-stats {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    padding: 15px;
    color: white;
    margin-top: 10px;
}

.hover-card-stats-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
}

.hover-card-stats-label {
    font-size: 12px;
    opacity: 0.9;
}

.hover-card-stats-value {
    font-weight: 700;
    font-size: 14px;
}

.hover-card-footer {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
    font-size: 11px;
    color: #999;
    border-top: 1px solid #eee;
    padding-top: 10px;
}

.hover-card-rank-icon {
    height: 20px;
    vertical-align: middle;
    margin-right: 5px;
}

/* Progress bar for level completion */
.level-progress {
    height: 6px;
    background: #e0e0e0;
    border-radius: 3px;
    margin: 10px 0;
    overflow: hidden;
}

.level-progress-bar {
    height: 100%;
    background: linear-gradient(90deg, #4caf50, #8bc34a);
    border-radius: 3px;
    transition: width 0.3s ease;
}
</style>

<?php
require_once 'config/rewards_config.php';
$rewardsConfig = include 'config/rewards_config.php';
require 'element/connection.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

require_once "tree_rewards.php";

// Make sure $userId is defined (from session)
$userId = $_SESSION['user_id'] ?? 0;

// Wallet Balance
$walletResult = $conn->query("SELECT wallet FROM users WHERE user_id = $userId");
$walletRow = $walletResult->fetch_assoc();
$totalWallet = $walletRow['wallet'] ?? 0;

$availableBalance = $totalWallet;
?>
<!-- Replace the button with this clearer version -->
<button id="refreshPayoutBtn" class="btn btn-primary" style="margin: 10px 0;">
    <i class="fas fa-sync-alt"></i> Check My Level Rewards
</button>

<!-- SweetAlert -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
document.getElementById("refreshPayoutBtn").addEventListener("click", function () {
    fetch("php/pay_rewards.php")
        .then(res => res.json())
        .then(data => {
            if (data.status === "success") {
                if (data.paid_levels.length > 0) {
                    Swal.fire({
                        toast: true,
                        icon: 'success',
                        title: '✅ Rewards Paid!',
                        text: 'Levels: ' + data.paid_levels.join(', '),
                        position: 'top-end',
                        timer: 4000,
                        showConfirmButton: false
                    });
                } else {
                    Swal.fire({
                        toast: true,
                        icon: 'info',
                        title: 'No rewards to pay yet.',
                        position: 'top-end',
                        timer: 3000,
                        showConfirmButton: false
                    });
                }
            }
        });
});
    
</script>
<div class="card-body">
    <h5 class="card-title">Wallet Balance: ₹<?= $availableBalance; ?></h5>
    <?php if (!empty($rewardsGiven)): ?>
        <div class="alert alert-success">
            <?php foreach ($rewardsGiven as $reward): ?>
                Level <?= $reward['level'] ?> completed! ₹<?= $reward['amount'] ?> credited.<br>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>


<br>

<!-- Add Member Form -->

<script>
// Function to save current form data to localStorage
function saveFormData() {
    const formData = {
        sponsor_id: document.getElementById('sponsor_id').value,
        name: document.getElementById('name').value,
        email: document.getElementById('email').value,
        phone: document.getElementById('phone').value,
        lastUpdated: new Date().toISOString()
    };
    
    localStorage.setItem('currentMemberForm', JSON.stringify(formData));
    console.log('Form data auto-saved:', formData);
}

// Function to load saved data from localStorage
function loadFormData() {
    const savedData = localStorage.getItem('currentMemberForm');
    
    if (savedData) {
        try {
            const formData = JSON.parse(savedData);
            
            // Populate form fields with saved data
            document.getElementById('sponsor_id').value = formData.sponsor_id || '';
            document.getElementById('name').value = formData.name || '';
            document.getElementById('email').value = formData.email || '';
            document.getElementById('phone').value = formData.phone || '';
            
            console.log('Form data loaded from localStorage:', formData);
            
            // Optional: Show when it was last updated
            if (formData.lastUpdated) {
                const lastUpdate = new Date(formData.lastUpdated).toLocaleString();
                console.log('Last updated:', lastUpdate);
            }
        } catch (e) {
            console.error('Error loading saved data:', e);
        }
    } else {
        console.log('No saved form data found');
    }
}

// Function to clear the saved form data after successful submission
function clearSavedFormData() {
    localStorage.removeItem('currentMemberForm');
    console.log('Form data cleared from localStorage');
}

// Load saved data when the page loads
window.addEventListener('load', function() {
    loadFormData();
});

// Optional: Auto-save every 30 seconds as backup
setInterval(saveFormData, 30000);

// Optional: Save before page unload
window.addEventListener('beforeunload', function() {
    saveFormData();
});

// Optional: Handle form submission to clear data
document.querySelector('.add-member-form').addEventListener('submit', function(e) {
    // Uncomment the line below if you want to clear the form data after submission
    // setTimeout(clearSavedFormData, 1000);
});
</script>

<!-- Floating Hover Card Container -->
<div id="hoverCard" class="user-hover-card">
    <div class="hover-card-header">
        <div class="hover-card-avatar" id="hoverAvatar">👤</div>
        <div class="hover-card-title">
            <h3 id="hoverName">User Name</h3>
            <p id="hoverUserId">ID: 12345678</p>
            <span class="hover-card-badge" id="hoverStatus">Active</span>
        </div>
    </div>
    
    <div class="hover-card-info">
        <div class="hover-card-info-item">
            <div class="hover-card-info-label">Current Level</div>
            <div class="hover-card-info-value" id="hoverLevel">0/7</div>
        </div>
        <div class="hover-card-info-item">
            <div class="hover-card-info-label">Rank</div>
            <div class="hover-card-info-value" id="hoverRank">Starter</div>
        </div>
        <div class="hover-card-info-item">
            <div class="hover-card-info-label">Direct</div>
            <div class="hover-card-info-value" id="hoverDirect">0</div>
        </div>
        <div class="hover-card-info-item">
            <div class="hover-card-info-label">Wallet</div>
            <div class="hover-card-info-value" id="hoverWallet">₹0</div>
        </div>
    </div>
    
    <div class="level-progress">
        <div class="level-progress-bar" id="hoverProgress" style="width: 0%"></div>
    </div>
    
    <div class="hover-card-stats">
        <div class="hover-card-stats-row">
            <span class="hover-card-stats-label">Team Size</span>
            <span class="hover-card-stats-value" id="hoverTeamSize">0</span>
        </div>
        <div class="hover-card-stats-row">
            <span class="hover-card-stats-label">Completed Levels</span>
            <span class="hover-card-stats-value" id="hoverCompletedLevels">0</span>
        </div>
        <div class="hover-card-stats-row">
            <span class="hover-card-stats-label">Total Earnings</span>
            <span class="hover-card-stats-value" id="hoverEarnings">₹0</span>
        </div>
    </div>
    
    <div class="hover-card-footer">
        <span id="hoverJoined">Joined: N/A</span>
        <span id="hoverLastActive">Last Active: N/A</span>
    </div>
</div>

<!-- JavaScript for auto-filling sponsor ID and hover card -->
<script>
// Hover card functionality
const hoverCard = document.getElementById('hoverCard');
let hoverTimeout;
let isHovering = false;

function showHoverCard(event, userData) {
    clearTimeout(hoverTimeout);
    
    // Populate hover card data
    document.getElementById('hoverName').textContent = userData.name;
    document.getElementById('hoverUserId').textContent = 'ID: ' + userData.user_id;
    document.getElementById('hoverLevel').textContent = userData.current_level + '/' + userData.max_levels;
    document.getElementById('hoverRank').textContent = userData.rank;
    document.getElementById('hoverDirect').textContent = userData.direct_count;
    document.getElementById('hoverWallet').textContent = '₹' + userData.wallet;
    document.getElementById('hoverTeamSize').textContent = userData.team_size;
    document.getElementById('hoverCompletedLevels').textContent = userData.completed_levels;
    document.getElementById('hoverEarnings').textContent = '₹' + userData.total_earnings;
    document.getElementById('hoverJoined').textContent = 'Joined: ' + userData.joining_date;
    document.getElementById('hoverLastActive').textContent = 'Last Active: ' + (userData.last_active || 'N/A');
    
    // Set status badge
    const statusBadge = document.getElementById('hoverStatus');
    if (userData.status == 1) {
        statusBadge.textContent = 'Active';
        statusBadge.style.background = '#4caf50';
        statusBadge.style.color = 'white';
    } else if (userData.status == 0) {
        statusBadge.textContent = 'Inactive';
        statusBadge.style.background = '#f44336';
        statusBadge.style.color = 'white';
    } else if (userData.status == 2) {
        statusBadge.textContent = 'Banned';
        statusBadge.style.background = '#9c27b0';
        statusBadge.style.color = 'white';
    }
    
    // Set avatar (first letter of name)
    document.getElementById('hoverAvatar').textContent = userData.name.charAt(0).toUpperCase();
    
    // Set progress bar (current level progress)
    const progressPercent = (userData.current_level / userData.max_levels) * 100;
    document.getElementById('hoverProgress').style.width = progressPercent + '%';
    
    // Position the card near cursor
    const mouseX = event.clientX;
    const mouseY = event.clientY;
    
    // Get viewport dimensions
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;
    
    // Card dimensions
    const cardWidth = 320;
    const cardHeight = 420;
    
    // Calculate position (prevent going off-screen)
    let left = mouseX + 20;
    let top = mouseY - cardHeight - 10;
    
    // Adjust if going off right edge
    if (left + cardWidth > viewportWidth) {
        left = mouseX - cardWidth - 20;
    }
    
    // Adjust if going off top edge
    if (top < 10) {
        top = mouseY + 20;
    }
    
    // Adjust if going off bottom edge
    if (top + cardHeight > viewportHeight - 20) {
        top = viewportHeight - cardHeight - 20;
    }
    
    hoverCard.style.left = left + 'px';
    hoverCard.style.top = top + 'px';
    
    // Show the card
    hoverCard.classList.add('show');
    isHovering = true;
}

function hideHoverCard() {
    hoverTimeout = setTimeout(() => {
        if (!isHovering) {
            hoverCard.classList.remove('show');
        }
    }, 200);
}

// Keep card visible when hovering over it
hoverCard.addEventListener('mouseenter', () => {
    isHovering = true;
    clearTimeout(hoverTimeout);
});

hoverCard.addEventListener('mouseleave', () => {
    isHovering = false;
    hideHoverCard();
});

function setSponsorId(userId) {
    document.getElementById('sponsor_id').value = userId;
}

// Click handler on member boxes
$(document).on('click', '.member-view-box', function() {
    // Extract user ID from the element
    var userId = $(this).find('.name span:contains("User ID:")').text().replace('User ID:', '').trim();
    if (userId) {
        setSponsorId(userId);
        // Scroll to form
        $('html, body').animate({
            scrollTop: $('.add-member-form').offset().top
        }, 500);
    }
});

// Hover handler to fetch and show user data
$(document).on('mouseenter', '.member-view-box', function(e) {
    var userId = $(this).find('.name span:contains("User ID:")').text().replace('User ID:', '').trim();
    
    // Fetch user data via AJAX
    $.ajax({
        url: 'php/get_user_details.php',
        method: 'GET',
        data: { user_id: userId },
        dataType: 'json',
        success: function(userData) {
            showHoverCard(e, userData);
        },
        error: function(xhr, status, error) {
            console.error('Error fetching user details:', error);
        }
    });
});

$(document).on('mouseleave', '.member-view-box', function() {
    hideHoverCard();
});
</script>

<?php
function getUserLevelRewards($conn, $user_id) {
    $rewards = [];
    $stmt = $conn->prepare("SELECT level, paid FROM level_rewards WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rewards[(int)$row['level']] = $row['paid'];
    }
    $stmt->close();
    return $rewards;
}

function creditWallet($conn, $user_id, $completedLevels) {
    $levelAmounts = [
        1 => 1000,
        2 => 1600,
        3 => 6500,
        4 => 28000,
        5 => 130000,
        6 => 540000,
        7 => 2250000
    ];

    for ($level = 1; $level <= $completedLevels; $level++) {
        $amount = $levelAmounts[$level] ?? 0;

        $check = $conn->prepare("SELECT 1 FROM wallet WHERE user_id = ? AND level = ?");
        $check->bind_param("ii", $user_id, $level);
        $check->execute();
        $check->store_result();

        if ($check->num_rows === 0) {
            $insert = $conn->prepare("INSERT INTO wallet (user_id, level, amount) VALUES (?, ?, ?)");
            $insert->bind_param("iii", $user_id, $level, $amount);
            $insert->execute();
            $insert->close();
        }

        $check->close();
    }
}

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()) {
                // Check if all 4 child positions are filled
                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;
                }

                // Add children to next level list
                $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;
}

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 getStatusIcon($status) {
    switch($status) {
        case 0:
            return '<span class="status-icon status-active" title="Active">✓</span>';
        case 1:
            return '<span class="status-icon status-inactive" title="Inactive">✗</span>';
        case 2:
            return '<span class="status-icon status-banned" title="Banned">🚫</span>';
        default:
            return '<span class="status-icon status-unknown" title="Unknown">?</span>';
    }
}

function getStatusText($status) {
    switch($status) {
        case 1:
            return 'Active';
        case 0:
            return 'Inactive';
        case 2:
            return 'Banned';
        default:
            return 'Unknown';
    }
}

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 buildTree($conn, $userId, $depth = 0, $max_depth = 11, &$visited = []) {
    global $rewardsConfig;
    
    if ($depth > $max_depth || in_array($userId, $visited)) return '';
    $visited[] = $userId;

    $user = $conn->query("SELECT * FROM users WHERE user_id = $userId")->fetch_assoc();
    if (!$user) return '';

    $name = htmlspecialchars($user['name']);
    $levelCount = calculateUserLevels($conn, $userId);
    $status = (int)($user['status'] ?? 1);
    $statusIcon = getStatusIcon($status);
    
    $downlineCount = 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) $downlineCount++;
    }

    // Determine color class based on total direct downline count
    // Determine color class based on total direct downline count
if ($downlineCount <= 1) {
    $colorClass = 'status-red';      // 0 or 1 users - Red
} elseif ($downlineCount == 2) {
    $colorClass = 'status-red';   // 2 users - Orange
} elseif ($downlineCount == 3) {
    $colorClass = 'status-yellow';   // 3 users - Yellow
} else {
    $colorClass = 'status-green';    // 4 users - Green (Complete)
}

    // Initialize HTML string
    $html = '<li>';
    $html .= '<div class="member-view-box" data-user-id="' . $userId . '" onclick="copyUserIdToClipboard(' . $userId . ')">
        <div class="member-header ' . $colorClass . '">
            <span>' . htmlspecialchars($user['name']) . ' ' . $statusIcon . '</span>
        </div>
        <div class="member-image">
            <img src="php/bmw.jpg" alt="Member">
        </div>
        <div class="member-footer">
            <div class="name">
                <span>Rank: ' . htmlspecialchars($user['rank'] ?? 'Starter') . '</span>
            </div>
            <div class="downline">
                <span>Level: ' . getCurrentLevel($conn, $userId) . '/7</span>
            </div>
            <div class="name">
                <span>User ID: ' . $userId . '</span>
            </div>
            <div class="wallet">
                <span>Wallet: ₹' . number_format($user['wallet'] ?? 0) . '</span>
            </div>
        </div>
    </div>';

    // Child UL (initially hidden)
    $html .= '<ul style="display: none;">';
    $positionLabels = [
        'left_1_id' => 'Add Left 1',
        'left_2_id' => 'Add Left 2',
        'right_1_id' => 'Add Right 1',
        'right_2_id' => 'Add Right 2',
    ];

    foreach ($positionLabels as $pos => $label) {
        $childId = (int)($user[$pos] ?? 0);

        if ($childId > 0 && !in_array($childId, $visited)) {
            $html .= buildTree($conn, $childId, $depth + 1, $max_depth, $visited);
        } else {
            $html .= '<li class="no-children"><a href="javascript:void(0);" onclick="openAddUserForm(' . $userId . ', \'' . $pos . '\')">';
            $html .= '<div style="height: 100px; width: 100px; border-radius: 100px; padding: 10px; 
                      box-shadow: 0px 0 20px rgba(0, 0, 0, 0.1); display: flex; justify-content: center; 
                      align-items: center; border: 1px solid #ccc; background: white; font-family: poppins;">
                      <div class="name"><span>' . $label . '</span></div>
                      </div></a></li>';
        }
    }

    $html .= '</ul>';
    $html .= '</li>';

    return $html;
}

function isDescendant($conn, $root_id, $search_id) {
    if ($root_id == $search_id) return true;
    $result = $conn->query("SELECT user_id FROM users WHERE placement_id = $root_id");
    while ($row = $result->fetch_assoc()) {
        if ($row['user_id'] == $search_id || isDescendant($conn, $row['user_id'], $search_id)) {
            return true;
        }
    }
    return false;
}

// ------------------- RENDERING SECTION -------------------

$current_root_id = $userId;
$requested_id = isset($_GET['parent_id']) ? (int)$_GET['parent_id'] : $current_root_id;

// Validate the requested user
if (!isDescendant($conn, $current_root_id, $requested_id)) {
    echo "<p style='color:red;'>❌ User Not Available. Showing your tree (User ID: $current_root_id)</p>";
    $parent_id = $current_root_id;
} else {
    $parent_id = $requested_id;
   
}

// Confirm user exists
$check = $conn->query("SELECT * FROM users WHERE user_id = $parent_id");
if ($check->num_rows == 0) {
    echo "<p style='color:red;'>❌ User ID $parent_id not found.</p>";
    exit;
}

$root = $check->fetch_assoc();

// Search form with status filter
?>


<?php
// Initialize
$visited = [];
$completedLevels = calculateUserLevels($conn, $parent_id);

// Show completed levels
echo '<div class="completed-levels" style="padding:10px;font-weight:bold;">✅ Levels Completed: ' . $completedLevels . '</div>';

// Tree container
echo '<div class="genealogy-body genealogy-scroll"><div class="genealogy-tree">';
echo '<ul>' . buildTree($conn, $parent_id, 1, 11, $visited) . '</ul>';
echo '</div></div>';
?>

<script>
function copyUserIdToClipboard(userId) {
    navigator.clipboard.writeText(userId).then(function () {
        Swal.fire({
            toast: true,
            position: 'top-end',
            icon: 'success',
            title: 'User ID ' + userId + ' copied to clipboard!',
            showConfirmButton: false,
            timer: 2000
        });
    }).catch(function (err) {
        console.error('Failed to copy user ID: ', err);
    });
}

function openAddUserForm(userId, position) {
    document.getElementById('sponsor_id').value = userId;
    $('html, body').animate({
        scrollTop: $('.add-member-form').offset().top
    }, 500);
}
</script>