<?php
/**
 * Automaatse väljalogimise seaded - AINULT ADMINITELE
 */

require_once '../config/config.php';
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

// Nõua admin õigusi
requireAdmin();

$error = '';
$success = '';

// Lae praegused seaded
$current_settings = [
    'auto_logout_enabled' => getSystemSetting('auto_logout_enabled', '1'),
    'auto_logout_timeout' => getSystemSetting('auto_logout_timeout', '30'),
    'auto_logout_warning' => getSystemSetting('auto_logout_warning', '5'),
    'session_check_interval' => getSystemSetting('session_check_interval', '5'),
    'multi_tab_restriction' => getSystemSetting('multi_tab_restriction', '0')
];

// Töötle seadete uuendamist
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_settings'])) {
    $auto_logout_enabled = isset($_POST['auto_logout_enabled']) ? '1' : '0';
    $auto_logout_timeout = (int)getPost('auto_logout_timeout', 30);
    $auto_logout_warning = (int)getPost('auto_logout_warning', 5);
    $session_check_interval = (int)getPost('session_check_interval', 5);
    $multi_tab_restriction = isset($_POST['multi_tab_restriction']) ? '1' : '0';
    
    // Valideerimine
    if ($auto_logout_timeout < 5 || $auto_logout_timeout > 480) {
        $error = 'Timeout peab olema 5-480 minuti vahel';
    } elseif ($auto_logout_warning < 1 || $auto_logout_warning >= $auto_logout_timeout) {
        $error = 'Hoiatuse aeg peab olema 1 minut kuni timeout aeg';
    } elseif ($session_check_interval < 1 || $session_check_interval > 60) {
        $error = 'Sessiooni kontroll peab olema 1-60 minuti vahel';
    } else {
        try {
            // Uuenda seaded
            $user_id = $_SESSION['user_id'];
            
            updateSystemSetting('auto_logout_enabled', $auto_logout_enabled, $user_id);
            updateSystemSetting('auto_logout_timeout', (string)$auto_logout_timeout, $user_id);
            updateSystemSetting('auto_logout_warning', (string)$auto_logout_warning, $user_id);
            updateSystemSetting('session_check_interval', (string)$session_check_interval, $user_id);
            updateSystemSetting('multi_tab_restriction', $multi_tab_restriction, $user_id);
            
            // Uuenda praegused seaded
            $current_settings = [
                'auto_logout_enabled' => $auto_logout_enabled,
                'auto_logout_timeout' => (string)$auto_logout_timeout,
                'auto_logout_warning' => (string)$auto_logout_warning,
                'session_check_interval' => (string)$session_check_interval,
                'multi_tab_restriction' => $multi_tab_restriction
            ];
            
            $success = 'Automaatse väljalogimise seaded uuendatud!';
            
            // Logi tegevus
            logActivity($user_id, 'auto_logout_settings_updated', json_encode($current_settings));
            
        } catch (Exception $e) {
            $error = 'Seadete uuendamine ebaõnnestus: ' . $e->getMessage();
            error_log('Auto-logout settings update error: ' . $e->getMessage());
        }
    }
}

// Lae aktiivste kasutajate statistika
try {
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(DISTINCT user_id) as active_sessions
        FROM activity_log 
        WHERE created_at > datetime('now', '-1 hour')
        AND action IN ('login', 'session_check')
    ");
    $stmt->execute();
    $session_stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Lae automaatsete väljalogimiste statistika
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as auto_logouts_today,
            COUNT(CASE WHEN created_at > datetime('now', '-1 hour') THEN 1 END) as auto_logouts_hour
        FROM activity_log 
        WHERE action = 'auto_logout' 
        AND date(created_at) = date('now')
    ");
    $stmt->execute();
    $logout_stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $session_stats = ['active_sessions' => 0];
    $logout_stats = ['auto_logouts_today' => 0, 'auto_logouts_hour' => 0];
    error_log('Session stats error: ' . $e->getMessage());
}

$page_title = 'Automaatse väljalogimise seaded';
$page_description = 'Halda automaatse väljalogimise süsteemi seadeid';

include '../includes/header.php';
?>

