<?php
require_once 'config/database.php';
requireAdmin();

require_once 'templates/header.php';
require_once 'templates/navbar.php';
require_once 'templates/sidebar.php';
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Security Monitoring</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item active">Security</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Security Stats -->
            <div class="row">
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-success">
                        <div class="inner">
                            <h3 id="successfulLogins">0</h3>
                            <p>Successful Logins (24h)</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-sign-in-alt"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-warning">
                        <div class="inner">
                            <h3 id="failedLogins">0</h3>
                            <p>Failed Logins (24h)</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-danger">
                        <div class="inner">
                            <h3 id="lockedAccounts">0</h3>
                            <p>Locked Accounts</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-lock"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3 id="activeSessions">0</h3>
                            <p>Active Sessions</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-users"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Security Logs -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Security Event Logs</h3>
                            <div class="card-tools">
                                <div class="input-group input-group-sm" style="width: 300px;">
                                    <select id="severityFilter" class="form-control">
                                        <option value="">All Severities</option>
                                        <option value="low">Low</option>
                                        <option value="medium">Medium</option>
                                        <option value="high">High</option>
                                        <option value="critical">Critical</option>
                                    </select>
                                    <select id="eventTypeFilter" class="form-control ml-2">
                                        <option value="">All Events</option>
                                        <option value="login_attempt">Login Attempt</option>
                                        <option value="login_success">Login Success</option>
                                        <option value="login_failed">Login Failed</option>
                                        <option value="account_locked">Account Locked</option>
                                        <option value="password_reset">Password Reset</option>
                                        <option value="suspicious_activity">Suspicious Activity</option>
                                    </select>
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-default" onclick="loadSecurityLogs()">
                                            <i class="fas fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-body table-responsive p-0">
                            <table class="table table-hover text-nowrap">
                                <thead>
                                    <tr>
                                        <th>Time</th>
                                        <th>Event Type</th>
                                        <th>Admin</th>
                                        <th>IP Address</th>
                                        <th>Severity</th>
                                        <th>Details</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody id="securityLogsTable">
                                    <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                        <div class="card-footer">
                            <div class="row">
                                <div class="col-sm-6">
                                    <div class="dataTables_info" id="securityLogsInfo">
                                        Showing 0 to 0 of 0 entries
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="dataTables_paginate paging_simple_numbers" id="securityLogsPagination">
                                        <!-- Pagination will be populated via JavaScript -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Login Attempts -->
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Recent Login Attempts</h3>
                        </div>
                        <div class="card-body">
                            <canvas id="loginAttemptsChart" height="200"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Security Events by Severity</h3>
                        </div>
                        <div class="card-body">
                            <canvas id="severityChart" height="200"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
let currentPage = 1;
let totalPages = 1;

$(document).ready(function() {
    loadSecurityStats();
    loadSecurityLogs();
    initializeCharts();
    
    // Auto-refresh every 30 seconds
    setInterval(function() {
        loadSecurityStats();
        loadSecurityLogs();
    }, 30000);
});

function loadSecurityStats() {
    $.get('api/system/fetch_security_stats.php', function(response) {
        if (response.success) {
            const stats = response.data;
            $('#successfulLogins').text(stats.successful_logins);
            $('#failedLogins').text(stats.failed_logins);
            $('#lockedAccounts').text(stats.locked_accounts);
            $('#activeSessions').text(stats.active_sessions);
        }
    });
}

function loadSecurityLogs(page = 1) {
    const severity = $('#severityFilter').val();
    const eventType = $('#eventTypeFilter').val();
    
    $.get('api/system/fetch_security_logs.php', {
        limit: 20,
        offset: (page - 1) * 20,
        severity: severity,
        event_type: eventType
    }, function(response) {
        if (response.success) {
            const logs = response.data;
            let html = '';
            
            logs.forEach(function(log) {
                const severityBadge = getSeverityBadge(log.severity);
                const eventTypeBadge = getEventTypeBadge(log.event_type);
                const statusBadge = log.resolved ? 
                    '<span class="badge badge-success">Resolved</span>' : 
                    '<span class="badge badge-warning">Open</span>';
                
                const adminName = log.username ? 
                    `${log.first_name} ${log.last_name} (${log.username})` : 
                    'System';
                
                html += `
                    <tr>
                        <td>${new Date(log.created_at).toLocaleString()}</td>
                        <td>${eventTypeBadge}</td>
                        <td>${adminName}</td>
                        <td>${log.ip_address || 'N/A'}</td>
                        <td>${severityBadge}</td>
                        <td>${log.details || 'N/A'}</td>
                        <td>${statusBadge}</td>
                    </tr>
                `;
            });
            
            $('#securityLogsTable').html(html);
            
            // Update pagination
            currentPage = page;
            totalPages = Math.ceil(response.total / 20);
            updatePagination();
            
            // Update info
            const start = (page - 1) * 20 + 1;
            const end = Math.min(page * 20, response.total);
            $('#securityLogsInfo').text(`Showing ${start} to ${end} of ${response.total} entries`);
        }
    });
}

function getSeverityBadge(severity) {
    const badges = {
        'low': 'badge-secondary',
        'medium': 'badge-warning',
        'high': 'badge-danger',
        'critical': 'badge-dark'
    };
    
    return `<span class="badge ${badges[severity] || 'badge-secondary'}">${severity.toUpperCase()}</span>`;
}

function getEventTypeBadge(eventType) {
    const badges = {
        'login_success': 'badge-success',
        'login_failed': 'badge-danger',
        'login_attempt': 'badge-info',
        'account_locked': 'badge-warning',
        'password_reset': 'badge-primary',
        'suspicious_activity': 'badge-dark'
    };
    
    return `<span class="badge ${badges[eventType] || 'badge-secondary'}">${eventType.replace('_', ' ').toUpperCase()}</span>`;
}

function updatePagination() {
    let html = '';
    
    // Previous button
    html += `<button class="btn btn-sm btn-default ${currentPage === 1 ? 'disabled' : ''}" 
             onclick="loadSecurityLogs(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}>
             <i class="fas fa-chevron-left"></i>
             </button>`;
    
    // Page numbers
    for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
        html += `<button class="btn btn-sm ${i === currentPage ? 'btn-primary' : 'btn-default'}" 
                 onclick="loadSecurityLogs(${i})">${i}</button>`;
    }
    
    // Next button
    html += `<button class="btn btn-sm btn-default ${currentPage === totalPages ? 'disabled' : ''}" 
             onclick="loadSecurityLogs(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''}>
             <i class="fas fa-chevron-right"></i>
             </button>`;
    
    $('#securityLogsPagination').html(html);
}

function initializeCharts() {
    // Login attempts chart
    const loginCtx = document.getElementById('loginAttemptsChart').getContext('2d');
    new Chart(loginCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'Successful',
                data: [],
                borderColor: 'rgb(40, 167, 69)',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                tension: 0.1
            }, {
                label: 'Failed',
                data: [],
                borderColor: 'rgb(220, 53, 69)',
                backgroundColor: 'rgba(220, 53, 69, 0.1)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
    
    // Severity chart
    const severityCtx = document.getElementById('severityChart').getContext('2d');
    new Chart(severityCtx, {
        type: 'doughnut',
        data: {
            labels: ['Low', 'Medium', 'High', 'Critical'],
            datasets: [{
                data: [0, 0, 0, 0],
                backgroundColor: [
                    '#6c757d',
                    '#ffc107',
                    '#dc3545',
                    '#343a40'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
}
</script>

<?php require_once 'templates/footer.php'; ?>
