<?php
require_once __DIR__ . '/header.php';
perms_require('view_audit');
$user = current_user();
$isSuper = perms_is_super($user);

$page  = max(1, v_int($_GET['p'] ?? 1, 1, 99999, 1));
$per   = 50;
$off   = ($page - 1) * $per;

$evt   = v_clean_string($_GET['event'] ?? '', 50);
$uid   = v_int($_GET['user_id'] ?? 0, 0);

$where  = [];
$params = [];
if ($evt !== '') { $where[] = 'l.event_type = ?'; $params[] = $evt; }
if ($uid > 0)    { $where[] = 'l.user_id = ?';    $params[] = $uid; }

// Coordinator: only see events triggered by users in their facility (or 'system' events with null user_id).
if (!$isSuper && $user['facility_id']) {
    $where[]  = '(l.user_id IS NULL OR EXISTS (SELECT 1 FROM users u2 WHERE u2.id = l.user_id AND u2.facility_id = ?))';
    $params[] = (int)$user['facility_id'];
}

$whereSql = $where ? ' WHERE ' . implode(' AND ', $where) : '';

$total = $pdo->prepare("SELECT COUNT(*) AS c FROM osce_logs l LEFT JOIN users u ON u.id = l.user_id $whereSql");
$total->execute($params);
$total = (int)$total->fetch()['c'];

$stmt = $pdo->prepare("SELECT l.*, u.username FROM osce_logs l LEFT JOIN users u ON u.id = l.user_id $whereSql ORDER BY l.id DESC LIMIT $per OFFSET $off");
$stmt->execute($params);
$rows = $stmt->fetchAll();

$events = $pdo->query("SELECT DISTINCT event_type FROM osce_logs WHERE event_type IS NOT NULL ORDER BY event_type")->fetchAll();
?>
<h2>Audit Log <small class="muted">(<?php echo $total; ?> entries)</small></h2>

<form method="get" class="mb-2">
    <div class="form-row">
        <div class="field"><label>Event</label>
            <select name="event">
                <option value="">All</option>
                <?php foreach ($events as $e): ?>
                    <option value="<?php echo h($e['event_type']); ?>" <?php if ($evt===$e['event_type']) echo 'selected'; ?>><?php echo h($e['event_type']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="field"><label>User ID</label><input type="number" name="user_id" value="<?php echo $uid>0 ? (int)$uid : ''; ?>"></div>
    </div>
    <button type="submit" class="btn">Filter</button>
    <a href="audit_log.php" class="btn">Clear</a>
</form>

<div class="table-wrap">
<table class="data">
    <thead><tr><th>ID</th><th>When</th><th>Event</th><th>User</th><th>Role</th><th>Detail</th></tr></thead>
    <tbody>
    <?php foreach ($rows as $r): ?>
        <tr>
            <td data-label="ID"><?php echo (int)$r['id']; ?></td>
            <td data-label="When"><?php echo h($r['created_at']); ?></td>
            <td data-label="Event"><?php echo h($r['event_type']); ?></td>
            <td data-label="User"><?php echo h($r['username'] ?? '(system)'); ?> <small class="muted">#<?php echo (int)$r['user_id']; ?></small></td>
            <td data-label="Role"><?php echo h($r['user_role']); ?></td>
            <td data-label="Detail"><pre style="white-space:pre-wrap;font-size:12px;margin:0;"><?php echo h($r['message']); ?></pre></td>
        </tr>
    <?php endforeach; ?>
    <?php if (!$rows): ?><tr><td colspan="6" class="muted">No log entries match.</td></tr><?php endif; ?>
    </tbody>
</table>
</div>

<?php
$pages = max(1, (int)ceil($total / $per));
if ($pages > 1):
    $qs = $_GET; ?>
<p class="mt-2 flex">
    <?php for ($i = 1; $i <= $pages; $i++):
        $qs['p'] = $i;
        $url = 'audit_log.php?' . http_build_query($qs);
        ?>
        <a href="<?php echo h($url); ?>" class="btn btn-sm <?php if ($i===$page) echo 'btn-primary'; ?>"><?php echo $i; ?></a>
    <?php endfor; ?>
</p>
<?php endif; ?>

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