<main class="admin-main">
    <div class="container">
        <!-- Breadcrumb -->
        <nav class="breadcrumb">
            <a href="<?php echo url('admin/dashboard.php'); ?>">Admin</a>
            <span class="breadcrumb-separator">›</span>
            <span class="breadcrumb-current">Auto-logout seaded</span>
        </nav>

        <!-- Header -->
        <div class="page-header">
            <div class="page-header-content">
                <h1 class="page-title">
                    <i class="icon-shield"></i>
                    Automaatse väljalogimise seaded
                </h1>
                <p class="page-subtitle">
                    Halda süsteemi turvalisuse seadeid ja automaatset väljalogimist
                </p>
            </div>
            
            <div class="page-actions">
                <button onclick="testAutoLogout()" class="btn btn-secondary">
                    <i class="icon-play"></i>
                    <span>Testi süsteemi</span>
                </button>
            </div>
        </div>

        <!-- Alerts -->
        <?php if ($error): ?>
            <div class="alert alert-error">
                <i class="icon-alert-circle"></i>
                <span><?php echo htmlspecialchars($error); ?></span>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success">
                <i class="icon-check-circle"></i>
                <span><?php echo htmlspecialchars($success); ?></span>
            </div>
        <?php endif; ?>

        <!-- Grid -->
        <div class="admin-grid">
            <!-- Seaded -->
            <div class="admin-card main-card">
                <div class="card-header">
                    <h2 class="card-title">
                        <i class="icon-settings"></i>
                        Süsteemi seaded
                    </h2>
                </div>
                
                <div class="card-content">
                    <form method="POST" class="settings-form">
                        <!-- Põhiseaded -->
                        <div class="form-section">
                            <h3 class="section-title">Automaatne väljalogimine</h3>
                            
                            <div class="form-group">
                                <label class="checkbox-label">
                                    <input type="checkbox" name="auto_logout_enabled" 
                                           class="checkbox-input" 
                                           <?php echo $current_settings['auto_logout_enabled'] === '1' ? 'checked' : ''; ?>>
                                    <span class="checkbox-custom"></span>
                                    <span class="checkbox-text">Luba automaatne väljalogimine</span>
                                </label>
                                <div class="form-help">Kui lubatud, logitakse kasutajad automaatselt välja passiivsuse korral</div>
                            </div>
                        </div>

                        <!-- Ajaseaded -->
                        <div class="form-section" id="timeout-settings">
                            <h3 class="section-title">Ajaseaded</h3>
                            
                            <div class="form-grid">
                                <div class="form-group">
                                    <label for="auto_logout_timeout" class="form-label">
                                        Timeout (minutites) *
                                    </label>
                                    <input type="number" id="auto_logout_timeout" name="auto_logout_timeout" 
                                           class="form-input" min="5" max="480" 
                                           value="<?php echo htmlspecialchars($current_settings['auto_logout_timeout']); ?>" 
                                           required>
                                    <div class="form-help">5-480 minutit. Kui kaua kasutaja võib olla passiivne.</div>
                                </div>

                                <div class="form-group">
                                    <label for="auto_logout_warning" class="form-label">
                                        Hoiatuse aeg (minutites) *
                                    </label>
                                    <input type="number" id="auto_logout_warning" name="auto_logout_warning" 
                                           class="form-input" min="1" max="60" 
                                           value="<?php echo htmlspecialchars($current_settings['auto_logout_warning']); ?>" 
                                           required>
                                    <div class="form-help">Mitu minutit enne väljalogimist hoiatust näidata.</div>
                                </div>

                                <div class="form-group">
                                    <label for="session_check_interval" class="form-label">
                                        Sessiooni kontroll (minutites) *
                                    </label>
                                    <input type="number" id="session_check_interval" name="session_check_interval" 
                                           class="form-input" min="1" max="60" 
                                           value="<?php echo htmlspecialchars($current_settings['session_check_interval']); ?>" 
                                           required>
                                    <div class="form-help">Kui tihti serverist sessiooni kehtivust kontrollida.</div>
                                </div>
                            </div>
                        </div>

                        <!-- Täiendavad seaded -->
                        <div class="form-section">
                            <h3 class="section-title">Täiendavad turvalisuse seaded</h3>
                            
                            <div class="form-group">
                                <label class="checkbox-label">
                                    <input type="checkbox" name="multi_tab_restriction" 
                                           class="checkbox-input" 
                                           <?php echo $current_settings['multi_tab_restriction'] === '1' ? 'checked' : ''; ?>>
                                    <span class="checkbox-custom"></span>
                                    <span class="checkbox-text">Piira mitme tabi kasutamist</span>
                                </label>
                                <div class="form-help">
                                    <strong>Hoiatus:</strong> Võib mõjutada kasutajakogemust. 
                                    Kui lubatud, hoiatab kasutajaid mitme tabi avamisel.
                                </div>
                            </div>
                        </div>

                        <!-- Salvesta -->
                        <div class="form-actions">
                            <button type="submit" name="update_settings" class="btn btn-primary">
                                <i class="icon-save"></i>
                                <span>Salvesta seaded</span>
                            </button>
                            
                            <button type="button" onclick="resetToDefaults()" class="btn btn-secondary">
                                <i class="icon-refresh"></i>
                                <span>Taasta vaikeväärtused</span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Statistika -->
            <div class="admin-sidebar">
                <!-- Sessioonide statistika -->
                <div class="admin-card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="icon-activity"></i>
                            Sessioonide statistika
                        </h3>
                    </div>
                    <div class="card-content">
                        <div class="stats-list">
                            <div class="stat-item">
                                <div class="stat-label">Aktiivsed sessioonid (viimane tund)</div>
                                <div class="stat-value"><?php echo $session_stats['active_sessions']; ?></div>
                            </div>
                            
                            <div class="stat-item">
                                <div class="stat-label">Auto-logout täna</div>
                                <div class="stat-value danger"><?php echo $logout_stats['auto_logouts_today']; ?></div>
                            </div>
                            
                            <div class="stat-item">
                                <div class="stat-label">Auto-logout viimane tund</div>
                                <div class="stat-value warning"><?php echo $logout_stats['auto_logouts_hour']; ?></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Praegused seaded -->
                <div class="admin-card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="icon-info"></i>
                            Praegused seaded
                        </h3>
                    </div>
                    <div class="card-content">
                        <div class="current-settings">
                            <div class="setting-item">
                                <strong>Staatus:</strong>
                                <span class="status-badge <?php echo $current_settings['auto_logout_enabled'] === '1' ? 'active' : 'inactive'; ?>">
                                    <?php echo $current_settings['auto_logout_enabled'] === '1' ? 'Aktiivne' : 'Välja lülitatud'; ?>
                                </span>
                            </div>
                            
                            <div class="setting-item">
                                <strong>Timeout:</strong>
                                <span><?php echo $current_settings['auto_logout_timeout']; ?> minutit</span>
                            </div>
                            
                            <div class="setting-item">
                                <strong>Hoiatus:</strong>
                                <span><?php echo $current_settings['auto_logout_warning']; ?> minutit enne</span>
                            </div>
                            
                            <div class="setting-item">
                                <strong>Kontroll:</strong>
                                <span>Iga <?php echo $current_settings['session_check_interval']; ?> minutit</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Kiired toimingud -->
                <div class="admin-card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="icon-zap"></i>
                            Kiired toimingud
                        </h3>
                    </div>
                    <div class="card-content">
                        <div class="quick-actions">
                            <button onclick="viewActiveSessions()" class="action-btn">
                                <i class="icon-users"></i>
                                <span>Aktiivsed sessioonid</span>
                            </button>
                            
                            <button onclick="viewLogoutHistory()" class="action-btn">
                                <i class="icon-clock"></i>
                                <span>Väljalogimiste ajalugu</span>
                            </button>
                            
                            <button onclick="exportSettings()" class="action-btn">
                                <i class="icon-download"></i>
                                <span>Ekspordi seaded</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<style>
