<?php
$pageTitle = "Journal d'activité";
require_once __DIR__ . '/includes/header.php';
requireRole(['admin']);
$db = getDB();

$action = $_GET['action'] ?? '';

// Clear all logs
if ($action === 'clear') {
    $db->prepare("DELETE FROM logs")->execute();
    logAction($_SESSION['user_id'], 'logs_clear', "Historique d'activités effacé");
    flash('success', "L'historique d'activités a été entièrement effacé.");
    redirect('/logs.php');
}

$search = $_GET['search'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));

$where = "WHERE 1=1";
$params = [];
if ($search) { $where .= " AND (l.action LIKE ? OR l.details LIKE ? OR u.full_name LIKE ?)"; $s="%$search%"; $params=[$s,$s,$s]; }

$total = $db->prepare("SELECT COUNT(*) FROM logs l LEFT JOIN users u ON l.user_id=u.id $where");
$total->execute($params);
$pagination = paginate($total->fetchColumn(), 30, $page);

$stmt = $db->prepare("SELECT l.*, u.full_name, u.username FROM logs l LEFT JOIN users u ON l.user_id=u.id $where ORDER BY l.created_at DESC LIMIT {$pagination['per_page']} OFFSET {$pagination['offset']}");
$stmt->execute($params);
$logs = $stmt->fetchAll();

$actionIcons = [
    'login'=>'bi-box-arrow-in-right text-success',
    'logout'=>'bi-box-arrow-right text-secondary',
    'voyageur_create'=>'bi-person-plus text-primary',
    'voyageur_update'=>'bi-person-gear text-warning',
    'voyageur_delete'=>'bi-person-x text-danger',
    'programme_create'=>'bi-calendar-plus text-primary',
    'programme_update'=>'bi-calendar-event text-warning',
    'inscription_delete'=>'bi-journal-x text-danger',
    'paiement_create'=>'bi-cash-coin text-success',
    'document_upload'=>'bi-cloud-upload text-info',
    'user_create'=>'bi-person-plus-fill text-primary',
    'user_update'=>'bi-person-fill-gear text-warning',
    'user_delete'=>'bi-person-fill-x text-danger',
];
?>

<div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2">
    <form class="d-flex gap-2" method="GET">
        <div class="input-group" style="width:300px;">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" name="search" class="form-control" placeholder="Rechercher action, utilisateur..." value="<?= sanitize($search) ?>">
        </div>
        <button class="btn btn-outline-primary">Chercher</button>
    </form>
    <a href="<?= APP_URL ?>/logs.php?action=clear" class="btn btn-danger" onclick="return confirmDelete('Êtes-vous sûr de vouloir effacer tout l\'historique d\'activités ? Cette action est irréversible.')"><i class="bi bi-trash me-2"></i>Effacer l'historique</a>
</div>

<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover">
            <thead><tr><th>Date & Heure</th><th>Utilisateur</th><th>Action</th><th>Détails</th><th>IP</th></tr></thead>
            <tbody>
            <?php foreach ($logs as $l): ?>
                <tr>
                    <td><small><?= formatDateTime($l['created_at']) ?></small></td>
                    <td><strong><?= sanitize($l['full_name'] ?? 'Système') ?></strong><br><small class="text-muted"><?= sanitize($l['username'] ?? '') ?></small></td>
                    <td><i class="bi <?= $actionIcons[$l['action']] ?? 'bi-activity text-muted' ?> me-1"></i><?= sanitize($l['action']) ?></td>
                    <td><small><?= sanitize($l['details'] ?: '-') ?></small></td>
                    <td><small class="text-muted"><?= sanitize($l['ip_address'] ?: '-') ?></small></td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($logs)): ?><tr><td colspan="5" class="text-center text-muted py-4">Aucune activité</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card-footer">
        <?= renderPagination($pagination, APP_URL.'/logs.php?search='.urlencode($search)) ?>
        <p class="text-muted small text-center mb-0"><?= $pagination['total'] ?> entrée(s)</p>
    </div>
</div>

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