<?php
/**
 * System-Logs - KORRIGIERT für deutsche Spaltennamen
 * Backend Logs mit korrektem Spalten-Mapping
 */

require_once __DIR__ . '/config.php';
requireBackendAccess();

$pageTitle = 'System-Logs';

// Tab auswählen
$activeTab = $_GET['tab'] ?? 'activity';

// Limit
$limit = intval($_GET['limit'] ?? 50);

$logs = [];
$stats = [];

try {
    if ($activeTab === 'activity') {
        // FIXED: users Tabelle statt benutzer, user_id statt benutzer_id
        $logs = $db->select("
            SELECT al.*, u.username
            FROM activity_log al
            LEFT JOIN users u ON al.user_id = u.id
            ORDER BY al.zeitstempel DESC
            LIMIT ?
        ", [$limit]);
        
        // Statistiken
        $stats['total'] = $db->selectOne("SELECT COUNT(*) as count FROM activity_log")['count'];
        $stats['created'] = $db->selectOne("SELECT COUNT(*) as count FROM activity_log WHERE aktion = 'created'")['count'];
        $stats['updated'] = $db->selectOne("SELECT COUNT(*) as count FROM activity_log WHERE aktion = 'updated'")['count'];
        $stats['deleted'] = $db->selectOne("SELECT COUNT(*) as count FROM activity_log WHERE aktion = 'deleted'")['count'];
        
    } else { // security
        $logs = $db->select("
            SELECT sl.*, u.username
            FROM security_log sl
            LEFT JOIN users u ON sl.user_id = u.id
            ORDER BY sl.created_at DESC
            LIMIT ?
        ", [$limit]);
        
        // Statistiken (24h)
        $stats['total'] = $db->selectOne("SELECT COUNT(*) as count FROM security_log")['count'];
        $stats['success_24h'] = $db->selectOne("SELECT COUNT(*) as count FROM security_log WHERE event_type = 'login_success' AND created_at >= datetime('now', '-24 hours')")['count'];
        $stats['failed_24h'] = $db->selectOne("SELECT COUNT(*) as count FROM security_log WHERE event_type = 'login_failed' AND created_at >= datetime('now', '-24 hours')")['count'];
        
        $totalLogins = $stats['success_24h'] + $stats['failed_24h'];
        $stats['success_rate'] = $totalLogins > 0 ? round(($stats['success_24h'] / $totalLogins) * 100, 1) : 0;
    }
    
} catch (Exception $e) {
    $error = 'Fehler beim Laden der Logs: ' . $e->getMessage();
    error_log("Logs Error: " . $e->getMessage());
}

// Layout laden
include 'layout/header_next_page.php';
?>

<!-- Main Content -->
<main class="backend-main">
    
    <?php if (isset($error)): ?>
        <div class="alert alert-danger">
            <strong><i class="ti ti-circle-x" style="color:var(--vs-danger);"></i> Fehler!</strong> <?php echo htmlspecialchars($error); ?>
        </div>
    <?php endif; ?>
    
    <!-- Tab Navigation -->
    <div class="tab-navigation">
        <a href="?tab=activity&limit=<?php echo $limit; ?>" class="tab-link <?php echo $activeTab === 'activity' ? 'active' : ''; ?>">
            <i class="ti ti-chart-bar"></i> Activity Logs
        </a>
        <a href="?tab=security&limit=<?php echo $limit; ?>" class="tab-link <?php echo $activeTab === 'security' ? 'active' : ''; ?>">
            <i class="ti ti-lock"></i> Security Logs
        </a>
    </div>
    
    <!-- Statistik-Karten -->
    <?php if (!empty($stats)): ?>
    <div class="dashboard-grid" style="margin-bottom: 30px;">
        <?php if ($activeTab === 'activity'): ?>
            <div class="widget-card">
                <div class="widget-header">
                    <div>
                        <div class="widget-value"><?php echo number_format($stats['total'], 0, ',', '.'); ?></div>
                        <div class="widget-label"><i class="ti ti-chart-bar"></i> Gesamt</div>
                    </div>
                    <div class="widget-icon"><i class="ti ti-chart-bar"></i></div>
                </div>
            </div>
            
            <div class="widget-card">
                <div class="widget-header">
                    <div>
                        <div class="widget-value" style="color: var(--vs-success);"><?php echo number_format($stats['created'], 0, ',', '.'); ?></div>
                        <div class="widget-label"><i class="ti ti-plus"></i> Erstellt</div>
                    </div>
                    <div class="widget-icon"><i class="ti ti-plus"></i></div>
                </div>
            </div>
            
            <div class="widget-card">
                <div class="widget-header">
                    <div>
                        <div class="widget-value" style="color: var(--vs-accent);"><?php echo number_format($stats['updated'], 0, ',', '.'); ?></div>
                        <div class="widget-label"><i class="ti ti-pencil"></i> Bearbeitet</div>
                    </div>
                    <div class="widget-icon"><i class="ti ti-pencil"></i></div>
                </div>
            </div>
            
            <div class="widget-card">
                <div class="widget-header">
                    <div>
                        <div class="widget-value" style="color: var(--vs-danger);"><?php echo number_format($stats['deleted'], 0, ',', '.'); ?></div>
                        <div class="widget-label"><i class="ti ti-trash"></i> Gelöscht</div>
                    </div>
                    <div class="widget-icon"><i class="ti ti-trash"></i></div>
                </div>
            </div>
        <?php else: ?>
            <div class="widget-card">
                <div class="widget-header">
                    <div>
                        <div class="widget-value"><?php echo number_format($stats['total'], 0, ',', '.'); ?></div>
                        <div class="widget-label"><i class="ti ti-chart-bar"></i> Gesamt</div>
                    </div>
                    <div class="widget-icon"><i class="ti ti-chart-bar"></i></div>
                </div>
            </div>
            
            <div class="widget-card">
                <div class="widget-header">
                    <div>
                        <div class="widget-value" style="color: var(--vs-success);"><?php echo number_format($stats['success_24h'], 0, ',', '.'); ?></div>
                        <div class="widget-label"><i class="ti ti-circle-check" style="color:var(--vs-success);"></i> Erfolg (24h)</div>
                    </div>
                    <div class="widget-icon"><i class="ti ti-circle-check" style="color:var(--vs-success);"></i></div>
                </div>
            </div>
            
            <div class="widget-card">
                <div class="widget-header">
                    <div>
                        <div class="widget-value" style="color: var(--vs-danger);"><?php echo number_format($stats['failed_24h'], 0, ',', '.'); ?></div>
                        <div class="widget-label"><i class="ti ti-circle-x" style="color:var(--vs-danger);"></i> Fehler (24h)</div>
                    </div>
                    <div class="widget-icon"><i class="ti ti-circle-x" style="color:var(--vs-danger);"></i></div>
                </div>
            </div>
            
            <div class="widget-card">
                <div class="widget-header">
                    <div>
                        <div class="widget-value" style="font-size: 32px;"><?php echo $stats['success_rate']; ?>%</div>
                        <div class="widget-label"><i class="ti ti-trending-up"></i> Erfolgsquote</div>
                    </div>
                    <div class="widget-icon"><i class="ti ti-trending-up"></i></div>
                </div>
            </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    
    <!-- Logs-Tabelle -->
    <div class="activity-timeline">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h2><?php echo $activeTab === 'security' ? '<i class="ti ti-lock"></i> Security Logs' : '<i class="ti ti-chart-bar"></i> Activity Logs'; ?></h2>
            <div>
                <select id="limitSelect" onchange="changeLimit()" class="form-control" style="width: auto; display: inline-block;">
                    <option value="25" <?php echo $limit == 25 ? 'selected' : ''; ?>>25 Einträge</option>
                    <option value="50" <?php echo $limit == 50 ? 'selected' : ''; ?>>50 Einträge</option>
                    <option value="100" <?php echo $limit == 100 ? 'selected' : ''; ?>>100 Einträge</option>
                    <option value="250" <?php echo $limit == 250 ? 'selected' : ''; ?>>250 Einträge</option>
                </select>
            </div>
        </div>
        
        <?php if (count($logs) === 0): ?>
            <div style="text-align: center; padding: 40px; color: #999;">
                <div style="font-size: 48px; margin-bottom: 15px;"><i class="ti ti-chart-bar"></i></div>
                <p>Keine Logs gefunden</p>
                <?php if ($activeTab === 'security' && $stats['total'] == 0): ?>
                    <p style="font-size: 13px; color: #999; margin-top: 10px;">
                        Möchten Sie historische Logs importieren?<br>
                        <a href="../migrate_security_logs.php" style="color: var(--vs-accent);">→ Security-Logs aus Datei importieren</a>
                    </p>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <table class="backend-table">
                <thead>
                    <tr>
                        <th style="width: 180px;">Zeit</th>
                        <th style="width: 120px;">Benutzer</th>
                        <?php if ($activeTab === 'activity'): ?>
                            <th style="width: 100px;">Aktion</th>
                            <th style="width: 120px;">Tabelle</th>
                            <th>Bezeichnung</th>
                            <th style="width: 150px;">IP-Adresse</th>
                        <?php else: ?>
                            <th style="width: 150px;">Event</th>
                            <th>Beschreibung</th>
                            <th style="width: 150px;">IP-Adresse</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($logs as $log): ?>
                        <tr>
                            <td>
                                <?php 
                                $time = $activeTab === 'security' ? $log['created_at'] : $log['zeitstempel'];
                                echo '<span title="' . date('d.m.Y H:i:s', strtotime($time)) . '">' . timeAgo($time) . '</span>';
                                ?>
                            </td>
                            <td>
                                <strong><?php echo htmlspecialchars($log['username'] ?? 'System'); ?></strong>
                            </td>
                            
                            <?php if ($activeTab === 'activity'): ?>
                                <td>
                                    <?php 
                                    $badges = [
                                        'created' => '<span class="badge badge-success"><i class="ti ti-plus"></i> Erstellt</span>',
                                        'updated' => '<span class="badge badge-info"><i class="ti ti-pencil"></i> Bearbeitet</span>',
                                        'deleted' => '<span class="badge badge-danger"><i class="ti ti-trash"></i> Gelöscht</span>',
                                    ];
                                    echo $badges[$log['aktion']] ?? '<span class="badge">' . htmlspecialchars($log['aktion']) . '</span>';
                                    ?>
                                </td>
                                <td>
                                    <code style="background: var(--vs-surface-2); padding: 2px 8px; border-radius: 3px; font-size: 13px;">
                                        <?php echo htmlspecialchars($log['tabelle']); ?>
                                    </code>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($log['bezeichnung'] ?? '-'); ?></strong>
                                </td>
                                <td>
                                    <code style="background: var(--vs-surface-2); padding: 2px 8px; border-radius: 3px; font-size: 12px;">
                                        <?php echo htmlspecialchars($log['ip_adresse'] ?? '-'); ?>
                                    </code>
                                </td>
                            <?php else: ?>
                                <td>
                                    <?php 
                                    $badges = [
                                        'login_success' => '<span class="badge badge-success"><i class="ti ti-circle-check" style="color:var(--vs-success);"></i> Login OK</span>',
                                        'login_failed' => '<span class="badge badge-danger"><i class="ti ti-circle-x" style="color:var(--vs-danger);"></i> Login Fehler</span>',
                                        'logout' => '<span class="badge badge-secondary">🚪 Logout</span>',
                                        'password_change' => '<span class="badge badge-info"><i class="ti ti-key"></i> Passwort</span>',
                                    ];
                                    echo $badges[$log['event_type']] ?? '<span class="badge">' . htmlspecialchars($log['event_type']) . '</span>';
                                    ?>
                                </td>
                                <td><?php echo htmlspecialchars($log['description'] ?? '-'); ?></td>
                                <td>
                                    <code style="background: var(--vs-surface-2); padding: 2px 8px; border-radius: 3px; font-size: 12px;">
                                        <?php echo htmlspecialchars($log['ip_address'] ?? '-'); ?>
                                    </code>
                                </td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    
</main>

<script>
function changeLimit() {
    const limit = document.getElementById('limitSelect').value;
    const currentTab = '<?php echo $activeTab; ?>';
    window.location.href = '?tab=' + currentTab + '&limit=' + limit;
}
</script>

<?php include 'layout/footer_next_page.php'; ?>
