<?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">Audit Logs</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">Audit Logs</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <!-- Filters -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Filter Logs</h3>
                        </div>
                        <div class="card-body">
                            <form id="filterForm">
                                <div class="row">
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>Date Range</label>
                                            <select class="form-control" id="dateRange">
                                                <option value="today">Today</option>
                                                <option value="yesterday">Yesterday</option>
                                                <option value="last_7_days">Last 7 Days</option>
                                                <option value="last_30_days">Last 30 Days</option>
                                                <option value="custom">Custom Range</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>From Date</label>
                                            <input type="date" class="form-control" id="fromDate">
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>To Date</label>
                                            <input type="date" class="form-control" id="toDate">
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>Action Type</label>
                                            <select class="form-control" id="actionType">
                                                <option value="">All Actions</option>
                                                <option value="login">Login</option>
                                                <option value="logout">Logout</option>
                                                <option value="create">Create</option>
                                                <option value="update">Update</option>
                                                <option value="delete">Delete</option>
                                                <option value="view">View</option>
                                                <option value="export">Export</option>
                                                <option value="backup">Backup</option>
                                                <option value="restore">Restore</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>User</label>
                                            <select class="form-control" id="userId">
                                                <option value="">All Users</option>
                                                <!-- Will be populated dynamically -->
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>IP Address</label>
                                            <input type="text" class="form-control" id="ipAddress" placeholder="IP Address">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <button type="button" class="btn btn-primary" onclick="loadLogs()">
                                            <i class="fas fa-filter"></i> Apply Filters
                                        </button>
                                        <button type="button" class="btn btn-secondary" onclick="clearFilters()">
                                            <i class="fas fa-times"></i> Clear Filters
                                        </button>
                                        <button type="button" class="btn btn-success" onclick="exportLogs()">
                                            <i class="fas fa-download"></i> Export Logs
                                        </button>
                                        <button type="button" class="btn btn-danger" onclick="clearOldLogs()">
                                            <i class="fas fa-trash"></i> Clear Old Logs
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Logs Table -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Audit Logs</h3>
                            <div class="card-tools">
                                <div class="input-group input-group-sm" style="width: 150px;">
                                    <input type="text" id="searchLogs" class="form-control" placeholder="Search logs...">
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-default">
                                            <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" id="auditLogsTable">
                                <thead>
                                    <tr>
                                        <th>Timestamp</th>
                                        <th>User</th>
                                        <th>Action</th>
                                        <th>Module</th>
                                        <th>Description</th>
                                        <th>IP Address</th>
                                        <th>User Agent</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Logs will be populated here -->
                                </tbody>
                            </table>
                        </div>
                        <div class="card-footer">
                            <div class="row">
                                <div class="col-sm-5">
                                    <div class="dataTables_info" id="logsInfo">
                                        <!-- Info will be populated here -->
                                    </div>
                                </div>
                                <div class="col-sm-7">
                                    <div class="dataTables_paginate paging_simple_numbers" id="logsPagination">
                                        <!-- Pagination will be populated here -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div class="row">
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3 id="totalLogsToday">0</h3>
                            <p>Today's Activities</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-clock"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-success">
                        <div class="inner">
                            <h3 id="totalLoginsToday">0</h3>
                            <p>Today's Logins</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="totalFailedLogins">0</h3>
                            <p>Failed Login Attempts</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="totalSecurityAlerts">0</h3>
                            <p>Security Alerts</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-shield-alt"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Activity Chart -->
            <div class="row">
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Activity Timeline</h3>
                        </div>
                        <div class="card-body">
                            <canvas id="activityChart" style="height: 300px;"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Action Types Distribution</h3>
                        </div>
                        <div class="card-body">
                            <canvas id="actionChart" style="height: 300px;"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Log Details Modal -->
<div class="modal fade" id="logDetailsModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Log Details</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div id="logDetailsContent">
                    <!-- Log details will be populated here -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Clear Logs Modal -->
<div class="modal fade" id="clearLogsModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Clear Old Logs</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <p>This will permanently delete old audit logs. This action cannot be undone.</p>
                <div class="form-group">
                    <label>Clear logs older than:</label>
                    <select class="form-control" id="clearLogsOlderThan">
                        <option value="30">30 days</option>
                        <option value="90">90 days</option>
                        <option value="180">6 months</option>
                        <option value="365">1 year</option>
                    </select>
                </div>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i>
                    <strong>Warning:</strong> This action cannot be undone. Make sure you have exported important logs before clearing.
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" onclick="confirmClearLogs()">Clear Logs</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

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

