<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/settings_permissions.php';

auth_require_login();
$pdo = crm_pdo();

if (!gp_can_access_settings($pdo)) {
    http_response_code(403);
    die('Access denied.');
}

$page_title = 'System Logs';

$limit = 100;
$stmt = $pdo->prepare("
    SELECT l.*, u.username 
    FROM system_logs l
    LEFT JOIN users u ON u.id = l.user_id
    ORDER BY l.created_at DESC
    LIMIT ?
");
$stmt->bindValue(1, $limit, PDO::PARAM_INT);
$stmt->execute();
$logs = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>System Logs</h1>
    <span>Audit trail & security monitor</span>
  </div>
</div>

<div class="card">
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>Date/Time</th>
                    <th>User</th>
                    <th>IP Address</th>
                    <th>Action</th>
                    <th>Entity</th>
                    <th>Details</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($logs as $log): ?>
                <tr>
                    <td style="white-space:nowrap;font-size:0.85rem;color:var(--gp-muted);"><?php echo h(gp_date($log['created_at'], true)); ?></td>
                    <td><span class="badge"><?php echo h($log['username'] ?: 'System/Guest'); ?></span></td>
                    <td style="font-family:monospace;"><?php echo h($log['ip_address']); ?></td>
                    <td><strong style="color:var(--gp-primary);"><?php echo h($log['action_type']); ?></strong></td>
                    <td>
                        <?php if ($log['entity_type']): ?>
                            <span style="font-size:0.8rem;text-transform:uppercase;color:var(--gp-muted);"><?php echo h($log['entity_type']); ?></span>
                            #<?php echo (int)$log['entity_id']; ?>
                        <?php else: ?>
                            -
                        <?php endif; ?>
                    </td>
                    <td style="font-size:0.9rem;"><?php echo h($log['details']); ?></td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($logs)): ?>
                <tr><td colspan="6" style="text-align:center;">No logs recorded yet.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
