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


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

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

// Get today's date
$today = date('Y-m-d');
$current_month = date('m');
$current_year = date('Y');

// Fetch today's income
$today_income_query = mysqli_query($conn, "SELECT SUM(amount) as total FROM income_history 
                                          WHERE user_id = '$my_id' AND DATE(created_at) = '$today'");
$today_income = mysqli_fetch_assoc($today_income_query)['total'] ?? 0;

// Fetch monthly income
$month_income_query = mysqli_query($conn, "SELECT SUM(amount) as total FROM income_history 
                                          WHERE user_id = '$my_id' AND MONTH(created_at) = '$current_month' 
                                          AND YEAR(created_at) = '$current_year'");
$month_income = mysqli_fetch_assoc($month_income_query)['total'] ?? 0;

// Fetch total downline count
$total_downline = $user_data['left_count'] + $user_data['right_count'];

// Fetch direct customers
$direct_customers = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM users WHERE sponsor_id = '$my_id'"));

// Fetch available PINs
$available_pins = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM pin WHERE allcote_user = '$my_id' AND status = '0'"));

// Fetch recent activities
$recent_activities = mysqli_query($conn, "SELECT * FROM income_history 
                                         WHERE user_id = '$my_id' 
                                         ORDER BY created_at DESC LIMIT 10");

// Fetch chart data for last 7 days
$chart_data = [];
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $income = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM income_history 
                                                      WHERE user_id = '$my_id' AND DATE(created_at) = '$date'"));
    $chart_data['dates'][] = date('d M', strtotime($date));
    $chart_data['income'][] = (float)($income['total'] ?? 0);
    $chart_data['downline'][] = $total_downline;
    $chart_data['customers'][] = $direct_customers;
}

// Fetch rank details
$ranks = [
    'NO Rank' => 0,
    'Bronze' => 60,
    'Silver' => 300,
    'Gold' => 1000,
    'Platinum' => 2000,
    'Diamond' => 5000,
    'Emerald' => 10000,
    'Garnet' => 20000,
    'Ruby' => 50000,
    'Star' => 100000,
    '2 Star' => 200000
];

$next_rank = '';
$pairs_needed = 0;
foreach ($ranks as $rank => $pairs) {
    if ($pairs > $user_data['total_pairs']) {
        $next_rank = $rank;
        $pairs_needed = $pairs - $user_data['total_pairs'];
        break;
    }
}
?>

<!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']); ?> || Dashboard</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/quill/quill.snow.css" rel="stylesheet">
    <link href="assets/vendor/quill/quill.bubble.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">

    <!-- ApexCharts -->
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

    <!-- 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%);
            --dark-gradient: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
            --primary-color: #667eea;
            --secondary-color: #764ba2;
        }

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

        /* Welcome Section */
        .welcome-section {
            background: var(--primary-gradient);
            border-radius: 30px;
            padding: 40px;
            margin-bottom: 30px;
            color: white;
            position: relative;
            overflow: hidden;
        }

        .welcome-section::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -10%;
            width: 300px;
            height: 300px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }

        .welcome-section::after {
            content: '';
            position: absolute;
            bottom: -30%;
            left: -5%;
            width: 200px;
            height: 200px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }

        .welcome-title {
            font-size: 2.5rem;
            font-weight: 800;
            margin-bottom: 10px;
            position: relative;
            z-index: 1;
        }

        .welcome-subtitle {
            font-size: 1.1rem;
            opacity: 0.9;
            position: relative;
            z-index: 1;
        }

        .rank-badge {
            background: rgba(255, 255, 255, 0.2);
            padding: 10px 25px;
            border-radius: 50px;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            font-weight: 600;
            position: relative;
            z-index: 1;
        }

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

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

        .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: 20px;
            font-size: 24px;
            background: var(--primary-gradient);
            color: white;
        }

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

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

        .stat-change {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 0.9rem;
            color: #10b981;
        }

        /* Progress Card */
        .progress-card {
            background: white;
            border-radius: 24px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            margin-bottom: 25px;
        }

        .progress-title {
            font-size: 1.1rem;
            font-weight: 600;
            margin-bottom: 15px;
            color: #1e293b;
        }

        .progress-stats {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }

        .progress-current {
            font-size: 1.5rem;
            font-weight: 700;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .progress-target {
            color: #64748b;
            font-weight: 500;
        }

        .progress {
            height: 12px;
            border-radius: 30px;
            background: #e2e8f0;
            margin-bottom: 15px;
        }

        .progress-bar {
            background: var(--primary-gradient);
            border-radius: 30px;
        }

        .next-rank {
            background: #f8fafc;
            padding: 15px;
            border-radius: 16px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .next-rank i {
            color: var(--primary-color);
            font-size: 20px;
        }

        /* Chart Container */
        .chart-container {
            background: white;
            border-radius: 24px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            margin-bottom: 25px;
        }

        .chart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .chart-title {
            font-size: 1.2rem;
            font-weight: 700;
            color: #1e293b;
        }

        .chart-filters {
            display: flex;
            gap: 10px;
        }

        .chart-filter {
            padding: 8px 16px;
            border-radius: 30px;
            font-size: 0.9rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #f1f5f9;
            color: #64748b;
            border: none;
        }

        .chart-filter:hover,
        .chart-filter.active {
            background: var(--primary-gradient);
            color: white;
        }

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

        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .table-title {
            font-size: 1.2rem;
            font-weight: 700;
            color: #1e293b;
        }

        .table-search {
            padding: 10px 20px;
            border: 2px solid #e2e8f0;
            border-radius: 30px;
            font-size: 0.95rem;
            width: 300px;
            transition: all 0.3s ease;
        }

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

        .custom-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0 10px;
        }

        .custom-table thead th {
            padding: 15px 20px;
            font-size: 0.9rem;
            font-weight: 700;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border: none;
            background: #f8fafc;
        }

        .custom-table tbody tr {
            background: white;
            border-radius: 16px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.03);
            transition: all 0.3s ease;
        }

        .custom-table tbody tr:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.15);
        }

        .custom-table tbody td {
            padding: 20px;
            vertical-align: middle;
            border: none;
        }

        .badge-custom {
            padding: 6px 15px;
            border-radius: 30px;
            font-size: 0.85rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .badge-success {
            background: #dcfce7;
            color: #166534;
        }

        .badge-warning {
            background: #fed7aa;
            color: #9a3412;
        }

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

        /* Activity List */
        .activity-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .activity-item {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 0;
            border-bottom: 1px solid #e2e8f0;
        }

        .activity-item:last-child {
            border-bottom: none;
        }

        .activity-icon {
            width: 45px;
            height: 45px;
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .activity-icon.income { background: #dcfce7; color: #166534; }
        .activity-icon.withdraw { background: #fee2e2; color: #991b1b; }
        .activity-icon.pin { background: #dbeafe; color: #1e40af; }

        .activity-details {
            flex: 1;
        }

        .activity-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 3px;
        }

        .activity-time {
            font-size: 0.85rem;
            color: #64748b;
        }

        .activity-amount {
            font-weight: 700;
            color: #10b981;
        }

        /* Quick Actions */
        .quick-actions {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin-top: 25px;
        }

        .quick-action {
            background: white;
            border-radius: 20px;
            padding: 20px;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            border: 1px solid #e2e8f0;
        }

        .quick-action:hover {
            transform: translateY(-5px);
            border-color: var(--primary-color);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.15);
        }

        .quick-action i {
            font-size: 28px;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 10px;
        }

        .quick-action span {
            display: block;
            font-weight: 600;
            color: #1e293b;
        }

        /* Animations */
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .animate-slide {
            animation: slideIn 0.5s ease forwards;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .welcome-title {
                font-size: 1.8rem;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .table-search {
                width: 100%;
            }
            
            .chart-header {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </style>
</head>

<body>

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

    <main id="main" class="main">
        <!-- Welcome Section -->
        <div class="welcome-section animate-slide">
            <div class="row align-items-center">
                <div class="col-lg-8">
                    <h1 class="welcome-title">Welcome back, <?php echo htmlspecialchars($user_data['name']); ?>! 👋</h1>
                    <p class="welcome-subtitle">Your dashboard is ready with latest updates and insights</p>
                    
                    <div class="rank-badge mt-4">
                        <i class="fas fa-crown"></i>
                        <span>Current Rank: <?php echo $user_data['rank']; ?></span>
                    </div>
                </div>
                <div class="col-lg-4 text-lg-end mt-4 mt-lg-0">
                    <i class="fas fa-chart-line" style="font-size: 100px; opacity: 0.2;"></i>
                </div>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-wallet"></i>
                </div>
                <div class="stat-label">Total Wallet Balance</div>
                <div class="stat-value">₹<?php echo number_format($user_data['wallet'], 2); ?></div>
                <div class="stat-change">
                    <i class="fas fa-arrow-up"></i>
                    <span>+₹<?php echo number_format($today_income, 2); ?> today</span>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-users"></i>
                </div>
                <div class="stat-label">Total Downline</div>
                <div class="stat-value"><?php echo $total_downline; ?></div>
                <div class="stat-change">
                    <i class="fas fa-arrow-up"></i>
                    <span>+<?php echo $user_data['left_count']; ?> Left | <?php echo $user_data['right_count']; ?> Right</span>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-user-plus"></i>
                </div>
                <div class="stat-label">Direct Customers</div>
                <div class="stat-value"><?php echo $direct_customers; ?></div>
                <div class="stat-change">
                    <i class="fas fa-arrow-up"></i>
                    <span>Active members</span>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-ticket-alt"></i>
                </div>
                <div class="stat-label">Available E-PINs</div>
                <div class="stat-value"><?php echo $available_pins; ?></div>
                <div class="stat-change">
                    <i class="fas fa-tag"></i>
                    <span><?php echo $available_pins; ?> PINs available</span>
                </div>
            </div>
        </div>

        <!-- Progress Card -->
        <div class="progress-card">
            <div class="progress-title">Rank Progress - Next Rank: <?php echo $next_rank ?: 'Max Rank Reached'; ?></div>
            <?php if ($next_rank): ?>
                <div class="progress-stats">
                    <span class="progress-current"><?php echo $user_data['total_pairs']; ?> Pairs</span>
                    <span class="progress-target">Target: <?php echo $pairs_needed + $user_data['total_pairs']; ?> Pairs</span>
                </div>
                <div class="progress">
                    <?php
                    $target_pairs = $pairs_needed + $user_data['total_pairs'];
                    $progress_percentage = ($user_data['total_pairs'] / $target_pairs) * 100;
                    ?>
                    <div class="progress-bar" style="width: <?php echo $progress_percentage; ?>%"></div>
                </div>
                <div class="next-rank">
                    <i class="fas fa-info-circle"></i>
                    <span>You need <?php echo $pairs_needed; ?> more pairs to reach <?php echo $next_rank; ?> rank</span>
                </div>
            <?php else: ?>
                <div class="text-center py-3">
                    <i class="fas fa-trophy fa-3x" style="color: #fbbf24;"></i>
                    <h5 class="mt-3">Congratulations! You've reached the highest rank!</h5>
                </div>
            <?php endif; ?>
        </div>

        <div class="row">
            <div class="col-lg-8">
                <!-- Chart Section -->
                <div class="chart-container">
                    <div class="chart-header">
                        <h5 class="chart-title">Performance Overview</h5>
                        <div class="chart-filters">
                            <button class="chart-filter active" onclick="changeChartPeriod('week')">Week</button>
                            <button class="chart-filter" onclick="changeChartPeriod('month')">Month</button>
                            <button class="chart-filter" onclick="changeChartPeriod('year')">Year</button>
                        </div>
                    </div>
                    <div id="performanceChart"></div>
                </div>

                <!-- Recent Members Table -->
                <div class="table-container">
                    <div class="table-header">
                        <h5 class="table-title">Recent Team Members</h5>
                        <input type="text" class="table-search" placeholder="Search members..." id="searchInput">
                    </div>
                    
                    <table class="custom-table" id="membersTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Member Name</th>
                                <th>User ID</th>
                                <th>Phone</th>
                                <th>Position</th>
                                <th>Join Date</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $recent_members = mysqli_query($conn, "SELECT * FROM users WHERE sponsor_id = '$my_id' ORDER BY id DESC LIMIT 10");
                            $count = 1;
                            while ($member = mysqli_fetch_assoc($recent_members)):
                                $position_class = $member['position'] == 0 ? 'badge-info' : 'badge-success';
                                $position_text = $member['position'] == 0 ? 'Left' : 'Right';
                            ?>
                            <tr>
                                <td><?php echo $count++; ?></td>
                                <td>
                                    <strong><?php echo htmlspecialchars($member['name']); ?></strong>
                                </td>
                                <td>
                                    <span class="badge-custom badge-info"><?php echo $member['user_id']; ?></span>
                                </td>
                                <td><?php echo $member['mobile'] ?: 'N/A'; ?></td>
                                <td>
                                    <span class="badge-custom <?php echo $position_class; ?>">
                                        <i class="fas fa-<?php echo $member['position'] == 0 ? 'arrow-left' : 'arrow-right'; ?>"></i>
                                        <?php echo $position_text; ?>
                                    </span>
                                </td>
                                <td><?php echo date('d M Y', strtotime($member['joining_date'])); ?></td>
                                <td>
                                    <a href="tree.php?user_id=<?php echo $member['user_id']; ?>" class="btn-action btn-copy" style="padding: 5px 15px; border-radius: 8px; text-decoration: none;">
                                        <i class="fas fa-eye"></i> View
                                    </a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="col-lg-4">
                <!-- Recent Activities -->
                <div class="chart-container">
                    <h5 class="chart-title mb-4">Recent Activities</h5>
                    <ul class="activity-list">
                        <?php while ($activity = mysqli_fetch_assoc($recent_activities)): ?>
                        <li class="activity-item">
                            <div class="activity-icon <?php echo $activity['credit_debit'] == 0 ? 'income' : 'withdraw'; ?>">
                                <i class="fas fa-<?php echo $activity['credit_debit'] == 0 ? 'arrow-down' : 'arrow-up'; ?>"></i>
                            </div>
                            <div class="activity-details">
                                <div class="activity-title"><?php echo htmlspecialchars($activity['description']); ?></div>
                                <div class="activity-time"><?php echo date('d M Y, h:i A', strtotime($activity['created_at'])); ?></div>
                            </div>
                            <div class="activity-amount <?php echo $activity['credit_debit'] == 0 ? 'text-success' : 'text-danger'; ?>">
                                <?php echo $activity['credit_debit'] == 0 ? '+' : '-'; ?>₹<?php echo number_format($activity['amount'], 2); ?>
                            </div>
                        </li>
                        <?php endwhile; ?>
                        
                        <?php if (mysqli_num_rows($recent_activities) == 0): ?>
                        <li class="text-center py-4 text-muted">No recent activities found</li>
                        <?php endif; ?>
                    </ul>
                </div>

                <!-- Quick Actions -->
                <div class="chart-container">
                    <h5 class="chart-title mb-4">Quick Actions</h5>
                    <div class="quick-actions">
                        <a href="pin.php" class="quick-action text-decoration-none">
                            <i class="fas fa-plus-circle"></i>
                            <span>Generate PIN</span>
                        </a>
                        <a href="withdraw.php" class="quick-action text-decoration-none">
                            <i class="fas fa-money-bill-wave"></i>
                            <span>Withdraw</span>
                        </a>
                        <a href="profile.php" class="quick-action text-decoration-none">
                            <i class="fas fa-user-edit"></i>
                            <span>Edit Profile</span>
                        </a>
                        <a href="tree.php" class="quick-action text-decoration-none">
                            <i class="fas fa-sitemap"></i>
                            <span>View Tree</span>
                        </a>
                    </div>
                </div>

                <!-- Income Summary -->
                <div class="chart-container">
                    <h5 class="chart-title mb-4">Income Summary</h5>
                    <div class="d-flex justify-content-between mb-3">
                        <span class="text-muted">Today's Income:</span>
                        <span class="fw-bold text-success">+₹<?php echo number_format($today_income, 2); ?></span>
                    </div>
                    <div class="d-flex justify-content-between mb-3">
                        <span class="text-muted">This Month:</span>
                        <span class="fw-bold text-success">+₹<?php echo number_format($month_income, 2); ?></span>
                    </div>
                    <div class="d-flex justify-content-between mb-3">
                        <span class="text-muted">Total Withdrawals:</span>
                        <span class="fw-bold text-danger">-₹<?php echo number_format($user_data['withdrawl_inc'], 2); ?></span>
                    </div>
                    <div class="d-flex justify-content-between pt-3 border-top">
                        <span class="fw-bold">Net Balance:</span>
                        <span class="fw-bold text-primary">₹<?php echo number_format($user_data['wallet'], 2); ?></span>
                    </div>
                </div>
            </div>
        </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>

    <script>
        // Performance Chart
        var options = {
            series: [{
                name: 'Income',
                data: <?php echo json_encode($chart_data['income']); ?>
            }, {
                name: 'Downline Growth',
                data: <?php echo json_encode(array_fill(0, 7, $total_downline)); ?>
            }, {
                name: 'New Customers',
                data: <?php echo json_encode(array_fill(0, 7, $direct_customers)); ?>
            }],
            chart: {
                type: 'area',
                height: 350,
                toolbar: {
                    show: false
                },
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800
                }
            },
            colors: ['#667eea', '#10b981', '#f59e0b'],
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.3,
                    opacityTo: 0.1
                }
            },
            dataLabels: {
                enabled: false
            },
            stroke: {
                curve: 'smooth',
                width: 3
            },
            xaxis: {
                categories: <?php echo json_encode($chart_data['dates']); ?>,
                labels: {
                    style: {
                        colors: '#64748b',
                        fontSize: '12px'
                    }
                }
            },
            yaxis: {
                labels: {
                    formatter: function(value) {
                        return '₹' + value;
                    },
                    style: {
                        colors: '#64748b',
                        fontSize: '12px'
                    }
                }
            },
            legend: {
                position: 'top',
                horizontalAlign: 'right',
                labels: {
                    colors: '#1e293b'
                }
            },
            tooltip: {
                y: {
                    formatter: function(value) {
                        return '₹' + value;
                    }
                }
            },
            grid: {
                borderColor: '#e2e8f0',
                strokeDashArray: 5
            }
        };

        var chart = new ApexCharts(document.querySelector("#performanceChart"), options);
        chart.render();

        // Chart period change
        function changeChartPeriod(period) {
            // Update active filter
            document.querySelectorAll('.chart-filter').forEach(btn => {
                btn.classList.remove('active');
            });
            event.target.classList.add('active');
            
            // Here you would typically fetch new data based on period
            // For now, we'll just show a notification
            showNotification('Chart period changed to ' + period, 'info');
        }

        // Table search functionality
        document.getElementById('searchInput').addEventListener('keyup', function() {
            var searchTerm = this.value.toLowerCase();
            var tableRows = document.querySelectorAll('#membersTable tbody tr');
            
            tableRows.forEach(row => {
                var text = row.textContent.toLowerCase();
                row.style.display = text.includes(searchTerm) ? '' : 'none';
            });
        });

        // Show notification function
        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="bi bi-${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);
        }

        // Auto refresh data every 30 seconds
        setInterval(function() {
            // Refresh chart data
            fetch('api/get_dashboard_data.php')
                .then(response => response.json())
                .then(data => {
                    // Update chart with new data
                    chart.updateSeries([{
                        name: 'Income',
                        data: data.income
                    }, {
                        name: 'Downline Growth',
                        data: data.downline
                    }, {
                        name: 'New Customers',
                        data: data.customers
                    }]);
                })
                .catch(error => console.log('Auto-refresh error:', error));
        }, 30000);

        // Initialize tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function(tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    </script>

    <!-- Add this to your footer for better performance -->
    <script>
        // Lazy load images
        document.addEventListener("DOMContentLoaded", function() {
            var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
            
            if ("IntersectionObserver" in window) {
                let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
                    entries.forEach(function(entry) {
                        if (entry.isIntersecting) {
                            let lazyImage = entry.target;
                            lazyImage.src = lazyImage.dataset.src;
                            lazyImage.classList.remove("lazy");
                            lazyImageObserver.unobserve(lazyImage);
                        }
                    });
                });

                lazyImages.forEach(function(lazyImage) {
                    lazyImageObserver.observe(lazyImage);
                });
            }
        });
    </script>

</body>
</html>