$(document).ready(function() {
    loadUsers();
    loadLogs();
    loadStatistics();
    loadActivityChart();
    loadActionChart();
    
    // Search functionality
    $('#searchLogs').on('input', function() {
        loadLogs();
    });
    
    // Date range change
    $('#dateRange').on('change', function() {
        const range = $(this).val();
        if (range === 'custom') {
            $('#fromDate, #toDate').prop('disabled', false);
        } else {
            $('#fromDate, #toDate').prop('disabled', true);
            setDateRange(range);
        }
    });
    
    // Set initial date range
    setDateRange('today');
});

function setDateRange(range) {
    const today = new Date();
    const fromDate = new Date();
    
    switch(range) {
        case 'today':
            fromDate.setDate(today.getDate());
            break;
        case 'yesterday':
            fromDate.setDate(today.getDate() - 1);
            today.setDate(today.getDate() - 1);
            break;
        case 'last_7_days':
            fromDate.setDate(today.getDate() - 7);
            break;
        case 'last_30_days':
            fromDate.setDate(today.getDate() - 30);
            break;
    }
    
    $('#fromDate').val(fromDate.toISOString().split('T')[0]);
    $('#toDate').val(today.toISOString().split('T')[0]);
}

function loadUsers() {
    $.ajax({
        url: 'api/fetch_admin_users.php',
        type: 'GET',
        success: function(response) {
            if (response.success) {
                let options = '<option value="">All Users</option>';
                response.users.forEach(function(user) {
                    options += `<option value="${user.id}">${user.username}</option>`;
                });
                $('#userId').html(options);
            }
        }
    });
}

function loadLogs() {
    const filters = {
        search: $('#searchLogs').val(),
        from_date: $('#fromDate').val(),
        to_date: $('#toDate').val(),
        action_type: $('#actionType').val(),
        user_id: $('#userId').val(),
        ip_address: $('#ipAddress').val(),
        page: currentPage
    };
    
    $.ajax({
        url: 'api/fetch_audit_logs.php',
        type: 'GET',
        data: filters,
        success: function(response) {
            if (response.success) {
                let html = '';
                response.logs.forEach(function(log) {
                    const statusClass = log.status === 'success' ? 'success' : 'danger';
                    const actionClass = getActionClass(log.action);
                    
                    html += `
                        <tr>
                            <td>${formatDateTime(log.timestamp)}</td>
                            <td>${log.username || 'System'}</td>
                            <td>
                                <span class="badge badge-${actionClass}">${log.action}</span>
                            </td>
                            <td>${log.module || 'System'}</td>
                            <td>${log.description}</td>
                            <td>${log.ip_address}</td>
                            <td title="${log.user_agent}">${truncateText(log.user_agent, 20)}</td>
                            <td>
                                <span class="badge badge-${statusClass}">${log.status}</span>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-outline-info" onclick="viewLogDetails(${log.id})">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </td>
                        </tr>
                    `;
                });
                
                $('#auditLogsTable tbody').html(html);
                
                // Update pagination
                totalPages = response.totalPages;
                updatePagination();
                updateInfo(response.totalRecords, response.filteredRecords);
            }
        }
    });
}

function loadStatistics() {
    $.ajax({
        url: 'api/fetch_audit_statistics.php',
        type: 'GET',
        success: function(response) {
            if (response.success) {
                $('#totalLogsToday').text(response.stats.today_activities);
                $('#totalLoginsToday').text(response.stats.today_logins);
                $('#totalFailedLogins').text(response.stats.failed_logins);
                $('#totalSecurityAlerts').text(response.stats.security_alerts);
            }
        }
    });
}

