<?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'];

/* RBAC CHECK */
if (!can($user, 'permissions_audit', 'view', $pdo)) {
    http_response_code(403);
    die('Access denied.');
}

/* FETCH DATA */
$stmt = $pdo->prepare("
    SELECT 
        p.*,
        u.first_name,
        u.last_name
    FROM permission_audit_logs p
    JOIN users u ON u.id = p.changed_by_user_id
    ORDER BY p.created_at DESC
    LIMIT 100
");

$stmt->execute();
$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

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

<h3>Permission Change Audit Log</h3>

<table class="table table-bordered table-sm">
<thead>
<tr>
<th>Date</th>
<th>Changed By</th>
<th>Role</th>
<th>Module</th>
<th>Old</th>
<th>New</th>
<th>IP</th>
</tr>
</thead>
<tbody>
<?php foreach ($logs as $log): ?>
<tr>
<td><?= htmlspecialchars($log['created_at']) ?></td>
<td><?= htmlspecialchars($log['first_name'].' '.$log['last_name']) ?></td>
<td><?= htmlspecialchars($log['role_key']) ?></td>
<td><?= htmlspecialchars($log['module_key']) ?></td>
<td>
V:<?= (int)$log['old_view'] ?>
C:<?= (int)$log['old_create'] ?>
E:<?= (int)$log['old_edit'] ?>
D:<?= (int)$log['old_delete'] ?>
</td>
<td>
V:<?= (int)$log['new_view'] ?>
C:<?= (int)$log['new_create'] ?>
E:<?= (int)$log['new_edit'] ?>
D:<?= (int)$log['new_delete'] ?>
</td>
<td><?= htmlspecialchars($log['ip_address']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

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