<?php
require_once __DIR__ . '/config.php';
requireAuth();

// Paramètres de pagination
$linesPerPage = 50;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $linesPerPage;

// Lire les logs
$logContent = '';
$totalLines = 0;
$reverse = isset($_GET['reverse']) && $_GET['reverse'] === '1';

if (file_exists(LOG_FILE)) {
    $allLines = file(LOG_FILE, FILE_IGNORE_NEW_LINES);
    $totalLines = count($allLines);
    $displayLines = $reverse ? 
        array_slice($allLines, $offset, $linesPerPage) : 
        array_slice(array_reverse($allLines), $offset, $linesPerPage);
    $logContent = implode("\n", $displayLines);
}

// Statistiques simples
$errorCount = 0;
$okCount = 0;
if (file_exists(LOG_FILE)) {
    $logRaw = file_get_contents(LOG_FILE);
    $errorCount = substr_count($logRaw, '[ERREUR]') + substr_count($logRaw, '[🔴');
    $okCount = substr_count($logRaw, '[OK]') + substr_count($logRaw, '[✅');
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>📋 Logs - Monitoring</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
    <link href="style.css" rel="stylesheet">
    <style>
        .log-viewer {
            font-family: 'Monaco', 'Consolas', 'Courier New', monospace;
            font-size: 0.85rem;
            background: #1e1e1e;
            color: #d4d4d4;
            border-radius: 8px;
            padding: 1rem;
            max-height: 60vh;
            overflow-y: auto;
            white-space: pre-wrap;
            word-break: break-all;
        }
        .log-viewer .error { color: #f14c4c; }
        .log-viewer .success { color: #89d185; }
        .log-viewer .warning { color: #cca700; }
        .log-viewer .info { color: #75beff; }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark shadow">
        <div class="container">
            <a class="navbar-brand" href="index.php">
                <i class="bi bi-speedometer2 me-2"></i>Monitoring Neris
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="index.php"><i class="bi bi-arrow-left me-1"></i>Dashboard</a>
                <a class="nav-link text-warning" href="index.php?logout=1"><i class="bi bi-box-arrow-right me-1"></i>Déconnexion</a>
            </div>
        </div>
    </nav>

    <!-- Contenu -->
    <div class="container py-4">
        <div class="card">
            <div class="card-header bg-white d-flex justify-content-between align-items-center flex-wrap gap-2">
                <h5 class="mb-0"><i class="bi bi-journal-text me-2"></i>Logs du monitoring</h5>
                <div class="d-flex gap-2">
                    <a href="?reverse=<?= $reverse ? '0' : '1' ?>&page=1" 
                       class="btn btn-sm btn-outline-secondary">
                        <i class="bi bi-arrow-down-up me-1"></i>
                        <?= $reverse ? 'Plus récents d\'abord' : 'Plus anciens d\'abord' ?>
                    </a>
                    <a href="monitor.log" download class="btn btn-sm btn-outline-primary">
                        <i class="bi bi-download me-1"></i>Télécharger
                    </a>
                </div>
            </div>
            
            <div class="card-body">
                <!-- Stats rapides -->
                <div class="row mb-3">
                    <div class="col-6 col-md-3">
                        <div class="p-2 bg-success bg-opacity-10 rounded text-center">
                            <strong class="text-success"><?= $okCount ?></strong>
                            <div class="small text-muted">Succès</div>
                        </div>
                    </div>
                    <div class="col-6 col-md-3">
                        <div class="p-2 bg-danger bg-opacity-10 rounded text-center">
                            <strong class="text-danger"><?= $errorCount ?></strong>
                            <div class="small text-muted">Erreurs</div>
                        </div>
                    </div>
                    <div class="col-6 col-md-3">
                        <div class="p-2 bg-info bg-opacity-10 rounded text-center">
                            <strong><?= $totalLines ?></strong>
                            <div class="small text-muted">Lignes totales</div>
                        </div>
                    </div>
                    <div class="col-6 col-md-3">
                        <div class="p-2 bg-secondary bg-opacity-10 rounded text-center">
                            <strong><?= ceil($totalLines / $linesPerPage) ?></strong>
                            <div class="small text-muted">Pages</div>
                        </div>
                    </div>
                </div>
                
                <!-- Visionneuse de logs -->
                <?php if (empty($logContent)): ?>
                    <div class="text-center py-5 text-muted">
                        <i class="bi bi-inbox fs-1"></i>
                        <p class="mt-3">Aucun log disponible</p>
                    </div>
                <?php else: ?>
                    <div class="log-viewer"><?php 
                        // Coloration syntaxique basique
                        echo htmlspecialchars($logContent);
                    ?></div>
                <?php endif; ?>
                
                <!-- Pagination -->
                <?php if ($totalLines > $linesPerPage): ?>
                    <nav class="mt-3">
                        <ul class="pagination pagination-sm justify-content-center">
                            <?php 
                            $totalPages = ceil($totalLines / $linesPerPage);
                            for ($p = 1; $p <= $totalPages; $p++):
                                if ($p == 1 || $p == $totalPages || ($p >= $page - 2 && $p <= $page + 2)):
                            ?>
                                <li class="page-item <?= $p === $page ? 'active' : '' ?>">
                                    <a class="page-link" href="?page=<?= $p ?>&reverse=<?= $reverse ? '1' : '0' ?>">
                                        <?= $p ?>
                                    </a>
                                </li>
                            <?php 
                                elseif ($p == $page - 3 || $p == $page + 3):
                            ?>
                                <li class="page-item disabled"><span class="page-link">...</span></li>
                            <?php 
                                endif;
                            endfor; 
                            ?>
                        </ul>
                    </nav>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Bouton pour vider les logs (optionnel - à utiliser avec précaution) -->
        <div class="text-center mt-3">
            <form method="POST" action="clear_logs.php" 
                  onsubmit="return confirm('⚠️ Vraiment supprimer tous les logs ? Cette action est irréversible.');">
                <button type="submit" class="btn btn-sm btn-outline-danger">
                    <i class="bi bi-trash me-1"></i>Vider les logs
                </button>
            </form>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer text-center py-3">
        <div class="container">
            <small>Logs du monitoring • <?= date('d/m/Y H:i') ?></small>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-scroll vers le bas si affichage "plus récents d'abord"
        <?php if (!$reverse): ?>
        document.querySelector('.log-viewer')?.scrollTo({
            top: document.querySelector('.log-viewer')?.scrollHeight,
            behavior: 'auto'
        });
        <?php endif; ?>
    </script>
</body>
</html>