<?php
session_start();
require_once 'includes/config.php';

// Initialize variables
$error = '';
$success = '';
$email = '';
$remember = false;

// Check if user is already logged in
if (isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?: '');
    $password = $_POST['password'] ?: '';
    $remember = isset($_POST['remember']);
    $verification_code = $_POST['verification_code'] ?: '';
    $backup_code = $_POST['backup_code'] ?: '';
    
    // Validate inputs
    if (empty($email) || empty($password)) {
        $error = 'Please enter email and password';
    } else {
        // Check if 2FA is required from session
        $require_2fa = isset($_SESSION['2fa_required']) && $_SESSION['2fa_required'];
        
        if ($require_2fa) {
            // Handle 2FA verification
            $user_id = $_SESSION['2fa_user_id'] ?: 0;
            handle2FAVerification($user_id, $verification_code, $backup_code);
        } else {
            // Handle regular login
            handleRegularLogin($email, $password, $remember);
        }
    }
}

function handleRegularLogin($email, $password, $remember) {
    global $conn, $error, $success;
    
    // Get user by email
    $sql = "SELECT u.*, us.two_factor_enabled 
            FROM users u 
            LEFT JOIN user_security us ON u.id = us.user_id 
            WHERE u.email = ? AND u.status = 'active'";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "s", $email);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $user = mysqli_fetch_assoc($result);
    
    if (!$user) {
        // User not found or not active
        logFailedLogin($email, 'User not found or inactive');
        $error = 'Invalid email or password';
        return;
    }
    
    // Verify password
    if (!password_verify($password, $user['password'])) {
        logFailedLogin($email, 'Invalid password', $user['id']);
        $error = 'Invalid email or password';
        return;
    }
    
    // Check if 2FA is enabled
    if ($user['two_factor_enabled']) {
        // Store user ID in session for 2FA verification
        $_SESSION['2fa_user_id'] = $user['id'];
        $_SESSION['2fa_required'] = true;
        $_SESSION['2fa_email'] = $email;
        $_SESSION['2fa_remember'] = $remember;
        
        // Redirect to 2FA verification page
        header("Location: login.php?step=2fa");
        exit();
    }
    
    // Complete login without 2FA
    completeLogin($user, $remember);
}

function handle2FAVerification($user_id, $verification_code, $backup_code) {
    global $conn, $error, $success;
    
    // Get user and 2FA secret
    $sql = "SELECT u.*, us.two_factor_secret, us.backup_codes 
            FROM users u 
            LEFT JOIN user_security us ON u.id = us.user_id 
            WHERE u.id = ?";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "i", $user_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $user = mysqli_fetch_assoc($result);
    
    if (!$user) {
        $error = 'Session expired. Please login again.';
        unset2FASession();
        return;
    }
    
    require_once 'vendor/autoload.php';
    //use Sonata\GoogleAuthenticator\GoogleAuthenticator;
    
    $g = new GoogleAuthenticator();
    $secret = $user['two_factor_secret'];
    $backup_codes = json_decode($user['backup_codes'] ?: '[]', true);
    
    $verified = false;
    
    // Try verification code
    if (!empty($verification_code) && $g->checkCode($secret, $verification_code)) {
        $verified = true;
    }
    // Try backup code
    elseif (!empty($backup_code) && in_array(strtoupper($backup_code), $backup_codes)) {
        $verified = true;
        // Remove used backup code
        $backup_codes = array_diff($backup_codes, [strtoupper($backup_code)]);
        updateBackupCodes($user_id, $backup_codes);
    }
    
    if ($verified) {
        $remember = $_SESSION['2fa_remember'] ?: false;
        completeLogin($user, $remember);
        unset2FASession();
    } else {
        $error = 'Invalid verification code';
        logFailedLogin($user['email'], 'Invalid 2FA code', $user_id);
    }
}

