<?php

declare(strict_types=1);

require_once __DIR__ . '/../core/web_bootstrap.php';
require_once __DIR__ . '/../core/permissions.php';

/* SESSION CHECK */
if (empty($_SESSION['user']) || empty($_SESSION['api_token'])) {
    header('Location: login.php');
    exit;
}

$user = $_SESSION['user'];

if (!can($user, 'admin_audit', 'view', $pdo)) {
    http_response_code(403);
    die('Access denied.');
}

?>

<?php require 'partials/header.php'; ?>
<?php require 'partials/nav.php'; ?>

<h3>Admin Action Audit Log</h3>

<table class="table table-bordered table-sm">
<thead>
<tr>
<th>Date</th>
<th>User</th>
<th>Role</th>
<th>Module</th>
<th>Action</th>
<th>Record</th>
<th>IP</th>
</tr>
</thead>
<tbody id="auditTable"></tbody>
</table>

<script>
const token = '<?= htmlspecialchars($_SESSION['api_token'], ENT_QUOTES, 'UTF-8') ?>';

function escapeHtml(text) {
    if (!text) return '';
    return text
        .toString()
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

function loadAudit() {

    fetch('/api/admin/get_admin_audit.php', {
        headers: { 'Authorization': 'Bearer ' + token }
    })
    .then(res => res.json())
    .then(data => {

        if (!data.success) return alert(data.message);

        let rows = '';
        const logs = data.data.logs || [];

        logs.forEach(log => {

            rows += `
                <tr>
                    <td>${escapeHtml(log.created_at)}</td>
                    <td>${escapeHtml(log.full_name)}</td>
                    <td>${escapeHtml(log.role_key)}</td>
                    <td>${escapeHtml(log.module_key)}</td>
                    <td>${escapeHtml(log.action_type)}</td>
                    <td>${escapeHtml(log.record_id ?? '-')}</td>
                    <td>${escapeHtml(log.ip_address)}</td>
                </tr>
            `;
        });

        document.getElementById('auditTable').innerHTML = rows;
    });
}

loadAudit();
</script>

<?php require 'partials/footer.php'; ?>