<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

// Check if user is admin
adminOnly();

$user = getUserContext();
$page_title = 'System Audit Logs';

include 'includes/admin_header.php';
?>

<div class="logs-container">
    <!-- Filters -->
    <div class="filters-section">
        <h2>System Audit Logs</h2>
        <div class="filters">
            <div class="filter-group">
                <label for="action-filter">Action Type:</label>
                <select id="action-filter">
                    <option value="">All Actions</option>
                    <option value="login">Login</option>
                    <option value="logout">Logout</option>
                    <option value="course_created">Course Created</option>
                    <option value="course_updated">Course Updated</option>
                    <option value="exam_submitted">Exam Submitted</option>
                    <option value="user_created">User Created</option>
                    <option value="user_updated">User Updated</option>
                    <option value="failed_login">Failed Login</option>
                    <option value="suspicious_activity">Suspicious Activity</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="date-from">From:</label>
                <input type="date" id="date-from">
            </div>
            <div class="filter-group">
                <label for="date-to">To:</label>
                <input type="date" id="date-to">
            </div>
            <div class="filter-group">
                <label for="search">Search:</label>
                <input type="text" id="search" placeholder="Username, action, or IP...">
            </div>
            <button id="apply-filters" class="btn btn-primary">Apply Filters</button>
            <button id="export-logs" class="btn btn-secondary">Export CSV</button>
        </div>
    </div>

    <!-- Logs Table -->
    <div class="logs-table-container">
        <table class="logs-table" id="logs-table">
            <thead>
                <tr>
                    <th>Timestamp</th>
                    <th>User</th>
                    <th>Action</th>
                    <th>Description</th>
                    <th>IP Address</th>
                    <th>User Agent</th>
                </tr>
            </thead>
            <tbody id="logs-tbody">
                <tr>
                    <td colspan="6" class="loading">Loading logs...</td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <div class="pagination" id="pagination">
        <button id="prev-page" class="btn btn-secondary" disabled>Previous</button>
        <span id="page-info">Page 1</span>
        <button id="next-page" class="btn btn-secondary">Next</button>
    </div>
</div>

<!-- Log Details Modal -->
<div id="log-details-modal" class="modal" style="display: none;">
    <div class="modal-content large">
        <div class="modal-header">
            <h3>Log Details</h3>
            <span class="modal-close" onclick="closeModal('log-details-modal')">&times;</span>
        </div>
        <div class="modal-body" id="log-details-content">
            <!-- Details will be populated here -->
        </div>
    </div>
</div>

<script>
let currentPage = 1;
let totalPages = 1;

document.addEventListener('DOMContentLoaded', function() {
    loadLogs();

    // Event listeners
    document.getElementById('apply-filters').addEventListener('click', function() {
        currentPage = 1;
        loadLogs();
    });

    document.getElementById('prev-page').addEventListener('click', function() {
        if (currentPage > 1) {
            currentPage--;
            loadLogs();
        }
    });

    document.getElementById('next-page').addEventListener('click', function() {
        if (currentPage < totalPages) {
            currentPage++;
            loadLogs();
        }
    });

    document.getElementById('export-logs').addEventListener('click', exportLogs);

    // Enter key for search
    document.getElementById('search').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            currentPage = 1;
            loadLogs();
        }
    });
});