function completeLogin($user, $remember) {
    global $conn, $success;
    
    // Update last login
    $update_sql = "UPDATE users SET last_login = NOW() WHERE id = ?";
    $stmt = mysqli_prepare($conn, $update_sql);
    mysqli_stmt_bind_param($stmt, "i", $user['id']);
    mysqli_stmt_execute($stmt);
    
    // Set session variables
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['user_email'] = $user['email'];
    $_SESSION['user_name'] = $user['first_name'] . ' ' . $user['last_name'];
    $_SESSION['logged_in'] = true;
    $_SESSION['login_time'] = time();
    
    // Set remember me cookie if requested
    if ($remember) {
        $token = bin2hex(random_bytes(32));
        $expires = time() + (30 * 24 * 60 * 60); // 30 days
        
        // Store token in database
        $insert_sql = "INSERT INTO remember_tokens (user_id, token, expires_at) VALUES (?, ?, FROM_UNIXTIME(?))";
        $stmt = mysqli_prepare($conn, $insert_sql);
        mysqli_stmt_bind_param($stmt, "isi", $user['id'], $token, $expires);
        mysqli_stmt_execute($stmt);
        
        // Set cookie
        setcookie('remember_token', $token, $expires, '/', '', true, true);
        setcookie('user_id', $user['id'], $expires, '/', '', true, true);
    }
    
    // Record device info
    recordDevice($user['id']);
    
    // Log successful login
    logSuccessfulLogin($user['email'], $user['id']);
    
    // Send login notification if enabled
    sendLoginNotification($user);
    
    // Redirect to dashboard
    header("Location: index.php");
    exit();
}

function unset2FASession() {
    unset($_SESSION['2fa_user_id']);
    unset($_SESSION['2fa_required']);
    unset($_SESSION['2fa_email']);
    unset($_SESSION['2fa_remember']);
}

function recordDevice($user_id) {
    global $conn;
    
    $device_id = $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR'];
    $session_id = session_id();
    $device_name = getDeviceName();
    $browser = getBrowser1();
    $platform = getPlatform();
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $location = getLocation($ip_address);
    
    // Check if device exists
    $check_sql = "SELECT id FROM user_devices WHERE user_id = ? AND device_id = ?";
    $stmt = mysqli_prepare($conn, $check_sql);
    mysqli_stmt_bind_param($stmt, "is", $user_id, $device_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if (mysqli_num_rows($result) > 0) {
        // Update existing device
        $update_sql = "UPDATE user_devices SET 
                      session_id = ?, 
                      last_login = NOW(),
                      ip_address = ?,
                      location = ?
                      WHERE user_id = ? AND device_id = ?";
        $stmt = mysqli_prepare($conn, $update_sql);
        mysqli_stmt_bind_param($stmt, "sssis", $session_id, $ip_address, $location, $user_id, $device_id);
    } else {
        // Insert new device
        $insert_sql = "INSERT INTO user_devices 
                      (user_id, device_id, session_id, device_name, browser, platform, ip_address, location, created_at, last_login)
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
        $stmt = mysqli_prepare($conn, $insert_sql);
        mysqli_stmt_bind_param($stmt, "isssssss", $user_id, $device_id, $session_id, $device_name, $browser, $platform, $ip_address, $location);
    }
    
    mysqli_stmt_execute($stmt);
}

function logSuccessfulLogin($email, $user_id) {
    global $conn;
    
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $location = getLocation($ip_address);
    $browser = getBrowser1();
    $platform = getPlatform();
    
    $sql = "INSERT INTO user_login_history 
            (user_id, ip_address, location, browser, platform, success, login_time)
            VALUES (?, ?, ?, ?, ?, 1, NOW())";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "issss", $user_id, $ip_address, $location, $browser, $platform);
    mysqli_stmt_execute($stmt);
}

function logFailedLogin($email, $reason, $user_id = null) {
    global $conn;
    
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $location = getLocation($ip_address);
    $browser = getBrowser1();
    $platform = getPlatform();
    
    $sql = "INSERT INTO user_login_history 
            (user_id, ip_address, location, browser, platform, success, login_time)
            VALUES (?, ?, ?, ?, ?, 0, NOW())";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "issss", $user_id, $ip_address, $location, $browser, $platform);
    mysqli_stmt_execute($stmt);
}

function updateBackupCodes($user_id, $backup_codes) {
    global $conn;
    
    $backup_codes_json = json_encode(array_values($backup_codes));
    
    $sql = "UPDATE user_security SET backup_codes = ? WHERE user_id = ?";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "si", $backup_codes_json, $user_id);
    mysqli_stmt_execute($stmt);
}

function sendLoginNotification($user) {
    global $conn;
    
    // Check if notifications are enabled
    $sql = "SELECT notify_login FROM user_security WHERE user_id = ?";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "i", $user['id']);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $security = mysqli_fetch_assoc($result);
    
    if (!$security || $security['notify_login'] == 0) {
        return;
    }
    
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $location = getLocation($ip_address);
    $browser = getBrowser1();
    $platform = getPlatform();
    $time = date('Y-m-d H:i:s');
    
    $subject = "New Login to Your Account";
    $message = "Hello {$user['first_name']},\n\n";
    $message .= "There was a new login to your account:\n\n";
    $message .= "Time: $time\n";
    $message .= "IP Address: $ip_address\n";
    $message .= "Location: $location\n";
    $message .= "Browser: $browser\n";
    $message .= "Platform: $platform\n\n";
    $message .= "If this wasn't you, please change your password immediately and contact support.\n\n";
    $message .= "Best regards,\nAI Trading Platform";
    
    $headers = "From: security@yourdomain.com\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    
    mail($user['email'], $subject, $message, $headers);
}