/* ASENDA auto-logout-settings.php faili <style> sektsioon selle CSS-iga: */

/* ===== KAASAEGNE AUTO-LOGOUT SETTINGS DISAIN ===== */
.admin-main {
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    min-height: 100vh;
    padding: var(--spacing-6) 0;
}

.container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 var(--spacing-4);
}

/* ===== BREADCRUMB ===== */
.breadcrumb {
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    margin-bottom: var(--spacing-6);
    font-size: var(--font-size-sm);
    color: var(--gray-600);
}

.breadcrumb a {
    color: var(--primary-color);
    text-decoration: none;
    font-weight: 500;
}

.breadcrumb a:hover {
    text-decoration: underline;
}

.breadcrumb-separator {
    color: var(--gray-400);
}

.breadcrumb-current {
    color: var(--gray-900);
    font-weight: 600;
}

/* ===== PAGE HEADER ===== */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: var(--spacing-8);
    gap: var(--spacing-6);
}

.page-header-content h1 {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    margin-bottom: var(--spacing-2);
    color: var(--gray-900);
    font-size: 2rem;
    font-weight: 700;
}

.page-header-content h1 i {
    color: var(--primary-color);
    font-size: 1.8rem;
}

.page-header-content p {
    color: var(--gray-600);
    font-size: var(--font-size-lg);
    margin: 0;
}

