// Logs-Seite JavaScript
document.addEventListener('DOMContentLoaded', function() {
    loadLogs();
});

// Alle Logs laden
async function loadLogs() {
    try {
        const response = await fetch('/api/logs');
        const data = await response.json();
        
        if (data.success) {
            displayLogs(data.logs);
        } else {
            showError('Fehler beim Laden der Logs: ' + data.message);
        }
    } catch (error) {
        showError('Fehler beim Laden der Logs: ' + error.message);
    }
}

// Logs in der Tabelle anzeigen
function displayLogs(logs) {
    const tableBody = document.getElementById('logsTableBody');
    const loading = document.getElementById('loading');
    const noLogs = document.getElementById('noLogs');
    
    // Loading ausblenden
    loading.style.display = 'none';
    
    if (!logs || logs.length === 0) {
        noLogs.style.display = 'block';
        return;
    }
    
    // Tabelle leeren
    tableBody.innerHTML = '';
    
    // Logs hinzufügen
    logs.forEach(log => {
        const row = document.createElement('tr');
        
        // Zeitstempel formatieren
        const timestamp = new Date(log.timestamp);
        const formattedTime = timestamp.toLocaleString('de-DE', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
        
        // Auslöser übersetzen
        const triggerText = log.trigger === 'button' ? 'Button-Klick' : 
                           log.trigger === 'cron' ? 'Automatisch' : log.trigger;
        
        row.innerHTML = `
            <td>${formattedTime}</td>
            <td>${escapeHtml(log.pc_name)}</td>
            <td>${escapeHtml(log.mac)}</td>
            <td>${escapeHtml(triggerText)}</td>
        `;
        
        tableBody.appendChild(row);
    });
}

// Fehler anzeigen
function showError(message) {
    const loading = document.getElementById('loading');
    loading.innerHTML = `<p class="error">${escapeHtml(message)}</p>`;
}

// HTML-Escaping für Sicherheit
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}