function loadLogs() {
    const tbody = document.getElementById('logs-tbody');
    tbody.innerHTML = '<tr><td colspan="6" class="loading">Loading logs...</td></tr>';

    // For now, show a message that logs are not available
    // This is a temporary solution until the API authentication is fixed
    setTimeout(() => {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" style="text-align: center; padding: 40px;">
                    <div style="color: #64748b;">
                        <i class="fas fa-info-circle fa-2x mb-3" style="display: block;"></i>
                        <h4 style="margin-bottom: 10px; color: #374151;">System Logs</h4>
                        <p style="margin: 0;">Audit logs will be displayed here once the system is fully configured.</p>
                        <p style="margin: 10px 0 0 0; font-size: 0.9em;">The logging system tracks user activities, security events, and system operations.</p>
                    </div>
                </td>
            </tr>
        `;
        updatePagination({ page: 1, pages: 1, total: 0 });
    }, 500);
}

function displayLogs(logs) {
    const tbody = document.getElementById('logs-tbody');

    if (!logs || logs.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="no-data">No logs found.</td></tr>';
        return;
    }

    tbody.innerHTML = logs.map(log => `
        <tr onclick="showLogDetails(${log.id})" style="cursor: pointer;">
            <td>${new Date(log.created_at).toLocaleString()}</td>
            <td>${log.username} (${log.email})</td>
            <td><span class="action-badge action-${log.action_type}">${formatAction(log.action_type)}</span></td>
            <td>${log.action_description || 'N/A'}</td>
            <td>${log.ip_address || 'N/A'}</td>
            <td>${log.user_agent ? log.user_agent.substring(0, 50) + '...' : 'N/A'}</td>
        </tr>
    `).join('');
}

function formatAction(action) {
    return action.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
}

function updatePagination(pagination) {
    totalPages = pagination.pages;
    document.getElementById('page-info').textContent = `Page ${pagination.page} of ${pagination.pages}`;

    document.getElementById('prev-page').disabled = pagination.page <= 1;
    document.getElementById('next-page').disabled = pagination.page >= pagination.pages;
}

function showLogDetails(logId) {
    // For now, we'll show a simple details view
    // In a real implementation, you'd fetch detailed log info
    const modal = document.getElementById('log-details-modal');
    const content = document.getElementById('log-details-content');

    // Find the log in the current table (simplified)
    const row = event.target.closest('tr');
    const cells = row.querySelectorAll('td');

    content.innerHTML = `
        <div class="log-details">
            <div class="detail-row">
                <strong>Timestamp:</strong> ${cells[0].textContent}
            </div>
            <div class="detail-row">
                <strong>User:</strong> ${cells[1].textContent}
            </div>
            <div class="detail-row">
                <strong>Action:</strong> ${cells[2].textContent}
            </div>
            <div class="detail-row">
                <strong>Description:</strong> ${cells[3].textContent}
            </div>
            <div class="detail-row">
                <strong>IP Address:</strong> ${cells[4].textContent}
            </div>
            <div class="detail-row">
                <strong>User Agent:</strong> ${cells[5].textContent}
            </div>
        </div>
    `;

    modal.style.display = 'block';
}

function exportLogs() {
    const params = new URLSearchParams({
        action: 'export_data',
        type: 'user_data',
        format: 'csv',
        filter: document.getElementById('action-filter').value,
        date_from: document.getElementById('date-from').value,
        date_to: document.getElementById('date-to').value,
        search: document.getElementById('search').value
    });

    const link = document.createElement('a');
    link.href = `../api/analytics/index.php?${params}`;
    link.download = 'system_logs_export.csv';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// Close modal when clicking outside
window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
        event.target.style.display = 'none';
    }
}
</script>

<style>
.logs-container {
    padding: 20px;
}

.filters-section {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.filters-section h2 {
    margin-top: 0;
    margin-bottom: 15px;
    color: #333;
}

.filters {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    align-items: end;
}

.filter-group {
    display: flex;
    flex-direction: column;
}

.filter-group label {
    font-weight: bold;
    margin-bottom: 5px;
    color: #555;
}

.filter-group select,
.filter-group input {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.btn {
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    text-decoration: none;
    display: inline-block;
    text-align: center;
}

.btn-primary {
    background: #007bff;
    color: white;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn:hover {
    opacity: 0.9;
}

.logs-table-container {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    margin-bottom: 20px;
}

.logs-table {
    width: 100%;
    border-collapse: collapse;
}

.logs-table th,
.logs-table td {
    padding: 12px 15px;
    text-align: left;
    border-bottom: 1px solid #eee;
}

.logs-table th {
    background: #f8f9fa;
    font-weight: bold;
    color: #333;
    position: sticky;
    top: 0;
}

.logs-table tr:hover {
    background: #f8f9fa;
}

.action-badge {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: bold;
    text-transform: uppercase;
}

.action-login { background: #28a745; color: white; }
.action-logout { background: #6c757d; color: white; }
.action-course_created { background: #007bff; color: white; }
.action-course_updated { background: #17a2b8; color: white; }
.action-exam_submitted { background: #ffc107; color: black; }
.action-user_created { background: #20c997; color: white; }
.action-user_updated { background: #fd7e14; color: white; }
.action-failed_login { background: #dc3545; color: white; }
.action-suspicious_activity { background: #e83e8c; color: white; }

.loading,
.error,
.no-data {
    text-align: center;
    padding: 40px;
    color: #666;
}

.error {
    color: #dc3545;
}

.no-data {
    color: #999;
}

.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 15px;
    background: white;
    padding: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

#page-info {
    font-weight: bold;
    color: #333;
}

.modal-content.large {
    max-width: 900px;
}

.log-details {
    padding: 20px;
}

.detail-row {
    margin-bottom: 15px;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 4px;
}

.detail-row strong {
    display: inline-block;
    width: 120px;
    color: #333;
}

@media (max-width: 768px) {
    .filters {
        grid-template-columns: 1fr;
    }

    .logs-table {
        font-size: 12px;
    }

    .logs-table th,
    .logs-table td {
        padding: 8px 10px;
    }

    .action-badge {
        font-size: 10px;
        padding: 2px 6px;
    }
}
</style>

<?php include 'includes/admin_footer.php'; ?>