.page-actions {
    display: flex;
    gap: var(--spacing-3);
}

/* ===== CARDS SYSTEM ===== */
.admin-grid {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: var(--spacing-8);
    align-items: start;
}

.admin-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    border: 1px solid var(--gray-200);
    overflow: hidden;
    transition: all 0.3s ease;
}

.admin-card:hover {
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    transform: translateY(-2px);
}

.card-header {
    background: linear-gradient(135deg, var(--gray-50) 0%, var(--gray-100) 100%);
    padding: var(--spacing-6);
    border-bottom: 1px solid var(--gray-200);
}

.card-title {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    margin: 0;
    font-size: var(--font-size-xl);
    font-weight: 600;
    color: var(--gray-900);
}

.card-title i {
    color: var(--primary-color);
    font-size: 1.25rem;
}

.card-content {
    padding: var(--spacing-8);
}

/* ===== SIDEBAR ===== */
.admin-sidebar {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-6);
    position: sticky;
    top: var(--spacing-6);
}

/* ===== FORMS ===== */
.settings-form {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-8);
}

.form-section {
    position: relative;
    padding: var(--spacing-6);
    background: var(--gray-50);
    border-radius: 12px;
    border: 1px solid var(--gray-200);
}

.form-section:not(:last-child) {
    margin-bottom: var(--spacing-6);
}

.section-title {
    margin-bottom: var(--spacing-6);
    color: var(--gray-900);
    font-size: var(--font-size-xl);
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
}

.section-title:before {
    content: "";
    width: 4px;
    height: 24px;
    background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
    border-radius: 2px;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: var(--spacing-6);
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-2);
}

.form-label {
    font-weight: 600;
    color: var(--gray-700);
    font-size: var(--font-size-sm);
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
}

.form-input, .form-select {
    padding: var(--spacing-4);
    border: 2px solid var(--gray-200);
    border-radius: 8px;
    font-size: var(--font-size-base);
    transition: all 0.2s ease;
    background: white;
}

.form-input:focus, .form-select:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-help {
    font-size: var(--font-size-xs);
    color: var(--gray-500);
    line-height: 1.4;
}

/* ===== CHECKBOXES (MODERNIZED) ===== */
.checkbox-label {
    display: flex;
    align-items: flex-start;
    gap: var(--spacing-3);
    cursor: pointer;
    padding: var(--spacing-4);
    border-radius: 8px;
    transition: background-color 0.2s ease;
    border: 1px solid var(--gray-200);
    background: white;
}

.checkbox-label:hover {
    background: var(--gray-50);
    border-color: var(--primary-color);
}

.checkbox-input {
    display: none;
}

.checkbox-custom {
    width: 20px;
    height: 20px;
    border: 2px solid var(--gray-300);
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
    flex-shrink: 0;
    background: white;
}

.checkbox-input:checked + .checkbox-custom {
    background: var(--primary-color);
    border-color: var(--primary-color);
    transform: scale(1.05);
}

.checkbox-input:checked + .checkbox-custom::after {
    content: '✓';
    color: white;
    font-weight: bold;
    font-size: 12px;
}

.checkbox-text {
    font-weight: 500;
    color: var(--gray-900);
    line-height: 1.4;
}

/* ===== BUTTONS ===== */
.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: var(--spacing-4);
    margin-top: var(--spacing-8);
    padding-top: var(--spacing-6);
    border-top: 1px solid var(--gray-200);
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: var(--spacing-2);
    padding: var(--spacing-3) var(--spacing-6);
    border-radius: 8px;
    font-weight: 600;
    font-size: var(--font-size-sm);
    cursor: pointer;
    transition: all 0.2s ease;
    border: none;
    text-decoration: none;
}

