<?php
/**
 * admin/audit-trail.php - System Audit Trail & Activity Logs
 */

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

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

$breadcrumbs = [['title' => 'Audit Trail', 'url' => '']];

renderAdminHeader('Audit Trail', $breadcrumbs);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold"><i class="bi bi-journal-check me-2"></i>Audit Trail</h2>
        <p class="text-muted mb-0">Complete system activity log and audit history</p>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#filterModal">
            <i class="bi bi-funnel me-2"></i>Filter
        </button>
        <button class="btn btn-primary" onclick="exportAuditLog()">
            <i class="bi bi-download me-2"></i>Export
        </button>
    </div>
</div>

<!-- Statistics -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h3 class="fw-bold mb-1" id="total_events">0</h3>
                <small class="text-muted">Total Events</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h3 class="fw-bold mb-1 text-success" id="success_events">0</h3>
                <small class="text-muted">Successful</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h3 class="fw-bold mb-1 text-danger" id="failed_events">0</h3>
                <small class="text-muted">Failed</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h3 class="fw-bold mb-1 text-info" id="unique_users">0</h3>
                <small class="text-muted">Unique Users</small>
            </div>
        </div>
    </div>
</div>

<!-- Audit Log Table -->
<div class="card border-0 shadow-sm">
    <div class="card-body">
        <table class="table table-hover" id="auditTable">
            <thead>
                <tr>
                    <th>Timestamp</th>
                    <th>Event Type</th>
                    <th>User</th>
                    <th>Entity</th>
                    <th>Action</th>
                    <th>IP Address</th>
                    <th>Details</th>
                </tr>
            </thead>
            <tbody>
                <tr><td colspan="7" class="text-center py-5"><div class="spinner-border"></div></td></tr>
            </tbody>
        </table>
    </div>
</div>

<!-- Filter Modal -->
<div class="modal fade" id="filterModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Filter Audit Log</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Event Type</label>
                    <select class="form-select" id="filter_event_type">
                        <option value="">All Events</option>
                        <option value="create">Create</option>
                        <option value="update">Update</option>
                        <option value="delete">Delete</option>
                        <option value="login">Login</option>
                        <option value="logout">Logout</option>
                        <option value="access">Access</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">User</label>
                    <input type="text" class="form-control" id="filter_user" placeholder="Search by user name">
                </div>
                <div class="mb-3">
                    <label class="form-label">Entity Type</label>
                    <select class="form-select" id="filter_entity">
                        <option value="">All Entities</option>
                        <option value="users">Users</option>
                        <option value="products">Products</option>
                        <option value="orders">Orders</option>
                        <option value="settings">Settings</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Date Range</label>
                    <input type="date" class="form-control mb-2" id="filter_date_from">
                    <input type="date" class="form-control" id="filter_date_to">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="clearFilters()">Clear</button>
                <button type="button" class="btn btn-primary" onclick="applyFilters()">Apply</button>
            </div>
        </div>
    </div>
</div>

<!-- Details Modal -->
<div class="modal fade" id="detailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Event Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="eventDetails"></div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    loadAuditLog();
    loadStats();
});

function loadAuditLog(filters = {}) {
    $.get(APP_URL + '/api/admin.php', {...filters, action: 'get_audit_log'}, function(response) {
        if (response.success && response.data.length > 0) {
            let html = '';
            response.data.forEach(log => {
                const statusClass = log.status === 'success' ? 'success' : 'danger';
                html += `
                    <tr>
                        <td><small>${log.created_at}</small></td>
                        <td><span class="badge bg-${statusClass}">${log.event_type}</span></td>
                        <td>${log.user_name || 'System'}<br><small class="text-muted">${log.user_type || ''}</small></td>
                        <td><span class="badge bg-secondary">${log.entity_type}</span><br><small>#${log.entity_id || 'N/A'}</small></td>
                        <td>${log.action_description}</td>
                        <td><code>${log.ip_address || 'N/A'}</code></td>
                        <td><button class="btn btn-sm btn-outline-primary" onclick="viewDetails(${log.id})"><i class="bi bi-eye"></i></button></td>
                    </tr>
                `;
            });
            $('#auditTable tbody').html(html);
        } else {
            $('#auditTable tbody').html('<tr><td colspan="7" class="text-center py-5">No audit logs found</td></tr>');
        }
    });
}

function loadStats() {
    $.get(APP_URL + '/api/admin.php?action=get_audit_stats', function(response) {
        if (response.success) {
            $('#total_events').text(response.data.total);
            $('#success_events').text(response.data.success);
            $('#failed_events').text(response.data.failed);
            $('#unique_users').text(response.data.unique_users);
        }
    });
}

function viewDetails(logId) {
    $.get(APP_URL + '/api/admin.php?action=get_audit_details&log_id=' + logId, function(response) {
        if (response.success) {
            const log = response.data;
            $('#eventDetails').html(`
                <table class="table">
                    <tr><td><strong>Event ID:</strong></td><td>#${log.id}</td></tr>
                    <tr><td><strong>Type:</strong></td><td>${log.event_type}</td></tr>
                    <tr><td><strong>User:</strong></td><td>${log.user_name} (${log.user_type})</td></tr>
                    <tr><td><strong>Entity:</strong></td><td>${log.entity_type} #${log.entity_id}</td></tr>
                    <tr><td><strong>IP Address:</strong></td><td>${log.ip_address}</td></tr>
                    <tr><td><strong>Timestamp:</strong></td><td>${log.created_at}</td></tr>
                    <tr><td><strong>User Agent:</strong></td><td><small>${log.user_agent || 'N/A'}</small></td></tr>
                    ${log.old_data ? '<tr><td><strong>Old Data:</strong></td><td><pre>' + JSON.stringify(JSON.parse(log.old_data), null, 2) + '</pre></td></tr>' : ''}
                    ${log.new_data ? '<tr><td><strong>New Data:</strong></td><td><pre>' + JSON.stringify(JSON.parse(log.new_data), null, 2) + '</pre></td></tr>' : ''}
                </table>
            `);
            $('#detailsModal').modal('show');
        }
    });
}

function applyFilters() {
    const filters = {
        event_type: $('#filter_event_type').val(),
        user: $('#filter_user').val(),
        entity_type: $('#filter_entity').val(),
        date_from: $('#filter_date_from').val(),
        date_to: $('#filter_date_to').val()
    };
    $('#filterModal').modal('hide');
    loadAuditLog(filters);
}

function clearFilters() {
    $('#filter_event_type, #filter_user, #filter_entity, #filter_date_from, #filter_date_to').val('');
}

function exportAuditLog() {
    window.location.href = APP_URL + '/admin/export-audit-log.php';
}
</script>

<?php renderAdminFooter(); ?>