<?php
$pageTitle = 'Dashboard';
require_once __DIR__ . '/includes/header.php';

// Get statistics
try {
    $db = getDB();
    
    // Total servers
    $totalServers = $db->query("SELECT COUNT(*) FROM vpn_servers")->fetchColumn();
    $activeServers = $db->query("SELECT COUNT(*) FROM vpn_servers WHERE status = 'active'")->fetchColumn();
    
    // Total API keys
    $totalAPIs = $db->query("SELECT COUNT(*) FROM api_keys")->fetchColumn();
    $activeAPIs = $db->query("SELECT COUNT(*) FROM api_keys WHERE status = 'active'")->fetchColumn();
    
    // Total API requests (last 24 hours)
    $apiRequests24h = $db->query("SELECT COUNT(*) FROM api_logs WHERE request_time >= DATE_SUB(NOW(), INTERVAL 24 HOUR)")->fetchColumn();
    
    // Total API requests (all time)
    $apiRequestsTotal = $db->query("SELECT COUNT(*) FROM api_logs")->fetchColumn();
    
    // Recent API logs
    $recentLogs = $db->query("SELECT * FROM api_logs ORDER BY request_time DESC LIMIT 10")->fetchAll();
    
    // Top APIs by usage
    $topAPIs = $db-> query("SELECT api_key, COUNT(*) as total FROM api_logs GROUP BY api_key ORDER BY total DESC LIMIT 5")->fetchAll();
    
} catch (PDOException $e) {
    logActivity("Dashboard error: " . $e->getMessage(), 'error');
    $totalServers = $activeServers = $totalAPIs = $activeAPIs = $apiRequests24h = $apiRequestsTotal = 0;
    $recentLogs = $topAPIs = [];
}
?>

<div class="dashboard-grid">
    <!-- Stats Cards -->
    <div class="stats-row">
        <div class="stat-card stat-servers">
            <div class="stat-icon">🌐</div>
            <div class="stat-details">
                <h3><?= $totalServers ?></h3>
                <p>Total Servers</p>
                <span class="stat-badge"><?= $activeServers ?> Active</span>
            </div>
        </div>
        
        <div class="stat-card stat-apis">
            <div class="stat-icon">🔑</div>
            <div class="stat-details">
                <h3><?= $totalAPIs ?></h3>
                <p>API Keys</p>
                <span class="stat-badge"><?= $activeAPIs ?> Active</span>
            </div>
        </div>
        
        <div class="stat-card stat-requests">
            <div class="stat-icon">📊</div>
            <div class="stat-details">
                <h3><?= number_format($apiRequests24h) ?></h3>
                <p>Requests (24h)</p>
                <span class="stat-badge"><?= number_format($apiRequestsTotal) ?> Total</span>
            </div>
        </div>
        
        <div class="stat-card stat-status">
            <div class="stat-icon">✅</div>
            <div class="stat-details">
                <h3>Online</h3>
                <p>System Status</p>
                <span class="stat-badge badge-success">All Systems Operational</span>
            </div>
        </div>
    </div>
    
    <!-- Quick Actions -->
    <div class="card">
        <div class="card-header">
            <h2>Quick Actions</h2>
        </div>
        <div class="card-body">
            <div class="quick-actions">
                <a href="servers.php?action=add" class="action-btn btn-primary">
                    <span>➕</span> Add Server
                </a>
                <a href="api-keys.php?action=generate" class="action-btn btn-success">
                    <span>🔑</span> Generate API Key
                </a>
                <a href="api-logs.php" class="action-btn btn-info">
                    <span>📊</span> View Logs
                </a>
                <a href="settings.php" class="action-btn btn-secondary">
                    <span>⚙️</span> Settings
                </a>
            </div>
        </div>
    </div>
    
    <!-- Recent API Activity -->
    <div class="card">
        <div class="card-header">
            <h2>Recent API Activity</h2>
            <a href="api-logs.php" class="btn btn-sm btn-outline">View All</a>
        </div>
        <div class="card-body">
            <?php if (empty($recentLogs)): ?>
                <p class="text-muted text-center">No API activity yet</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Time</th>
                                <th>API Key</th>
                                <th>Request Type</th>
                                <th>IP Address</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recentLogs as $log): ?>
                                <tr>
                                    <td><?= date('M d, H:i', strtotime($log['request_time'])) ?></td>
                                    <td><code><?= esc(substr($log['api_key'], 0, 16)) ?>...</code></td>
                                    <td><?= esc($log['request_type']) ?></td>
                                    <td><?= esc($log['ip_address']) ?></td>
                                    <td>
                                        <span class="badge badge-<?= $log['response_status'] === 'success' ? 'success' : 'danger' ?>">
                                            <?= esc($log['response_status']) ?>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Top APIs by Usage -->
    <div class="card">
        <div class="card-header">
            <h2>Top APIs by Usage</h2>
        </div>
        <div class="card-body">
            <?php if (empty($topAPIs)): ?>
                <p class="text-muted text-center">No usage data yet</p>
            <?php else: ?>
                <div class="api-usage-list">
                    <?php foreach ($topAPIs as $index => $api): ?>
                        <div class="usage-item">
                            <div class="usage-rank">#<?= $index + 1 ?></div>
                            <div class="usage-details">
                                <code><?= esc(substr($api['api_key'], 0, 20)) ?>...</code>
                                <span class="text-muted"><?= number_format($api['total']) ?> requests</span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