.btn-primary {
    background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
    color: white;
    box-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);
}

.btn-primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.btn-secondary {
    background: var(--gray-100);
    color: var(--gray-700);
    border: 1px solid var(--gray-300);
}

.btn-secondary:hover {
    background: var(--gray-200);
    transform: translateY(-1px);
}

/* ===== STATISTICS ===== */
.stats-list {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-4);
}

.stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: var(--spacing-4);
    background: linear-gradient(135deg, var(--gray-50), white);
    border-radius: 8px;
    border: 1px solid var(--gray-200);
}

.stat-label {
    font-size: var(--font-size-sm);
    color: var(--gray-600);
    font-weight: 500;
}

.stat-value {
    font-weight: 700;
    font-size: var(--font-size-lg);
    color: var(--gray-900);
}

.stat-value.danger {
    color: var(--danger-color);
}

.stat-value.warning {
    color: #f59e0b;
}

/* ===== CURRENT SETTINGS ===== */
.current-settings {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-4);
}

.setting-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: var(--spacing-3) 0;
    border-bottom: 1px solid var(--gray-200);
    font-size: var(--font-size-sm);
}

.setting-item:last-child {
    border-bottom: none;
}

.status-badge {
    padding: var(--spacing-1) var(--spacing-3);
    border-radius: 16px;
    font-size: var(--font-size-xs);
    font-weight: 600;
    text-transform: uppercase;
}

.status-badge.active {
    background: linear-gradient(135deg, var(--success-color), #059669);
    color: white;
}

.status-badge.inactive {
    background: var(--gray-400);
    color: white;
}

/* ===== QUICK ACTIONS ===== */
.quick-actions {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-3);
}

.action-btn {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    padding: var(--spacing-4);
    background: white;
    border: 1px solid var(--gray-200);
    border-radius: 8px;
    color: var(--gray-700);
    cursor: pointer;
    transition: all 0.2s ease;
    text-align: left;
    font-size: var(--font-size-sm);
    font-weight: 500;
}

.action-btn:hover {
    background: var(--primary-color);
    border-color: var(--primary-color);
    color: white;
    transform: translateX(4px);
}

.action-btn i {
    color: var(--primary-color);
    transition: color 0.2s ease;
}

.action-btn:hover i {
    color: white;
}

/* ===== ALERTS ===== */
.alert {
    padding: var(--spacing-4);
    border-radius: 8px;
    margin-bottom: var(--spacing-4);
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    border-left: 4px solid;
}

.alert-success {
    background: rgba(16, 185, 129, 0.1);
    color: #047857;
    border-color: var(--success-color);
}

.alert-error {
    background: rgba(239, 68, 68, 0.1);
    color: #dc2626;
    border-color: var(--danger-color);
}

/* ===== RESPONSIVE DESIGN ===== */
@media (max-width: 1200px) {
    .admin-grid {
        grid-template-columns: 1fr;
        gap: var(--spacing-6);
    }
    
    .admin-sidebar {
        position: static;
        order: -1;
    }
}

@media (max-width: 768px) {
    .admin-main {
        padding: var(--spacing-4) 0;
    }
    
    .page-header {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-4);
    }
    
    .page-header-content h1 {
        font-size: 1.5rem;
    }
    
    .form-grid {
        grid-template-columns: 1fr;
        gap: var(--spacing-4);
    }
    
    .form-actions {
        flex-direction: column;
    }
    
    .card-content, .card-header {
        padding: var(--spacing-4);
    }
    
    .admin-sidebar {
        gap: var(--spacing-4);
    }
}

@media (max-width: 480px) {
    .container {
        padding: 0 var(--spacing-3);
    }
    
    .form-section {
        padding: var(--spacing-4);
    }
    
    .checkbox-label {
        padding: var(--spacing-3);
        flex-direction: column;
        align-items: flex-start;
        gap: var(--spacing-2);
    }
    
    .stat-item {
        flex-direction: column;
        align-items: flex-start;
        gap: var(--spacing-2);
    }
}

/* ===== SPECIAL STATES ===== */
#timeout-settings {
    transition: opacity 0.3s ease;
}

