<?php
/**
 * 🚀 Lance le script de monitoring manuellement depuis l'interface web
 * Utile pour tester sans attendre le Cron
 * 
 * Sécurité : 
 * - Vérification du chemin du script
 * - Échappement des arguments shell
 * - Timeout d'exécution
 */
require_once __DIR__ . '/config.php';
requireAuth();

// 🔐 Validation du chemin du script (prévention path traversal)
$allowedBase = realpath(BASE_DIR);
$scriptPath = realpath(MONITOR_SCRIPT);

if (!$scriptPath || strpos($scriptPath, $allowedBase) !== 0 || !file_exists($scriptPath)) {
    error_log("[" . date('Y-m-d H:i:s') . "] Tentative d'exécution de script invalide : $MONITOR_SCRIPT");
    die("❌ Erreur de configuration : script de monitoring introuvable ou accès non autorisé.");
}

// ⏱️ Limiter le temps d'exécution max (60 secondes)
set_time_limit(60);

// 📦 Exécuter le script et capturer la sortie
$output = [];
$returnCode = 0;

// ✅ Commande sécurisée avec escapeshellarg
$phpPath = '/usr/local/bin/php'; // Doit correspondre à votre configuration
$command = sprintf('%s %s 2>&1', escapeshellcmd($phpPath), escapeshellarg($scriptPath));

// Exécution avec capture
exec($command, $output, $returnCode);
$outputText = implode("\n", $output);

// 📊 Parser les statistiques depuis la sortie (plus robuste que substr_count)
$stats = [
    'total' => 0,
    'ok' => 0,
    'blocked' => 0,
    'errors' => 0,
    'telegram_sent' => 0,
];

foreach ($output as $line) {
    if (preg_match('/\[✅ OK\]/', $line)) $stats['ok']++;
    if (preg_match('/\[⚠️ BLOQUÉ\]/', $line)) $stats['blocked']++;
    if (preg_match('/\[🔴 ERREUR\]/', $line)) $stats['errors']++;
    if (preg_match('/📱 Alert Telegram envoyée/', $line)) $stats['telegram_sent']++;
}
$stats['total'] = $stats['ok'] + $stats['blocked'] + $stats['errors'];

// 🎨 Déterminer la couleur d'alerte selon le résultat
$alertType = $returnCode !== 0 && $stats['errors'] > 0 ? 'danger' : 'success';
$alertIcon = $alertType === 'danger' ? '🔴' : '✅';
$alertMessage = $returnCode !== 0 
    ? "Le script s'est terminé avec des erreurs (code: $returnCode)" 
    : "Exécution terminée avec succès";
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🚀 Exécution - 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">
</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-play-circle me-2"></i>Résultat de l'exécution</h5>
                <div>
                    <span class="badge bg-<?= $alertType ?> me-2">
                        <?= $alertIcon ?> <?= htmlspecialchars($alertMessage) ?>
                    </span>
                    <span class="badge bg-secondary">
                        <?= date('d/m/Y H:i:s') ?>
                    </span>
                </div>
            </div>
            <div class="card-body">
                
                <!-- Message d'erreur si exec a échoué -->
                <?php if ($returnCode !== 0 && empty($outputText)): ?>
                    <div class="alert alert-danger alert-custom">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        <strong>Erreur d'exécution :</strong> Le script n'a produit aucune sortie. 
                        Vérifiez les permissions et les logs serveur.
                    </div>
                <?php endif; ?>
                
                <!-- Statistiques -->
                <div class="row text-center mb-4">
                    <div class="col-6 col-md-3">
                        <div class="p-3 bg-primary bg-opacity-10 rounded">
                            <h3 class="text-primary mb-0"><?= $stats['total'] ?></h3>
                            <small class="text-muted">Sites vérifiés</small>
                        </div>
                    </div>
                    <div class="col-6 col-md-3">
                        <div class="p-3 bg-success bg-opacity-10 rounded">
                            <h3 class="text-success mb-0"><?= $stats['ok'] ?></h3>
                            <small class="text-muted">✅ En ligne</small>
                        </div>
                    </div>
                    <div class="col-6 col-md-3">
                        <div class="p-3 bg-warning bg-opacity-10 rounded">
                            <h3 class="text-warning mb-0"><?= $stats['blocked'] ?></h3>
                            <small class="text-muted">⚠️ Bloqués</small>
                        </div>
                    </div>
                    <div class="col-6 col-md-3">
                        <div class="p-3 bg-danger bg-opacity-10 rounded">
                            <h3 class="text-danger mb-0"><?= $stats['errors'] ?></h3>
                            <small class="text-muted">🔴 En erreur</small>
                        </div>
                    </div>
                </div>
                
                <!-- Notification Telegram -->
                <?php if ($stats['telegram_sent'] > 0): ?>
                <div class="alert alert-info alert-custom mb-4">
                    <i class="bi bi-telegram me-2"></i>
                    <strong><?= $stats['telegram_sent'] ?> alerte(s) Telegram envoyée(s)</strong>
                </div>
                <?php endif; ?>
                
                <!-- Sortie brute (scrollable) -->
                <h6 class="mb-2"><i class="bi bi-terminal me-1"></i>Sortie du script :</h6>
                <?php if (empty($outputText)): ?>
                    <div class="alert alert-secondary small">
                        <i class="bi bi-info-circle me-1"></i>Aucune sortie à afficher.
                    </div>
                <?php else: ?>
                    <pre class="bg-light p-3 rounded small border" style="max-height: 50vh; overflow-y: auto; font-size: 0.8rem;">