function getDeviceName() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    
    if (strpos($user_agent, 'Mobile') !== false) {
        return 'Mobile Device';
    } elseif (strpos($user_agent, 'Tablet') !== false) {
        return 'Tablet';
    } else {
        return 'Desktop';
    }
}

function getBrowser1() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    
    if (strpos($user_agent, 'Chrome') !== false) return 'Chrome';
    if (strpos($user_agent, 'Firefox') !== false) return 'Firefox';
    if (strpos($user_agent, 'Safari') !== false) return 'Safari';
    if (strpos($user_agent, 'Edge') !== false) return 'Edge';
    if (strpos($user_agent, 'Opera') !== false) return 'Opera';
    if (strpos($user_agent, 'MSIE') !== false) return 'Internet Explorer';
    
    return 'Unknown';
}

function getPlatform() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    
    if (strpos($user_agent, 'Windows') !== false) return 'Windows';
    if (strpos($user_agent, 'Mac') !== false) return 'Mac';
    if (strpos($user_agent, 'Linux') !== false) return 'Linux';
    if (strpos($user_agent, 'Android') !== false) return 'Android';
    if (strpos($user_agent, 'iPhone') !== false) return 'iOS';
    if (strpos($user_agent, 'iPad') !== false) return 'iOS';
    
    return 'Unknown';
}

function getLocation($ip) {
    // Using ipinfo.io API (free tier)
    // Sign up at https://ipinfo.io/signup for your own token
    $token = 'YOUR_IPINFO_TOKEN'; // Replace with your token
    
    $url = "https://ipinfo.io/{$ip}?token={$token}";
    $response = @file_get_contents($url);
    
    if ($response) {
        $data = json_decode($response, true);
        if (isset($data['city']) && isset($data['country'])) {
            return $data['city'] . ', ' . $data['country'];
        }
    }
    
    return 'Unknown location';
}

