<?php
/**
 * ============================================================================
 * admin/security-dashboard.php - Security Overview Dashboard
 * Monitor security threats, failed logins, and suspicious activities
 * ============================================================================
 */

require_once __DIR__ . '/includes/base.php';

if (!hasAdminPermission('view_security_logs')) {
    setFlashMessage('Access denied.', 'error');
    header('Location: ' . APP_URL . '/admin/index.php');
    exit();
}

$breadcrumbs = [['title' => 'Security Dashboard', 'url' => '']];

// Fetch security statistics
try {
    // Recent threats
    $sql = "SELECT * FROM security_threats ORDER BY detected_at DESC LIMIT 20";
    $stmt = $db->query($sql);
    $threats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Failed login attempts
    $sql = "SELECT COUNT(*) as total, COUNT(DISTINCT ip_address) as unique_ips, MAX(attempted_at) as last_attempt
            FROM failed_login_attempts 
            WHERE attempted_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)";
    $stmt = $db->query($sql);
    $failed_logins = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Blocked IPs
    $sql = "SELECT COUNT(*) as total FROM ip_access_control WHERE status = 'blocked' AND is_active = 1";
    $stmt = $db->query($sql);
    $blocked_ips = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Security stats
    $sql = "SELECT 
                COUNT(*) as total_threats,
                SUM(CASE WHEN threat_type = 'brute_force' THEN 1 ELSE 0 END) as brute_force,
                SUM(CASE WHEN threat_type = 'sql_injection' THEN 1 ELSE 0 END) as sql_injection,
                SUM(CASE WHEN threat_type = 'xss' THEN 1 ELSE 0 END) as xss,
                SUM(CASE WHEN threat_type = 'ddos' THEN 1 ELSE 0 END) as ddos,
                SUM(CASE WHEN severity = 'critical' THEN 1 ELSE 0 END) as critical,
                SUM(CASE WHEN severity = 'high' THEN 1 ELSE 0 END) as high,
                SUM(CASE WHEN severity = 'medium' THEN 1 ELSE 0 END) as medium,
                SUM(CASE WHEN is_resolved = 0 THEN 1 ELSE 0 END) as unresolved
            FROM security_threats
            WHERE detected_at > DATE_SUB(NOW(), INTERVAL 7 DAY)";
    $stmt = $db->query($sql);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Recent blocked IPs
    $sql = "SELECT * FROM ip_access_control WHERE status = 'blocked' ORDER BY created_at DESC LIMIT 10";
    $stmt = $db->query($sql);
    $recent_blocks = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    logError('Security dashboard error: ' . $e->getMessage());
    $threats = [];
    $failed_logins = ['total' => 0, 'unique_ips' => 0];
    $blocked_ips = 0;
    $stats = array_fill_keys(['total_threats', 'brute_force', 'sql_injection', 'xss', 'ddos', 'critical', 'high', 'medium', 'unresolved'], 0);
}

renderAdminHeader('Security Dashboard', $breadcrumbs);
?>