<?php echo htmlspecialchars($outputText); ?>
                    </pre>
                <?php endif; ?>
                
                <!-- Actions -->
                <div class="d-flex gap-2 mt-4 flex-wrap">
                    <a href="index.php" class="btn btn-primary">
                        <i class="bi bi-arrow-left me-1"></i>Retour au dashboard
                    </a>
                    <a href="logs.php" class="btn btn-outline-secondary">
                        <i class="bi bi-journal-text me-1"></i>Voir les logs complets
                    </a>
                    <button type="button" onclick="location.reload()" class="btn btn-outline-primary">
                        <i class="bi bi-arrow-clockwise me-1"></i>Rafraîchir
                    </button>
                    <!-- Bouton pour relancer directement -->
                    <form method="GET" class="d-inline">
                        <button type="submit" class="btn btn-outline-success">
                            <i class="bi bi-arrow-repeat me-1"></i>Relancer
                        </button>
                    </form>
                </div>
                
            </div>
        </div>
        
        <!-- Note importante -->
        <div class="alert alert-warning mt-4">
            <i class="bi bi-info-circle me-2"></i>
            <strong>Note :</strong> Cette page exécute le script de monitoring en temps réel. 
            L'exécution peut prendre jusqu'à <?= count($sites) * 10 ?> secondes (10s par site). 
            Pour une surveillance continue, configurez la tâche Cron dans cPanel : 
            <code>*/5 * * * * /usr/local/bin/php /home/fasoon5/monitor.php</code>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer text-center py-3">
        <div class="container">
            <small>Exécution manuelle • <?= date('Y') ?></small>
        </div>
    </footer>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Rafraîchissement intelligent : uniquement si l'utilisateur reste sur la page
        document.addEventListener('DOMContentLoaded', function() {
            // Auto-refresh après 30s SI aucune interaction utilisateur
            let userActive = true;
            ['click', 'scroll', 'keypress'].forEach(evt => 
                document.addEventListener(evt, () => userActive = true)
            );
            
            setTimeout(() => {
                if (userActive && document.visibilityState === 'visible') {
                    // Afficher un toast avant refresh (optionnel)
                    location.reload();
                }
            }, 30000);
        });
    </script>
</body>
</html>