<?php
include 'security_middleware.php';
include 'config.php';

// Only allow admin access
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    die("Access denied. Admin only.");
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>🛡️ Security Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://use.fontawesome.com/releases/v6.0.0/css/all.css" rel="stylesheet">
    <meta http-equiv="refresh" content="30">
    <style>
        body { background: #1a1d29; color: #fff; }
        .security-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .alert-critical { background: #dc3545; animation: pulse 2s infinite; }
        .alert-high { background: #fd7e14; }
        .alert-medium { background: #ffc107; color: #000; }
        .alert-low { background: #28a745; }
        @keyframes pulse { 0%, 100% { opacity: 0.8; } 50% { opacity: 1; } }
        
        /* Emoji fallback styles */
        .emoji-icon { font-size: 1.2em; margin-right: 0.3em; }
        
        /* If Font Awesome fails to load, hide the icons and rely on emoji */
        @media all and (-webkit-min-device-pixel-ratio: 0) and (min-resolution: .001dpcm) {
            .fas::before { content: '' !important; }
        }
    </style>
</head>
<body>
<div class="container-fluid mt-3">
    <div class="row">
        <div class="col-12">
            <h1>🛡️ <i class="fas fa-shield-alt"></i> Security Dashboard</h1>
            <p class="lead">Real-time security monitoring • Auto-refresh: 30s</p>
        </div>
    </div>

    <div class="row">
        <!-- Security Events -->
        <div class="col-md-6">
            <div class="card security-card">
                <div class="card-header">
                    <h4>🚨 <i class="fas fa-exclamation-triangle"></i> Recent Security Events</h4>
                </div>
                <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                    <?php
                    if (file_exists('security_events.log')) {
                        $events = file('security_events.log', FILE_IGNORE_NEW_LINES);
                        $recent_events = array_slice($events, -20);
                        $recent_events = array_reverse($recent_events);
                        
                        foreach ($recent_events as $event) {
                            $data = json_decode($event, true);
                            if ($data) {
                                $severity_class = match($data['severity']) {
                                    'CRITICAL' => 'alert-critical',
                                    'HIGH' => 'alert-high',
                                    'MEDIUM' => 'alert-medium',
                                    default => 'alert-low'
                                };
                                
                                echo "<div class='alert $severity_class mb-2'>";
                                echo "<strong>[{$data['severity']}]</strong> {$data['timestamp']}<br>";
                                echo "{$data['message']}<br>";
                                echo "<small>IP: {$data['ip']} | User: {$data['user_id']}</small>";
                                echo "</div>";
                            }
                        }
                    } else {
                        echo "<p class='text-muted'>No security events logged yet.</p>";
                    }
                    ?>
                </div>
            </div>
        </div>

        <!-- System Status -->
        <div class="col-md-6">
            <div class="card security-card">
                <div class="card-header">
                    <h4>📊 <i class="fas fa-chart-line"></i> System Status</h4>
                </div>
                <div class="card-body">
                    <?php
                    // Check product integrity
                    $product_count = $conn->query("SELECT COUNT(*) as count FROM products")->fetch_assoc()['count'];
                    $max_id = $conn->query("SELECT MAX(id) as max_id FROM products")->fetch_assoc()['max_id'];
                    $integrity_score = $max_id > 0 ? round(($product_count / $max_id) * 100, 1) : 100;
                    
                    echo "<h5>📊 Database Integrity</h5>";
                    echo "<p><strong>Products:</strong> $product_count (ID sequence: $max_id)</p>";
                    echo "<p><strong>Integrity Score:</strong> {$integrity_score}%</p>";
                    
                    if ($integrity_score < 90) {
                        echo "<div class='alert alert-critical'>⚠️ Significant deletions detected!</div>";
                    } else {
                        echo "<div class='alert alert-low'>✅ Database integrity good</div>";
                    }
                    
                    // Check recent bot activity
                    echo "<h5 class='mt-3'>🤖 Bot Activity (Last 24h)</h5>";
                    if (file_exists('security_events.log')) {
                        $events = file_get_contents('security_events.log');
                        $bot_events = substr_count(strtolower($events), 'bot');
                        echo "<p><strong>Bot-related events:</strong> $bot_events</p>";
                        
                        if ($bot_events > 10) {
                            echo "<div class='alert alert-high'>🚨 High bot activity detected</div>";
                        } else {
                            echo "<div class='alert alert-low'>✅ Normal bot activity</div>";
                        }
                    }
                    
                    // Security file status
                    echo "<h5 class='mt-3'>🔧 Security Files Status</h5>";
                    $security_files = [
                        'robots.txt' => 'Bot blocking rules',
                        '.htaccess' => 'Web server security',
                        'security_middleware.php' => 'Application security'
                    ];
                    
                    foreach ($security_files as $file => $description) {
                        $status = file_exists($file) ? 
                            "<span class='badge bg-success'>✅ Active</span>" : 
                            "<span class='badge bg-danger'>❌ Missing</span>";
                        echo "<p><strong>$description:</strong> $status</p>";
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>

    <div class="row mt-3">
        <!-- Blocked IPs -->
        <div class="col-md-4">
            <div class="card security-card">
                <div class="card-header">
                    <h5>🚫 <i class="fas fa-ban"></i> IP Monitoring</h5>
                </div>
                <div class="card-body">
                    <?php
                    // Show top IPs from security events
                    if (file_exists('security_events.log')) {
                        $events = file('security_events.log', FILE_IGNORE_NEW_LINES);
                        $ip_counts = [];
                        
                        foreach ($events as $event) {
                            $data = json_decode($event, true);
                            if ($data && isset($data['ip'])) {
                                $ip_counts[$data['ip']] = ($ip_counts[$data['ip']] ?? 0) + 1;
                            }
                        }
                        
                        arsort($ip_counts);
                        $top_ips = array_slice($ip_counts, 0, 5, true);
                        
                        echo "<h6>Top IPs (Events)</h6>";
                        foreach ($top_ips as $ip => $count) {
                            $alert_level = $count > 10 ? 'danger' : ($count > 5 ? 'warning' : 'info');
                            echo "<p><code>$ip</code> <span class='badge bg-$alert_level'>$count</span></p>";
                        }
                    }
                    
                    // Blacklist status
                    if (file_exists('security_blacklist.txt')) {
                        $blacklisted = count(file('security_blacklist.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
                        echo "<h6 class='mt-3'>🚫 Blacklisted IPs</h6>";
                        echo "<p><strong>$blacklisted</strong> IPs blocked</p>";
                    }
                    ?>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="col-md-4">
            <div class="card security-card">
                <div class="card-header">
                    <h5>🔧 <i class="fas fa-tools"></i> Security Tools</h5>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <button onclick="clearSecurityLogs()" class="btn btn-warning">
                            <i class="fas fa-broom"></i> Clear Old Logs
                        </button>
                        <button onclick="exportSecurityReport()" class="btn btn-info">
                            <i class="fas fa-download"></i> Export Report
                        </button>
                        <a href="products/" class="btn btn-success">
                            <i class="fas fa-box"></i> Manage Products
                        </a>
                        <a href="detective.php" class="btn btn-secondary">
                            <i class="fas fa-search"></i> Detective Mode
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- System Health -->
        <div class="col-md-4">
            <div class="card security-card">
                <div class="card-header">
                    <h5><i class="fas fa-heartbeat"></i> System Health</h5>
                </div>
                <div class="card-body">
                    <?php
                    echo "<p><strong>PHP Version:</strong> " . PHP_VERSION . "</p>";
                    echo "<p><strong>Memory Usage:</strong> " . round(memory_get_usage() / 1024 / 1024, 2) . " MB</p>";
                    echo "<p><strong>Server Time:</strong> " . date('Y-m-d H:i:s') . "</p>";
                    
                    // Database connection status
                    if ($conn->ping()) {
                        echo "<p><strong>Database:</strong> <span class='badge bg-success'>Connected</span></p>";
                    } else {
                        echo "<p><strong>Database:</strong> <span class='badge bg-danger'>Disconnected</span></p>";
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function clearSecurityLogs() {
    if (confirm('Clear security logs older than 7 days?')) {
        fetch('security_cleanup.php', {method: 'POST'})
            .then(() => location.reload());
    }
}

function exportSecurityReport() {
    window.open('security_export.php', '_blank');
}

console.log('🛡️ Security Dashboard Active');
</script>
</body>
</html>