<style>
.security-stat-card {
    border-left: 4px solid;
    transition: transform 0.2s;
}
.security-stat-card:hover { transform: translateY(-5px); }
.threat-card {
    border-left: 4px solid;
    margin-bottom: 1rem;
}
.threat-card.critical { border-left-color: #dc3545; background: #fff5f5; }
.threat-card.high { border-left-color: #fd7e14; background: #fff9f0; }
.threat-card.medium { border-left-color: #ffc107; background: #fffef0; }
.threat-card.low { border-left-color: #0dcaf0; background: #f0fcff; }
</style>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">
            <i class="bi bi-shield-lock me-2"></i>Security Dashboard
        </h2>
        <p class="text-muted mb-0">Monitor security threats and system protection</p>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-danger" onclick="scanThreats()">
            <i class="bi bi-search me-2"></i>Scan Now
        </button>
        <a href="<?php echo APP_URL; ?>/admin/threat-detection.php" class="btn btn-primary">
            <i class="bi bi-shield-check me-2"></i>Threat Detection
        </a>
    </div>
</div>

<!-- Critical Alerts -->
<?php if ($stats['critical'] > 0): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <i class="bi bi-exclamation-triangle-fill me-2"></i>
    <strong>Critical Security Alert!</strong> <?php echo $stats['critical']; ?> critical threat(s) detected and require immediate attention.
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Security Statistics -->
<div class="row mb-4">
    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card border-0 shadow-sm security-stat-card" style="border-left-color: #dc3545;">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <h6 class="text-danger mb-1">Total Threats</h6>
                        <h2 class="mb-0 fw-bold"><?php echo $stats['total_threats']; ?></h2>
                        <small class="text-muted">Last 7 days</small>
                    </div>
                    <div class="bg-danger bg-opacity-10 p-3 rounded">
                        <i class="bi bi-shield-exclamation text-danger fs-3"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card border-0 shadow-sm security-stat-card" style="border-left-color: #ffc107;">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <h6 class="text-warning mb-1">Failed Logins</h6>
                        <h2 class="mb-0 fw-bold"><?php echo $failed_logins['total']; ?></h2>
                        <small class="text-muted">Last 24 hours</small>
                    </div>
                    <div class="bg-warning bg-opacity-10 p-3 rounded">
                        <i class="bi bi-key text-warning fs-3"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card border-0 shadow-sm security-stat-card" style="border-left-color: #6c757d;">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <h6 class="text-secondary mb-1">Blocked IPs</h6>
                        <h2 class="mb-0 fw-bold"><?php echo $blocked_ips; ?></h2>
                        <small class="text-muted">Currently active</small>
                    </div>
                    <div class="bg-secondary bg-opacity-10 p-3 rounded">
                        <i class="bi bi-ban text-secondary fs-3"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card border-0 shadow-sm security-stat-card" style="border-left-color: #dc3545;">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <h6 class="text-danger mb-1">Unresolved</h6>
                        <h2 class="mb-0 fw-bold"><?php echo $stats['unresolved']; ?></h2>
                        <small class="text-muted">Requires action</small>
                    </div>
                    <div class="bg-danger bg-opacity-10 p-3 rounded">
                        <i class="bi bi-exclamation-circle text-danger fs-3"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Threat Type Distribution -->
<div class="row mb-4">
    <div class="col-md-8">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">
                <h5 class="mb-0 fw-bold">Recent Security Threats</h5>
            </div>
            <div class="card-body">
                <?php if (empty($threats)): ?>
                <div class="text-center py-5">
                    <i class="bi bi-shield-check text-success" style="font-size: 4rem;"></i>
                    <p class="text-muted mt-3">No security threats detected</p>
                </div>
                <?php else: ?>
                <div style="max-height: 500px; overflow-y: auto;">
                    <?php foreach ($threats as $threat): ?>
                    <div class="threat-card card border-0 p-3 <?php echo $threat['severity']; ?>">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <div class="d-flex align-items-center mb-2">
                                    <span class="badge bg-<?php 
                                        echo $threat['severity'] === 'critical' ? 'danger' : 
                                            ($threat['severity'] === 'high' ? 'warning' : 
                                            ($threat['severity'] === 'medium' ? 'info' : 'secondary'));
                                    ?> me-2"><?php echo strtoupper($threat['severity']); ?></span>
                                    
                                    <span class="badge bg-dark me-2">
                                        <?php echo strtoupper(str_replace('_', ' ', $threat['threat_type'])); ?>
                                    </span>
                                    
                                    <?php if ($threat['is_resolved']): ?>
                                    <span class="badge bg-success">RESOLVED</span>
                                    <?php endif; ?>
                                </div>
                                
                                <strong><?php echo htmlspecialchars($threat['description']); ?></strong>
                                <div class="small text-muted mt-1">
                                    <i class="bi bi-hdd-network me-1"></i>IP: <?php echo htmlspecialchars($threat['source_ip']); ?>
                                    <?php if ($threat['user_id']): ?>
                                    | User ID: <?php echo $threat['user_id']; ?>
                                    <?php endif; ?>
                                </div>
                                <div class="small text-muted">
                                    <i class="bi bi-clock me-1"></i><?php echo timeAgo($threat['detected_at']); ?>
                                </div>
                            </div>
                            
                            <div class="d-flex flex-column gap-2">
                                <?php if (!$threat['is_resolved']): ?>
                                <button class="btn btn-sm btn-outline-danger" onclick="blockIP('<?php echo htmlspecialchars($threat['source_ip']); ?>')">
                                    <i class="bi bi-ban me-1"></i>Block IP
                                </button>
                                <button class="btn btn-sm btn-outline-success" onclick="resolveThreat(<?php echo $threat['id']; ?>)">
                                    <i class="bi bi-check me-1"></i>Resolve
                                </button>
                                <?php endif; ?>
                                <button class="btn btn-sm btn-outline-primary" onclick="viewThreatDetails(<?php echo $threat['id']; ?>)">
                                    <i class="bi bi-info-circle me-1"></i>Details
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <!-- Threat Types Chart -->
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header bg-white">
                <h6 class="mb-0 fw-bold">Threat Types (7 Days)</h6>
            </div>
            <div class="card-body">
                <canvas id="threatTypesChart" height="200"></canvas>
            </div>
        </div>
        
        <!-- Recently Blocked IPs -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <h6 class="mb-0 fw-bold">Recently Blocked IPs</h6>
                <a href="<?php echo APP_URL; ?>/admin/ip-blacklist.php" class="btn btn-sm btn-outline-primary">
                    View All
                </a>
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush">
                    <?php foreach ($recent_blocks as $block): ?>
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <strong><?php echo htmlspecialchars($block['ip_address']); ?></strong>
                                <br><small class="text-muted"><?php echo htmlspecialchars($block['reason'] ?? 'Security violation'); ?></small>
                            </div>
                            <button class="btn btn-sm btn-outline-success" onclick="unblockIP('<?php echo htmlspecialchars($block['ip_address']); ?>')">
                                <i class="bi bi-unlock"></i>
                            </button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Threat Details Modal -->
<div class="modal fade" id="threatDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Threat Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="threatDetailsContent">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
// Threat Types Chart
const threatCtx = document.getElementById('threatTypesChart');
new Chart(threatCtx, {
    type: 'doughnut',
    data: {
        labels: ['Brute Force', 'SQL Injection', 'XSS', 'DDoS'],
        datasets: [{
            data: [
                <?php echo $stats['brute_force']; ?>,
                <?php echo $stats['sql_injection']; ?>,
                <?php echo $stats['xss']; ?>,
                <?php echo $stats['ddos']; ?>
            ],
            backgroundColor: ['#dc3545', '#fd7e14', '#ffc107', '#0dcaf0']
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { position: 'bottom' }
        }
    }
});

function blockIP(ip) {
    Swal.fire({
        title: 'Block IP Address',
        text: `Block ${ip}?`,
        input: 'select',
        inputOptions: {
            'temporary': 'Temporary (24 hours)',
            'permanent': 'Permanent'
        },
        showCancelButton: true,
        confirmButtonColor: '#dc3545'
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.post(APP_URL + '/api/admin.php', {
                action: 'block_ip',
                ip_address: ip,
                block_type: result.value
            }, function(response) {
                hideLoading();
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(response.message, 'error');
                }
            });
        }
    });
}

function unblockIP(ip) {
    Swal.fire({
        title: 'Unblock IP?',
        text: `Unblock ${ip}?`,
        showCancelButton: true,
        confirmButtonText: 'Unblock',
        confirmButtonColor: '#22c55e'
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.post(APP_URL + '/api/admin.php', {
                action: 'unblock_ip',
                ip_address: ip
            }, function(response) {
                hideLoading();
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                }
            });
        }
    });
}

function resolveThreat(threatId) {
    Swal.fire({
        title: 'Resolve Threat',
        input: 'textarea',
        inputPlaceholder: 'Resolution notes...',
        showCancelButton: true,
        confirmButtonText: 'Resolve'
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.post(APP_URL + '/api/admin.php', {
                action: 'resolve_security_threat',
                threat_id: threatId,
                resolution_notes: result.value
            }, function(response) {
                hideLoading();
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                }
            });
        }
    });
}

