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

// Get user ID from session
$my_id = $_SESSION['user_id'];

// Fetch user details
$user_query = mysqli_query($conn, "SELECT * FROM users WHERE user_id = '$my_id'");
$user_data = mysqli_fetch_assoc($user_query);

// Handle export requests
if (isset($_GET['export'])) {
    $export_type = $_GET['export'];
    $package_filter = $_GET['package_filter'] ?? 'all';
    $date_from = $_GET['date_from'] ?? '';
    $date_to = $_GET['date_to'] ?? '';
    
    exportDownlineData($conn, $my_id, $export_type, $package_filter, $date_from, $date_to);
}

// Export function
function exportDownlineData($conn, $userId, $type, $packageFilter, $dateFrom, $dateTo) {
    // Build query based on filters
    $query = "SELECT u.*, 
              (SELECT COUNT(*) FROM users WHERE sponsor_id = u.user_id) as direct_count,
              (SELECT SUM(wallet) FROM users WHERE sponsor_id = u.user_id) as team_volume
              FROM users u 
              WHERE u.placement_id = '$userId' OR u.sponsor_id = '$userId'";
    
    if ($packageFilter != 'all') {
    // Make sure to use the amount values in the query
    $query .= " AND u.package_id = '$packageFilter'";
}
    
    if (!empty($dateFrom) && !empty($dateTo)) {
        $query .= " AND DATE(u.joining_date) BETWEEN '$dateFrom' AND '$dateTo'";
    }
    
    $result = mysqli_query($conn, $query);
    
    if ($type == 'excel') {
        // Excel export
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="downline_report_' . date('Y-m-d') . '.xls"');
        
        echo "ID\tName\tUser ID\tMobile\tPackage\tJoining Date\tDirect Count\tTeam Volume\tStatus\n";
        
        while ($row = mysqli_fetch_assoc($result)) {
    // Update this part to check by amount
    $package = '';
    if ($row['package_id'] == 2500) {
        $package = 'Package 1 (₹2,500)';
    } elseif ($row['package_id'] == 3500) {
        $package = 'Package 2 (₹3,500)';
    } else {
        $package = 'N/A';
    }
    $status = $row['status'] == 0 ? 'Active' : 'Inactive';
    
    echo $row['id'] . "\t" .
         $row['name'] . "\t" .
         $row['user_id'] . "\t" .
         $row['mobile'] . "\t" .
         $package . "\t" .
         $row['joining_date'] . "\t" .
         $row['direct_count'] . "\t" .
         $row['team_volume'] . "\t" .
         $status . "\n";
}
        exit;
    } elseif ($type == 'pdf') {
        // For PDF, we'll use a library like TCPDF or just show a message
        // For now, redirect back with message
        header("Location: level.php?msg=pdf_export_coming_soon");
        exit;
    }
}

// Search functionality
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$package_filter = isset($_GET['package']) ? $_GET['package'] : 'all';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Get all downline users with filtering
function getAllDownlineUsers($conn, $userId, &$visited = [], $search = '', $package = 'all', $dateFrom = '', $dateTo = '') {
    $all = [];
    $search_condition = '';
    if (!empty($search)) {
        $search_condition = " AND (name LIKE '%$search%' OR user_id LIKE '%$search%' OR mobile LIKE '%$search%')";
    }
    
    $package_condition = ($package != 'all') ? " AND package_id = '$package'" : '';
    
    $date_condition = '';
    if (!empty($dateFrom) && !empty($dateTo)) {
        $date_condition = " AND DATE(joining_date) BETWEEN '$dateFrom' AND '$dateTo'";
    }
    
    $query = "SELECT * FROM users WHERE placement_id = $userId $search_condition $package_condition $date_condition";
    $result = $conn->query($query);
    
    while ($row = $result->fetch_assoc()) {
        if (in_array($row['user_id'], $visited)) continue;
        $visited[] = $row['user_id'];
        $all[] = $row;
        $all = array_merge($all, getAllDownlineUsers($conn, $row['user_id'], $visited, $search, $package, $dateFrom, $dateTo));
    }
    return $all;
}