#timeout-settings.disabled {
    opacity: 0.5;
    pointer-events: none;
}

#timeout-settings.disabled .form-input,
#timeout-settings.disabled .form-select {
    background: var(--gray-100);
    color: var(--gray-400);
}

/* ===== ANIMATIONS ===== */
@keyframes slideInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.admin-card {
    animation: slideInUp 0.4s ease-out;
}

.admin-card:nth-child(2) {
    animation-delay: 0.1s;
}

.admin-card:nth-child(3) {
    animation-delay: 0.2s;
}

/* ===== LOADING STATES ===== */
.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none !important;
}

.btn:disabled:hover {
    transform: none !important;
    box-shadow: none !important;
}
</style>

<script>
// Auto-logout settings JavaScript
document.addEventListener('DOMContentLoaded', function() {
    const enabledCheckbox = document.querySelector('input[name="auto_logout_enabled"]');
    const timeoutSettings = document.getElementById('timeout-settings');
    
    // Disable/enable timeout settings based on main checkbox
    function toggleTimeoutSettings() {
        const inputs = timeoutSettings.querySelectorAll('input');
        inputs.forEach(input => {
            input.disabled = !enabledCheckbox.checked;
        });
        
        if (enabledCheckbox.checked) {
            timeoutSettings.classList.remove('disabled');
        } else {
            timeoutSettings.classList.add('disabled');
        }
    }
    
    enabledCheckbox.addEventListener('change', toggleTimeoutSettings);
    toggleTimeoutSettings(); // Initial state
    
    // Form validation
    const form = document.querySelector('.settings-form');
    form.addEventListener('submit', function(e) {
        const timeout = parseInt(document.getElementById('auto_logout_timeout').value);
        const warning = parseInt(document.getElementById('auto_logout_warning').value);
        
        if (warning >= timeout) {
            e.preventDefault();
            alert('Hoiatuse aeg peab olema väiksem kui timeout aeg!');
            return false;
        }
    });
});

// Quick action functions
function testAutoLogout() {
    if (typeof window.autoLogout !== 'undefined') {
        // Test current system
        const status = window.autoLogout.getStatus();
        alert(`Auto-logout süsteem:\n\nAktiivne: ${status.active ? 'Jah' : 'Ei'}\nTimeout: ${status.timeoutMinutes} min\nJäänud aeg: ${Math.floor(status.timeUntilLogout / 60)} min ${status.timeUntilLogout % 60} sek\nHoiatus: ${status.warningShown ? 'Nähtav' : 'Peidetud'}`);
    } else {
        alert('Auto-logout süsteem pole praegu aktiivne.');
    }
}

function resetToDefaults() {
    if (confirm('Kas tahad taastada vaikeväärtused?\n\n• Timeout: 30 minutit\n• Hoiatus: 5 minutit\n• Kontroll: 5 minutit\n• Luba auto-logout: Jah')) {
        document.getElementById('auto_logout_timeout').value = 30;
        document.getElementById('auto_logout_warning').value = 5;
        document.getElementById('session_check_interval').value = 5;
        document.querySelector('input[name="auto_logout_enabled"]').checked = true;
        document.querySelector('input[name="multi_tab_restriction"]').checked = false;
    }
}

function viewActiveSessions() {
    // TODO: Implement active sessions view
    alert('Aktiivsete sessioonide vaade tuleb peagi!');
}

function viewLogoutHistory() {
    // TODO: Implement logout history
    alert('Väljalogimiste ajaloo vaade tuleb peagi!');
}

function exportSettings() {
    const settings = {
        auto_logout_enabled: document.querySelector('input[name="auto_logout_enabled"]').checked,
        auto_logout_timeout: document.getElementById('auto_logout_timeout').value,
        auto_logout_warning: document.getElementById('auto_logout_warning').value,
        session_check_interval: document.getElementById('session_check_interval').value,
        multi_tab_restriction: document.querySelector('input[name="multi_tab_restriction"]').checked,
        exported_at: new Date().toISOString()
    };
    
    const blob = new Blob([JSON.stringify(settings, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'estreka_autologout_settings.json';
    a.click();
    URL.revokeObjectURL(url);
}
</script>

<?php include '../includes/footer.php'; ?>