<?php
// header.php
if (!defined('PAGE_TITLE')) {
    define('PAGE_TITLE', 'Wertsachen-Inventar');
}

// helpers.php einbinden wenn noch nicht geschehen
if (!function_exists('showFlashMessage')) {
    require_once 'helpers.php';
}

// helpers_permissions.php einbinden
if (!function_exists('getUserRole')) {
    require_once 'helpers_permissions.php';
}

// Theme aus Datenbank synchronisieren
if (function_exists('syncUserTheme')) {
    syncUserTheme();
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Wertsachen-Inventarverwaltung - Verwalten Sie Ihre wertvollen Gegenstände">
    <meta name="theme-color" content="#3498db">
    
    <title><?php echo htmlspecialchars(PAGE_TITLE); ?></title>
    
    <!-- Stylesheets -->
    <link rel="stylesheet" href="css/<?php echo htmlspecialchars($_SESSION['theme']); ?>.css">
    <link rel="stylesheet" href="css/enhancements.css">
    
    <!-- PWA Manifest -->
    <link rel="manifest" href="manifest.json">
    
    <!-- Favicon -->
    <link rel="icon" type="image/png" href="favicon.png">
    <link rel="apple-touch-icon" href="apple-touch-icon.png">
</head>
<body class="<?php echo htmlspecialchars($_SESSION['theme']); ?>-theme">
    <!-- Keyboard Shortcuts Info -->
    <div id="shortcuts-info" style="display: none; position: fixed; top: 10px; right: 10px; background: var(--vs-surface); padding: 15px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.2); z-index: 9999;">
        <h4 style="margin-top: 0;">⌨️ Tastenkombinationen</h4>
        <ul style="list-style: none; padding: 0; margin: 0; font-size: 12px;">
            <li><kbd>Strg+N</kbd> Neuer Eintrag</li>
            <li><kbd>Strg+S</kbd> Speichern</li>
            <li><kbd>ESC</kbd> Zurück</li>
        </ul>
        <button onclick="document.getElementById('shortcuts-info').style.display='none'" style="margin-top: 10px; width: 100%;">Schließen</button>
    </div>
    
    <div class="container">
        <header>
            <h1>
                <i class="ti ti-package"></i> Wertsachen-Inventarverwaltung
                <button onclick="document.getElementById('shortcuts-info').style.display='block'" 
                        style="font-size: 14px; margin-left: 10px; padding: 5px 10px; cursor: pointer;"
                        title="Tastenkombinationen anzeigen">
                    ⌨️
                </button>
            </h1>
            <div class="user-info">
                Angemeldet als: <strong><?php echo htmlspecialchars($_SESSION['username']); ?></strong>
                <?php if (function_exists('getUserRole')): ?>
                    <?php echo getRoleBadge(getUserRole()); ?>
                <?php endif; ?>
                | Session läuft ab in: <span id="session-timer">--:--</span> | 
                
                <!-- SPRACHWECHSLER -->
                <span class="language-switcher" style="margin: 0 10px;">
                    <?php
                    $langFlags = getLanguageFlags();
                    $langNames = getLanguageNames();
                    $availableLangs = AVAILABLE_LANGUAGES; // Fix: In Variable speichern
                    $lastLang = end($availableLangs); // Fix: end() braucht Referenz
                    foreach (AVAILABLE_LANGUAGES as $lang):
                        $active = ($currentLang === $lang) ? 'active' : '';
                        $style = ($currentLang === $lang) ? 'font-weight: bold; text-decoration: none;' : '';
                    ?>
                        <a href="change_language.php?lang=<?php echo $lang; ?>" 
                           class="<?php echo $active; ?>" 
                           style="<?php echo $style; ?>" 
                           title="<?php echo $langNames[$lang]; ?>">
                            <?php echo $langFlags[$lang]; ?> <?php echo strtoupper($lang); ?>
                        </a>
                        <?php if ($lang !== $lastLang): ?>|
                        <?php endif; ?>
                    <?php endforeach; ?>
                </span>                
                <!-- BACKEND-BUTTON (nur für Admins sichtbar) -->
<?php if (function_exists('isAdmin') && isAdmin()): ?>
    <a href="backend/" style="
        background: var(--vs-accent);
        color: white;
        padding: 8px 16px;
        border-radius: 6px;
        text-decoration: none;
        font-weight: 600;
        margin: 0 10px;
        display: inline-block;
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        transition: all 0.3s ease;
        font-size: 14px;
    " 
    onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 12px rgba(102, 126, 234, 0.4)';" 
    onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 8px rgba(102, 126, 234, 0.3)';"
    title="Admin-Backend aufrufen">
        👑 Admin-Backend
    </a>
<?php endif; ?>                
                <a href="logout.php">Abmelden</a>
            </div>
        </header>
        <nav>
            <!-- NEU: Dashboard als erste Option -->
            <a href="dashboard.php" class="vs-btn <?php echo basename($_SERVER['PHP_SELF']) == 'dashboard.php' ? 'vs-btn-primary' : 'vs-btn-secondary'; ?>">
                <i class="ti ti-home"></i> Dashboard
            </a>
            
            <!-- NEU: Übersicht umbenannt zu "Alle Gegenstände" -->
            <a href="index.php" class="vs-btn <?php echo basename($_SERVER['PHP_SELF']) == 'index.php' ? 'vs-btn-primary' : 'vs-btn-secondary'; ?>">
                <i class="ti ti-clipboard-list"></i> Alle Gegenstände
            </a>
            
            <?php if (canEdit()): ?>
            <a href="add.php" class="vs-btn <?php echo basename($_SERVER['PHP_SELF']) == 'add.php' ? 'vs-btn-primary' : 'vs-btn-secondary'; ?>">
                <i class="ti ti-plus"></i> Neuer Gegenstand
            </a>
            <?php endif; ?>
            
            <a href="settings.php" class="vs-btn <?php echo basename($_SERVER['PHP_SELF']) == 'settings.php' ? 'vs-btn-primary' : 'vs-btn-secondary'; ?>">
                <i class="ti ti-settings"></i> Einstellungen
            </a>
            
            <?php if (isAdmin()): ?>
            <a href="activity_log.php" class="vs-btn <?php echo basename($_SERVER['PHP_SELF']) == 'activity_log.php' ? 'vs-btn-primary' : 'vs-btn-secondary'; ?>">
                <i class="ti ti-list"></i> Aktivitäten
            </a>
            <?php endif; ?>
            
            <!-- Export Dropdown -->
            <div style="position: relative; display: inline-block; margin-left: auto;">
                <button onclick="toggleExportMenu()" class="vs-btn vs-btn-secondary" style="cursor: pointer;">
                    <i class="ti ti-package"></i> Export ▼
                </button>
                <div id="export-menu" style="display: none; position: absolute; top: 100%; right: 0; background: white; border: 1px solid #ddd; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.2); z-index: 1000; min-width: 220px; margin-top: 5px;">
                    <a href="export_csv.php" style="display: block; padding: 12px 15px; color: #333; text-decoration: none; border-bottom: 1px solid #eee;" onmouseover="this.style.background='#f5f5f5'" onmouseout="this.style.background='white'">
                        <i class="ti ti-chart-bar"></i> CSV-Datei
                    </a>
                    <a href="export_html.php" style="display: block; padding: 12px 15px; color: #333; text-decoration: none; border-bottom: 1px solid #eee;" onmouseover="this.style.background='#f5f5f5'" onmouseout="this.style.background='white'">
                        📄 HTML-Seite
                    </a>
                    <a href="export_pdf.php" style="display: block; padding: 12px 15px; color: #333; text-decoration: none; border-bottom: 1px solid #eee;" onmouseover="this.style.background='#f5f5f5'" onmouseout="this.style.background='white'">
                        📄 PDF Detailliert
                    </a>
                    <a href="export_pdf_compact.php" style="display: block; padding: 12px 15px; color: #333; text-decoration: none;" onmouseover="this.style.background='#f5f5f5'" onmouseout="this.style.background='white'">
                        <i class="ti ti-clipboard-list"></i> PDF Kompakt
                    </a>
                </div>
            </div>
            
            <script>
            function toggleExportMenu() {
                const menu = document.getElementById('export-menu');
                menu.style.display = menu.style.display === 'none' ? 'block' : 'none';
            }
            
            // Schließen wenn außerhalb geklickt wird
            document.addEventListener('click', function(e) {
                const menu = document.getElementById('export-menu');
                const button = e.target.closest('button');
                if (menu && !button && menu.style.display === 'block') {
                    menu.style.display = 'none';
                }
            });
            </script>
        </nav>
        <main>
        
        <script>
        // Session-Timer
        (function() {
            const sessionLifetime = <?php echo SESSION_LIFETIME; ?>;
            const lastActivity = <?php echo $_SESSION['last_activity'] ?? time(); ?>;
            
            function updateTimer() {
                const now = Math.floor(Date.now() / 1000);
                const elapsed = now - lastActivity;
                const remaining = sessionLifetime - elapsed;
                
                if (remaining <= 0) {
                    document.getElementById('session-timer').textContent = 'Abgelaufen';
                    document.getElementById('session-timer').style.color = 'red';
                    setTimeout(() => {
                        window.location.href = 'login.php?timeout=1';
                    }, 2000);
                    return;
                }
                
                const minutes = Math.floor(remaining / 60);
                const seconds = remaining % 60;
                
                const timerEl = document.getElementById('session-timer');
                timerEl.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
                
                // Warnung bei < 5 Minuten
                if (minutes < 5) {
                    timerEl.style.color = 'orange';
                    timerEl.style.fontWeight = 'bold';
                }
                
                // Kritisch bei < 2 Minuten
                if (minutes < 2) {
                    timerEl.style.color = 'red';
                }
            }
            
            updateTimer();
            setInterval(updateTimer, 1000);
        })();
        </script>