$visited = [];
$downlineUsers = getAllDownlineUsers($conn, $my_id, $visited, $search, $package_filter, $date_from, $date_to);

// Get direct downline IDs
$directIds = [];
$direct = $conn->query("SELECT left_1_id, left_2_id, right_1_id, right_2_id FROM users WHERE user_id = $my_id");
if ($direct && $direct->num_rows > 0) {
    $row = $direct->fetch_assoc();
    foreach ($row as $key => $val) {
        if ($val > 0) $directIds[] = $val;
    }
}

// Sort - direct first
usort($downlineUsers, function($a, $b) use ($directIds) {
    return (in_array($a['user_id'], $directIds) ? 0 : 1) <=> (in_array($b['user_id'], $directIds) ? 0 : 1);
});

// Get statistics
$total_downline = count($downlineUsers);
$total_direct = count($directIds);
$package1_count = 0;
$package2_count = 0;
$active_count = 0;
$total_team_volume = 0;

foreach ($downlineUsers as $user) {
    if ($user['package_id'] == 2500) $package1_count++;
    if ($user['package_id'] == 3500) $package2_count++;
    if ($user['status'] == 0) $active_count++;
    $total_team_volume += $user['wallet'];
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title><?php echo htmlspecialchars($user_data['name']); ?> || Downline Management</title>
    <meta content="" name="description">
    <meta content="" name="keywords">

    <!-- Favicons -->
    <link href="../img/logo/logo22222.png" rel="icon">

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">

    <!-- Vendor CSS Files -->
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
    <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
    <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.4.1/css/responsive.bootstrap5.min.css">

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet">

    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            --success-gradient: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            --warning-gradient: linear-gradient(135deg, #fad0c4 0%, #ffd1ff 100%);
            --danger-gradient: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);
            --primary-color: #667eea;
            --secondary-color: #764ba2;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 20px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            border: 1px solid rgba(102, 126, 234, 0.1);
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--primary-gradient);
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(102, 126, 234, 0.15);
        }

        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 15px;
            font-size: 24px;
            background: var(--primary-gradient);
            color: white;
        }

        .stat-value {
            font-size: 2rem;
            font-weight: 800;
            margin-bottom: 5px;
            color: #1e293b;
        }

        .stat-label {
            color: #64748b;
            font-size: 0.9rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        /* Filter Section */
        .filter-section {
            background: white;
            border-radius: 20px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            margin-bottom: 30px;
        }

        .filter-title {
            font-size: 1.1rem;
            font-weight: 700;
            margin-bottom: 20px;
            color: #1e293b;
        }

        .filter-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }

        .form-control-modern {
            width: 100%;
            padding: 12px 18px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            background: white;
        }

        .form-control-modern:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
            outline: none;
        }

        .btn-modern {
            padding: 12px 25px;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            cursor: pointer;
            background: var(--primary-gradient);
            color: white;
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }

        .btn-modern:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
        }

        .btn-outline-modern {
            background: transparent;
            border: 2px solid var(--primary-color);
            color: var(--primary-color);
            box-shadow: none;
        }

        .btn-outline-modern:hover {
            background: var(--primary-gradient);
            color: white;
            border-color: transparent;
        }

        /* Export Dropdown */
        .export-dropdown {
            position: relative;
            display: inline-block;
        }

        .export-menu {
            position: absolute;
            top: 100%;
            right: 0;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            min-width: 200px;
            display: none;
            z-index: 1000;
            padding: 10px;
        }

        .export-menu.show {
            display: block;
        }

        .export-item {
            padding: 12px 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .export-item:hover {
            background: #f8fafc;
        }

        /* Table Styles */
        .table-container {
            background: white;
            border-radius: 24px;
            padding: 25px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.05);
            overflow-x: auto;
        }

        .user-avatar {
            width: 45px;
            height: 45px;
            border-radius: 12px;
            object-fit: cover;
        }

        .package-badge {
            padding: 5px 12px;
            border-radius: 30px;
            font-size: 0.8rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .package-1 {
            background: #dbeafe;
            color: #1e40af;
        }

        .package-2 {
            background: #dcfce7;
            color: #166534;
        }

        .status-badge {
            padding: 5px 12px;
            border-radius: 30px;
            font-size: 0.8rem;
            font-weight: 600;
        }

        .status-active {
            background: #dcfce7;
            color: #166534;
        }

        .status-inactive {
            background: #fee2e2;
            color: #991b1b;
        }

        .binary-tree-wrapper {
            position: relative;
            width: 120px;
            height: 70px;
            margin: auto;
        }

        .parent-circle {
            width: 20px;
            height: 20px;
            background: var(--primary-gradient);
            border-radius: 50%;
            margin: 0 auto 10px;
            position: relative;
            z-index: 3;
            box-shadow: 0 5px 10px rgba(102, 126, 234, 0.3);
        }

        .binary-lines {
            position: absolute;
            top: 20px;
            left: 0;
            width: 120px;
            height: 40px;
            z-index: 1;
        }

        .binary-lines path {
            stroke: #94a3b8;
            stroke-width: 1.5;
            stroke-dasharray: 4;
        }

        .child-circle-container {
            position: absolute;
            bottom: 5px;
            left: 10px;
            width: calc(100% - 20px);
            display: flex;
            justify-content: space-between;
            z-index: 2;
        }

        .child-circle {
            width: 16px;
            height: 16px;
            border-radius: 50%;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .child-circle.green {
            background: #10b981;
            box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
        }

        .child-circle.grey {
            background: #cbd5e1;
        }

        .child-circle:hover {
            transform: scale(1.2);
        }

        .action-btn {
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 0.85rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .action-btn:hover {
            transform: translateY(-2px);
        }

        .btn-view {
            background: #e2e8f0;
            color: #334155;
        }

        .btn-tree {
            background: var(--primary-gradient);
            color: white;
        }

        /* DataTables Customization */
        .dataTables_wrapper .dataTables_length select,
        .dataTables_wrapper .dataTables_filter input {
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            padding: 8px 15px;
        }

        .dataTables_wrapper .dataTables_paginate .paginate_button {
            border-radius: 8px;
            padding: 8px 15px;
            margin: 0 3px;
        }

        .dataTables_wrapper .dataTables_paginate .paginate_button.current {
            background: var(--primary-gradient) !important;
            border: none;
            color: white !important;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .filter-grid {
                grid-template-columns: 1fr;
            }
            
            .binary-tree-wrapper {
                width: 80px;
            }
            
            .child-circle-container {
                left: 5px;
                width: calc(100% - 10px);
            }
        }
    </style>
</head>

<body>

    <!-- Header -->
    <?php include 'element/header.php'; ?>
    
    <!-- Sidebar -->
    <?php include 'element/sidebar.php'; ?>

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>Downline Management</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Downline</li>
                </ol>
            </nav>
        </div>

        <!-- Stats Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-users"></i>
                </div>
                <div class="stat-value"><?php echo $total_downline; ?></div>
                <div class="stat-label">Total Downline</div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-user-plus"></i>
                </div>
                <div class="stat-value"><?php echo $total_direct; ?></div>
                <div class="stat-label">Direct Members</div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-box"></i>
                </div>
                <div class="stat-value"><?php echo $package1_count; ?></div>
                <div class="stat-label">Package 1 Users</div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-crown"></i>
                </div>
                <div class="stat-value"><?php echo $package2_count; ?></div>
                <div class="stat-label">Package 2 Users</div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="stat-value"><?php echo $active_count; ?></div>
                <div class="stat-label">Active Users</div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-chart-line"></i>
                </div>
                <div class="stat-value">₹<?php echo number_format($total_team_volume, 2); ?></div>
                <div class="stat-label">Team Volume</div>
            </div>
        </div>

        <!-- Filter Section -->
        <div class="filter-section">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h5 class="filter-title mb-0">
                    <i class="fas fa-filter me-2"></i>Filter & Search
                </h5>
                
                <div class="export-dropdown">
                    <button class="btn-modern" onclick="toggleExportMenu()">
                        <i class="fas fa-download me-2"></i>Export Data
                    </button>
                    <div class="export-menu" id="exportMenu">
                        <div class="export-item" onclick="exportData('excel')">
                            <i class="fas fa-file-excel" style="color: #217346;"></i>
                            <span>Export as Excel</span>
                        </div>
                        <div class="export-item" onclick="exportData('pdf')">
                            <i class="fas fa-file-pdf" style="color: #ff0000;"></i>
                            <span>Export as PDF</span>
                        </div>
                        <div class="export-item" onclick="exportData('csv')">
                            <i class="fas fa-file-csv" style="color: #4CAF50;"></i>
                            <span>Export as CSV</span>
                        </div>
                        <div class="export-item" onclick="printTable()">
                            <i class="fas fa-print" style="color: #64748b;"></i>
                            <span>Print</span>
                        </div>
                    </div>
                </div>
            </div>

            <form method="GET" action="" id="filterForm">
                <div class="filter-grid">
                    <div>
                        <label class="form-label fw-bold">Search</label>
                        <input type="text" class="form-control-modern" name="search" 
                               placeholder="Name, ID, Mobile..." value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div>
    <label class="form-label fw-bold">Package</label>
    <select class="form-control-modern" name="package">
        <option value="all" <?php echo $package_filter == 'all' ? 'selected' : ''; ?>>All Packages</option>
        <option value="2500" <?php echo $package_filter == '2500' ? 'selected' : ''; ?>>Package 1 (₹2,500)</option>
        <option value="3500" <?php echo $package_filter == '3500' ? 'selected' : ''; ?>>Package 2 (₹3,500)</option>
    </select>
</div>
                    
                    <div>
                        <label class="form-label fw-bold">From Date</label>
                        <input type="date" class="form-control-modern" name="date_from" 
                               value="<?php echo $date_from; ?>">
                    </div>
                    
                    <div>
                        <label class="form-label fw-bold">To Date</label>
                        <input type="date" class="form-control-modern" name="date_to" 
                               value="<?php echo $date_to; ?>">
                    </div>
                    
                    <div class="d-flex align-items-end">
                        <button type="submit" class="btn-modern me-2">
                            <i class="fas fa-search me-2"></i>Apply Filters
                        </button>
                        <a href="level.php" class="btn-outline-modern btn-modern">
                            <i class="fas fa-redo-alt"></i>
                        </a>
                    </div>
                </div>
            </form>
        </div>

        <!-- Downline Table -->
        <div class="table-container">
            <table class="table" id="downlineTable">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Member</th>
                        <th>Contact</th>
                        <th>Package</th>
                        <th>Joining Date</th>
                        <th>Binary Tree</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($downlineUsers) > 0): ?>
                        <?php $a = 1; ?>
                        <?php foreach ($downlineUsers as $user_detail): 
                            $highlight = in_array($user_detail['user_id'], $directIds) ? 'style="background-color: rgba(102, 126, 234, 0.05);"' : '';
                            
                            // Get user's downline slots
                            $slots = ['left_1_id' => 0, 'left_2_id' => 0, 'right_1_id' => 0, 'right_2_id' => 0];
                            $slotQ = $conn->query("SELECT left_1_id, left_2_id, right_1_id, right_2_id FROM users WHERE user_id = " . $user_detail['user_id']);
                            if ($slotQ && $slotQ->num_rows > 0) {
                                $slots = $slotQ->fetch_assoc();
                            }
                        ?>
                        <tr <?php echo $highlight; ?>>
                            <td><?php echo $a++; ?></td>
                            
                            <td>
                                <div class="d-flex align-items-center">
                                    <img src="profile-img/<?php echo $user_detail['image'] ?? 'default-avatar.png'; ?>" 
                                         class="user-avatar me-3" 
                                         onerror="this.src='https://ui-avatars.com/api/?name=<?php echo urlencode($user_detail['name']); ?>&background=667eea&color=fff&size=45'">
                                    <div>
                                        <strong><?php echo htmlspecialchars($user_detail['name']); ?></strong><br>
                                        <small class="text-muted">ID: <?php echo $user_detail['user_id']; ?></small>
                                    </div>
                                </div>
                            </td>
                            
                            <td>
                                <i class="fas fa-phone-alt me-2 text-muted"></i><?php echo $user_detail['mobile'] ?: 'N/A'; ?><br>
                                <small class="text-muted">
                                    <i class="fas fa-user-tie me-1"></i>Sponsor: <?php echo $user_detail['sponsor_id']; ?>
                                </small>
                            </td>
                            
                            <td>
    <?php 
    if ($user_detail['package_id'] == 2500): ?>
        <span class="package-badge package-1">
            <i class="fas fa-box"></i> Package 1 (₹2,500)
        </span>
    <?php elseif ($user_detail['package_id'] == 3500): ?>
        <span class="package-badge package-2">
            <i class="fas fa-crown"></i> Package 2 (₹3,500)
        </span>
    <?php else: ?>
        <span class="package-badge" style="background: #f1f5f9; color: #64748b;">
            <i class="fas fa-minus"></i> No Package
        </span>
    <?php endif; ?>
</td>
                            
                            <td>
                                <i class="fas fa-calendar-alt me-2 text-muted"></i>
                                <?php echo date('d M Y', strtotime($user_detail['joining_date'])); ?><br>
                                <small class="text-muted"><?php echo date('h:i A', strtotime($user_detail['joining_date'])); ?></small>
                            </td>
                            
                            <td>
                                <div class="binary-tree-wrapper">
                                    <div class="parent-circle"></div>
                                    <svg viewBox="0 0 120 40" class="binary-lines">
                                        <path d="M60 0 C 40 10, 40 30, 20 40" stroke="#94a3b8" fill="transparent" stroke-dasharray="4"/>
                                        <path d="M60 0 C 50 10, 50 30, 40 40" stroke="#94a3b8" fill="transparent" stroke-dasharray="4"/>
                                        <path d="M60 0 C 70 10, 70 30, 80 40" stroke="#94a3b8" fill="transparent" stroke-dasharray="4"/>
                                        <path d="M60 0 C 80 10, 80 30, 100 40" stroke="#94a3b8" fill="transparent" stroke-dasharray="4"/>
                                    </svg>
                                    <div class="child-circle-container">
                                        <div class="child-circle <?php echo ($slots['left_1_id'] > 0) ? 'green' : 'grey'; ?>" 
                                             title="Left 1: <?php echo $slots['left_1_id'] ?: 'Empty'; ?>"></div>
                                        <div class="child-circle <?php echo ($slots['left_2_id'] > 0) ? 'green' : 'grey'; ?>" 
                                             title="Left 2: <?php echo $slots['left_2_id'] ?: 'Empty'; ?>"></div>
                                        <div class="child-circle <?php echo ($slots['right_1_id'] > 0) ? 'green' : 'grey'; ?>" 
                                             title="Right 1: <?php echo $slots['right_1_id'] ?: 'Empty'; ?>"></div>
                                        <div class="child-circle <?php echo ($slots['right_2_id'] > 0) ? 'green' : 'grey'; ?>" 
                                             title="Right 2: <?php echo $slots['right_2_id'] ?: 'Empty'; ?>"></div>
                                    </div>
                                </div>
                            </td>
                            
                            <td>
                                <span class="status-badge <?php echo ($user_detail['status'] == 0) ? 'status-active' : 'status-inactive'; ?>">
                                    <i class="fas fa-<?php echo ($user_detail['status'] == 0) ? 'check-circle' : 'times-circle'; ?> me-1"></i>
                                    <?php echo ($user_detail['status'] == 0) ? 'Active' : 'Inactive'; ?>
                                </span>
                            </td>
                            
                            <td>
                                <div class="d-flex gap-2">
                                    <a href="profile.php?user_id=<?php echo $user_detail['user_id']; ?>" 
                                       class="action-btn btn-view">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="level.php?user_id=<?php echo $user_detail['user_id']; ?>" 
                                       class="action-btn btn-tree">
                                        <i class="fas fa-sitemap"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" class="text-center py-5">
                                <i class="fas fa-users fa-4x text-muted mb-3"></i>
                                <h5 class="text-muted">No Downline Members Found</h5>
                                <p class="text-muted">Start building your team by referring new members</p>
                                <a href="pin.php" class="btn-modern">
                                    <i class="fas fa-plus-circle me-2"></i>Generate Referral PIN
                                </a>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </main>

    <!-- Footer -->
    <?php include('element/footer.php'); ?>

    <a href="#" class="back-to-top d-flex align-items-center justify-content-center">
        <i class="bi bi-arrow-up-short"></i>
    </a>

    <!-- Vendor JS Files -->
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/vendor/jquery/jquery-3.6.0.min.js"></script>
    <script src="assets/js/main.js"></script>

    <!-- DataTables -->
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/responsive.bootstrap5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>

    <script>
        // Initialize DataTable
        $(document).ready(function() {
            $('#downlineTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[0, 'asc']],
                language: {
                    search: "<i class='fas fa-search'></i>",
                    searchPlaceholder: "Search records...",
                    lengthMenu: "Show _MENU_ entries",
                    info: "Showing _START_ to _END_ of _TOTAL_ entries",
                    paginate: {
                        first: "First",
                        last: "Last",
                        next: "Next",
                        previous: "Previous"
                    }
                },
                dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'copy',
                        text: '<i class="fas fa-copy"></i> Copy',
                        className: 'btn-outline-modern btn-modern'
                    },
                    {
                        extend: 'excel',
                        text: '<i class="fas fa-file-excel"></i> Excel',
                        className: 'btn-outline-modern btn-modern'
                    },
                    {
                        extend: 'pdf',
                        text: '<i class="fas fa-file-pdf"></i> PDF',
                        className: 'btn-outline-modern btn-modern'
                    },
                    {
                        extend: 'print',
                        text: '<i class="fas fa-print"></i> Print',
                        className: 'btn-outline-modern btn-modern'
                    }
                ]
            });
        });

        // Toggle export menu
        function toggleExportMenu() {
            document.getElementById('exportMenu').classList.toggle('show');
        }

        // Close export menu when clicking outside
        window.onclick = function(event) {
            if (!event.target.matches('.btn-modern') && !event.target.closest('.btn-modern')) {
                var menus = document.getElementsByClassName('export-menu');
                for (var i = 0; i < menus.length; i++) {
                    menus[i].classList.remove('show');
                }
            }
        }

        // Export data function
        function exportData(type) {
            const search = document.querySelector('input[name="search"]').value;
            const package = document.querySelector('select[name="package"]').value;
            const dateFrom = document.querySelector('input[name="date_from"]').value;
            const dateTo = document.querySelector('input[name="date_to"]').value;
            
            window.location.href = `level.php?export=${type}&package_filter=${package}&date_from=${dateFrom}&date_to=${dateTo}`;
        }

        // Print table
        function printTable() {
            window.print();
        }

        // Show notification
        function showNotification(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 m-3`;
            alertDiv.style.zIndex = '9999';
            alertDiv.innerHTML = `
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'info-circle'} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(alertDiv);
            
            setTimeout(() => alertDiv.remove(), 3000);
        }

        // Check for messages from export
        <?php if (isset($_GET['msg']) && $_GET['msg'] == 'pdf_export_coming_soon'): ?>
        showNotification('PDF export feature coming soon!', 'info');
        <?php endif; ?>
    </script>

    <!-- Add this to your footer for better performance -->
    <style>
        /* Print styles */
        @media print {
            .header, .sidebar, .footer, .back-to-top, .filter-section, .btn-modern, .dataTables_filter, .dataTables_length, .dt-buttons {
                display: none !important;
            }
            
            .table-container {
                box-shadow: none;
                padding: 0;
            }
            
            table {
                width: 100% !important;
            }
        }
    </style>

</body>
</html>