function viewThreatDetails(threatId) {
    $('#threatDetailsModal').modal('show');
    $.get(APP_URL + '/api/admin.php?action=get_threat_details&threat_id=' + threatId, function(response) {
        if (response.success) {
            const t = response.data;
            $('#threatDetailsContent').html(`
                <table class="table">
                    <tr><td><strong>Threat ID:</strong></td><td>#${t.id}</td></tr>
                    <tr><td><strong>Type:</strong></td><td><span class="badge bg-dark">${t.threat_type}</span></td></tr>
                    <tr><td><strong>Severity:</strong></td><td><span class="badge bg-danger">${t.severity}</span></td></tr>
                    <tr><td><strong>Source IP:</strong></td><td>${t.source_ip}</td></tr>
                    <tr><td><strong>Detected:</strong></td><td>${t.detected_at}</td></tr>
                    <tr><td><strong>Description:</strong></td><td>${t.description}</td></tr>
                    <tr><td><strong>Details:</strong></td><td><pre>${JSON.stringify(JSON.parse(t.threat_data || '{}'), null, 2)}</pre></td></tr>
                </table>
            `);
        }
    });
}

function scanThreats() {
    Swal.fire({
        title: 'Security Scan',
        text: 'Start a full security scan?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Start Scan'
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.post(APP_URL + '/api/admin.php', { action: 'run_security_scan' }, function(response) {
                hideLoading();
                showToast(response.message || 'Scan complete', 'success');
                setTimeout(() => location.reload(), 2000);
            });
        }
    });
}
</script>

<?php renderAdminFooter(); ?>