// Handle remember me on page load
if (!isset($_SESSION['user_id']) && isset($_COOKIE['remember_token']) && isset($_COOKIE['user_id'])) {
    $token = $_COOKIE['remember_token'];
    $user_id = intval($_COOKIE['user_id']);
    
    $sql = "SELECT u.* FROM users u 
            JOIN remember_tokens rt ON u.id = rt.user_id 
            WHERE u.id = ? AND rt.token = ? AND rt.expires_at > NOW() AND u.status = 'active'";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "is", $user_id, $token);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $user = mysqli_fetch_assoc($result);
    
    if ($user) {
        // Check if 2FA is enabled
        $security_sql = "SELECT two_factor_enabled FROM user_security WHERE user_id = ?";
        $stmt2 = mysqli_prepare($conn, $security_sql);
        mysqli_stmt_bind_param($stmt2, "i", $user_id);
        mysqli_stmt_execute($stmt2);
        $result2 = mysqli_stmt_get_result($stmt2);
        $security = mysqli_fetch_assoc($result2);
        
        if ($security && $security['two_factor_enabled']) {
            // 2FA required even with remember me
            $_SESSION['2fa_user_id'] = $user['id'];
            $_SESSION['2fa_required'] = true;
            $_SESSION['2fa_email'] = $user['email'];
            $_SESSION['2fa_remember'] = true;
            header("Location: login.php?step=2fa");
            exit();
        } else {
            // Complete login
            completeLogin($user, true);
        }
    } else {
        // Invalid token, clear cookies
        setcookie('remember_token', '', time() - 3600, '/');
        setcookie('user_id', '', time() - 3600, '/');
    }
}
?>
<!DOCTYPE html>
<html lang="en" data-bs-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - AI Trading Platform</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Custom CSS -->
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .login-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
            max-width: 420px;
            width: 100%;
        }
        
        .login-header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px 20px;
            text-align: center;
        }
        
        .login-header i {
            font-size: 3rem;
            margin-bottom: 15px;
        }
        
        .login-body {
            padding: 30px;
        }
        
        .form-control {
            padding: 12px 15px;
            border-radius: 8px;
            border: 2px solid #e9ecef;
            transition: all 0.3s;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .btn-login {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: white;
            padding: 12px;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .alert {
            border-radius: 8px;
            border: none;
        }
        
        .form-check-input:checked {
            background-color: #667eea;
            border-color: #667eea;
        }
        
        .login-footer {
            text-align: center;
            padding: 20px;
            border-top: 1px solid #e9ecef;
            background: #f8f9fa;
        }
        
        .login-footer a {
            color: #667eea;
            text-decoration: none;
        }
        
        .login-footer a:hover {
            text-decoration: underline;
        }
        
        .qr-code-container {
            text-align: center;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .backup-code-hint {
            font-size: 0.875rem;
            color: #6c757d;
            margin-top: 5px;
        }
        
        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 30px;
        }
        
        .step {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            margin: 0 10px;
        }
        
        .step.active {
            background: #667eea;
            color: white;
        }
        
        .step-line {
            flex: 1;
            height: 2px;
            background: #e9ecef;
            margin: 0 5px;
            align-self: center;
        }
        
        .step-label {
            text-align: center;
            font-size: 0.875rem;
            color: #6c757d;
            margin-top: 5px;
        }
        
        .theme-toggle {
            position: fixed;
            top: 20px;
            right: 20px;
        }
        
        @media (max-width: 576px) {
            .login-card {
                margin: 10px;
            }
            
            .login-body {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <!-- Theme Toggle -->
    <div class="theme-toggle">
        <button class="btn btn-outline-light" id="themeToggle">
            <i class="fas fa-moon" id="themeIcon"></i>
        </button>
    </div>

    <!-- Login Card -->
    <div class="login-card">
        <div class="login-header">
            <i class="fas fa-robot"></i>
            <h2>AI Trading Platform</h2>
            <p>Secure Login System</p>
        </div>
        
        <?php if (isset($_GET['step']) && $_GET['step'] === '2fa'): ?>
        <!-- 2FA Verification Step -->
        <div class="login-body">
            <div class="step-indicator">
                <div class="step">1</div>
                <div class="step-line"></div>
                <div class="step active">2</div>
            </div>
            <div class="step-label">
                <span>Credentials</span>
                <span>2FA Verification</span>
            </div>
            
            <h4 class="mb-4 text-center">Two-Factor Authentication</h4>
            <p class="text-muted text-center mb-4">
                Enter the 6-digit code from your authenticator app
            </p>
            
            <?php if ($error): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo htmlspecialchars($error); ?>
            </div>
            <?php endif; ?>
            
            <form method="POST" action="login.php">
                <input type="hidden" name="email" value="<?php echo htmlspecialchars($_SESSION['2fa_email'] ?: ''); ?>">
                
                <div class="mb-4">
                    <label class="form-label">Verification Code</label>
                    <div class="input-group">
                        <span class="input-group-text">
                            <i class="fas fa-key"></i>
                        </span>
                        <input type="text" 
                               class="form-control" 
                               name="verification_code" 
                               maxlength="6" 
                               pattern="[0-9]{6}"
                               placeholder="000000"
                               required
                               autocomplete="off"
                               autofocus>
                    </div>
                    <div class="backup-code-hint">
                        <a href="#" onclick="showBackupCodeField()">Use backup code instead</a>
                    </div>
                </div>
                
                <div class="mb-4" id="backupCodeField" style="display: none;">
                    <label class="form-label">Backup Code</label>
                    <div class="input-group">
                        <span class="input-group-text">
                            <i class="fas fa-key"></i>
                        </span>
                        <input type="text" 
                               class="form-control" 
                               name="backup_code" 
                               maxlength="8"
                               placeholder="ABCD-1234"
                               autocomplete="off">
                    </div>
                </div>
                
                <div class="d-grid mb-3">
                    <button type="submit" class="btn btn-login">
                        <i class="fas fa-shield-check me-2"></i>
                        Verify & Login
                    </button>
                </div>
                
                <div class="text-center">
                    <a href="login.php" class="text-decoration-none">
                        <i class="fas fa-arrow-left me-1"></i>
                        Back to login
                    </a>
                </div>
            </form>
        </div>
        
        <?php else: ?>
        <!-- Regular Login Step -->
        <div class="login-body">
            <div class="step-indicator">
                <div class="step active">1</div>
                <div class="step-line"></div>
                <div class="step">2</div>
            </div>
            <div class="step-label">
                <span>Credentials</span>
                <span>2FA Verification</span>
            </div>
            
            <h4 class="mb-4 text-center">Welcome Back</h4>
            
            <?php if ($error): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo htmlspecialchars($error); ?>
            </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle me-2"></i>
                <?php echo htmlspecialchars($success); ?>
            </div>
            <?php endif; ?>
            
            <form method="POST" action="login.php">
                <div class="mb-3">
                    <label class="form-label">Email Address</label>
                    <div class="input-group">
                        <span class="input-group-text">
                            <i class="fas fa-envelope"></i>
                        </span>
                        <input type="email" 
                               class="form-control" 
                               name="email" 
                               value="<?php echo htmlspecialchars($email); ?>"
                               placeholder="you@example.com"
                               required
                               autocomplete="email"
                               autofocus>
                    </div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Password</label>
                    <div class="input-group">
                        <span class="input-group-text">
                            <i class="fas fa-lock"></i>
                        </span>
                        <input type="password" 
                               class="form-control" 
                               name="password" 
                               placeholder="••••••••"
                               required
                               autocomplete="current-password">
                        <button class="btn btn-outline-secondary" type="button" id="togglePassword">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>
                
                <div class="mb-4">
                    <div class="form-check">
                        <input class="form-check-input" 
                               type="checkbox" 
                               name="remember" 
                               id="remember"
                               <?php echo $remember ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="remember">
                            Remember me for 30 days
                        </label>
                    </div>
                </div>
                
                <div class="d-grid mb-3">
                    <button type="submit" class="btn btn-login">
                        <i class="fas fa-sign-in-alt me-2"></i>
                        Login to Account
                    </button>
                </div>
                
                <div class="text-center mb-4">
                    <a href="forgot-password.php" class="text-decoration-none">
                        <i class="fas fa-key me-1"></i>
                        Forgot password?
                    </a>
                </div>
            </form>
        </div>
        <?php endif; ?>
        
        <div class="login-footer">
            <p class="mb-0">
                Don't have an account? 
                <a href="register.php">Sign up now</a>
            </p>
            <p class="mt-2 mb-0">
                <a href="index.php">
                    <i class="fas fa-home me-1"></i>
                    Back to home
                </a>
            </p>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
    // Toggle password visibility
    document.getElementById('togglePassword')?.addEventListener('click', function() {
        const passwordInput = document.querySelector('input[name="password"]');
        const icon = this.querySelector('i');
        
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            passwordInput.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
    });
    
    // Show backup code field
    function showBackupCodeField() {
        document.getElementById('backupCodeField').style.display = 'block';
        document.querySelector('input[name="backup_code"]').focus();
        return false;
    }
    
    // Theme toggle
    document.getElementById('themeToggle').addEventListener('click', function() {
        const html = document.documentElement;
        const currentTheme = html.getAttribute('data-bs-theme');
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
        
        html.setAttribute('data-bs-theme', newTheme);
        
        const icon = document.getElementById('themeIcon');
        icon.className = newTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
        
        // Save preference
        document.cookie = `theme=${newTheme}; path=/; max-age=31536000`;
    });
    
    // Set initial theme
    const savedTheme = document.cookie.split('; ').find(row => row.startsWith('theme='));
    if (savedTheme) {
        const theme = savedTheme.split('=')[1];
        document.documentElement.setAttribute('data-bs-theme', theme);
        document.getElementById('themeIcon').className = theme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
    }
    
    // Auto-focus verification code input
    const verificationCodeInput = document.querySelector('input[name="verification_code"]');
    if (verificationCodeInput) {
        verificationCodeInput.focus();
        
        // Auto-submit on 6 digits
        verificationCodeInput.addEventListener('input', function() {
            if (this.value.length === 6) {
                this.form.submit();
            }
        });
    }
    
    // Show security tips for new visitors
    if (!localStorage.getItem('loginSecurityTipsShown')) {
        setTimeout(() => {
            Swal.fire({
                title: 'Security Tips',
                html: `
                    <div class="text-start">
                        <p><i class="fas fa-shield-alt text-primary me-2"></i> Enable 2FA for extra security</p>
                        <p><i class="fas fa-lock text-success me-2"></i> Use a strong, unique password</p>
                        <p><i class="fas fa-desktop text-warning me-2"></i> Only login on trusted devices</p>
                        <p><i class="fas fa-bell text-info me-2"></i> Enable login notifications</p>
                    </div>
                `,
                icon: 'info',
                confirmButtonText: 'Got it!',
                showCloseButton: true
            });
            localStorage.setItem('loginSecurityTipsShown', 'true');
        }, 1000);
    }
    
    // Handle enter key for 2FA verification
    document.addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && document.querySelector('input[name="verification_code"]')) {
            const form = document.querySelector('form');
            if (form.checkValidity()) {
                form.submit();
            }
        }
    });
    </script>
</body>
</html>