<?php
require_once '../includes/auth.php';
if ($_SESSION['user_role'] !== 'superadmin') {
    header('Location: ../dashboard.php');
    exit;
}
require_once '../config/database.php';
require_once '../includes/functions.php';

$pdo = getPDO();

// Pagination simple
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT) ?: 1;
$limit = 50;
$offset = ($page - 1) * $limit;

$total = $pdo->query("SELECT COUNT(*) FROM logs")->fetchColumn();
$stmt = $pdo->prepare("SELECT l.*, u.nom as user_nom 
                       FROM logs l 
                       LEFT JOIN users u ON l.user_id = u.id 
                       ORDER BY l.created_at DESC 
                       LIMIT ? OFFSET ?");
$stmt->bindValue(1, $limit, PDO::PARAM_INT);
$stmt->bindValue(2, $offset, PDO::PARAM_INT);
$stmt->execute();
$logs = $stmt->fetchAll();

require_once '../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="fas fa-history me-2"></i>Logs d'activité</h1>
    <a href="index.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Retour</a>
</div>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-sm table-striped">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>Utilisateur</th>
                        <th>Action</th>
                        <th>Détails</th>
                        <th>IP</th>
                        <th>Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($logs as $log): ?>
                    <tr>
                        <td><?= $log['id'] ?></td>
                        <td><?= htmlspecialchars($log['user_nom'] ?? 'Système') ?> (ID:<?= $log['user_id'] ?>)</td>
                        <td><?= htmlspecialchars($log['action']) ?></td>
                        <td><?= nl2br(htmlspecialchars($log['details'] ?? '')) ?></td>
                        <td><?= htmlspecialchars($log['ip_address']) ?></td>
                        <td><?= date('d/m/Y H:i:s', strtotime($log['created_at'])) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php if ($total > $limit): ?>
            <nav>
                <ul class="pagination justify-content-center">
                    <?php for ($i = 1; $i <= ceil($total / $limit); $i++): ?>
                        <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                            <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
        <?php endif; ?>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>