function loadActivityChart() {
    $.ajax({
        url: 'api/fetch_activity_chart.php',
        type: 'GET',
        success: function(response) {
            if (response.success) {
                const ctx = document.getElementById('activityChart').getContext('2d');
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: response.labels,
                        datasets: [{
                            label: 'Activities',
                            data: response.data,
                            borderColor: 'rgb(75, 192, 192)',
                            backgroundColor: 'rgba(75, 192, 192, 0.2)',
                            tension: 0.1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            }
        }
    });
}

function loadActionChart() {
    $.ajax({
        url: 'api/fetch_action_chart.php',
        type: 'GET',
        success: function(response) {
            if (response.success) {
                const ctx = document.getElementById('actionChart').getContext('2d');
                new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: response.labels,
                        datasets: [{
                            data: response.data,
                            backgroundColor: [
                                '#FF6384',
                                '#36A2EB',
                                '#FFCE56',
                                '#4BC0C0',
                                '#9966FF',
                                '#FF9F40'
                            ]
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            }
        }
    });
}

function viewLogDetails(logId) {
    $.ajax({
        url: 'api/fetch_log_details.php',
        type: 'GET',
        data: { id: logId },
        success: function(response) {
            if (response.success) {
                const log = response.log;
                let html = `
                    <div class="row">
                        <div class="col-md-6">
                            <strong>Timestamp:</strong> ${formatDateTime(log.timestamp)}
                        </div>
                        <div class="col-md-6">
                            <strong>User:</strong> ${log.username || 'System'}
                        </div>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-md-6">
                            <strong>Action:</strong> ${log.action}
                        </div>
                        <div class="col-md-6">
                            <strong>Module:</strong> ${log.module || 'System'}
                        </div>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-md-6">
                            <strong>IP Address:</strong> ${log.ip_address}
                        </div>
                        <div class="col-md-6">
                            <strong>Status:</strong> <span class="badge badge-${log.status === 'success' ? 'success' : 'danger'}">${log.status}</span>
                        </div>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-md-12">
                            <strong>Description:</strong><br>
                            ${log.description}
                        </div>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-md-12">
                            <strong>User Agent:</strong><br>
                            <small>${log.user_agent}</small>
                        </div>
                    </div>
                `;
                
                if (log.additional_data) {
                    html += `
                        <hr>
                        <div class="row">
                            <div class="col-md-12">
                                <strong>Additional Data:</strong><br>
                                <pre>${JSON.stringify(JSON.parse(log.additional_data), null, 2)}</pre>
                            </div>
                        </div>
                    `;
                }
                
                $('#logDetailsContent').html(html);
                $('#logDetailsModal').modal('show');
            }
        }
    });
}

function clearFilters() {
    $('#searchLogs').val('');
    $('#dateRange').val('today');
    $('#actionType').val('');
    $('#userId').val('');
    $('#ipAddress').val('');
    setDateRange('today');
    loadLogs();
}

function exportLogs() {
    const filters = {
        search: $('#searchLogs').val(),
        from_date: $('#fromDate').val(),
        to_date: $('#toDate').val(),
        action_type: $('#actionType').val(),
        user_id: $('#userId').val(),
        ip_address: $('#ipAddress').val()
    };
    
    window.location.href = 'api/export_audit_logs.php?' + $.param(filters);
}

function clearOldLogs() {
    $('#clearLogsModal').modal('show');
}

function confirmClearLogs() {
    const days = $('#clearLogsOlderThan').val();
    
    $.ajax({
        url: 'api/clear_old_logs.php',
        type: 'POST',
        data: { days: days },
        success: function(response) {
            if (response.success) {
                toastr.success('Old logs cleared successfully');
                $('#clearLogsModal').modal('hide');
                loadLogs();
                loadStatistics();
            } else {
                toastr.error(response.message);
            }
        }
    });
}

function getActionClass(action) {
    const actionClasses = {
        'login': 'success',
        'logout': 'info',
        'create': 'primary',
        'update': 'warning',
        'delete': 'danger',
        'view': 'secondary',
        'export': 'info',
        'backup': 'dark',
        'restore': 'primary'
    };
    
    return actionClasses[action] || 'secondary';
}

function formatDateTime(timestamp) {
    const date = new Date(timestamp);
    return date.toLocaleString();
}

function truncateText(text, maxLength) {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
}

function updatePagination() {
    let html = '';
    
    // Previous button
    if (currentPage > 1) {
        html += `<button class="btn btn-sm btn-outline-primary" onclick="changePage(${currentPage - 1})">Previous</button>`;
    }
    
    // Page numbers
    for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
        const activeClass = i === currentPage ? 'btn-primary' : 'btn-outline-primary';
        html += `<button class="btn btn-sm ${activeClass}" onclick="changePage(${i})">${i}</button>`;
    }
    
    // Next button
    if (currentPage < totalPages) {
        html += `<button class="btn btn-sm btn-outline-primary" onclick="changePage(${currentPage + 1})">Next</button>`;
    }
    
    $('#logsPagination').html(html);
}

function updateInfo(totalRecords, filteredRecords) {
    const start = (currentPage - 1) * 50 + 1;
    const end = Math.min(currentPage * 50, filteredRecords);
    $('#logsInfo').text(`Showing ${start} to ${end} of ${filteredRecords} entries (filtered from ${totalRecords} total entries)`);
}

function changePage(page) {
    currentPage = page;
    loadLogs();
}
</script>

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