<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'account/include/db.php'; 

$error = '';

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

$user_theme = isset($_SESSION['theme']) ? $_SESSION['theme'] : '#0ea5e9';

// Handle standard login
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['login'])) {
    $login_id = mysqli_real_escape_string($conn, $_POST['login_id']);
    $password = $_POST['password'];

    $sql = "SELECT `id`, `username`, `full_name`, `email`, `password`, `balance`, `theme`, `created_at`, `biometric_enabled`, `biometric_id` 
            FROM `users` 
            WHERE `email` = '$login_id' OR `username` = '$login_id' LIMIT 1";
            
    $result = mysqli_query($conn, $sql);

    if ($result && mysqli_num_rows($result) > 0) {
        $user = mysqli_fetch_assoc($result);
        
        if ($password == $user['password']) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['theme'] = $user['theme'] ? $user['theme'] : '#0ea5e9'; 
            
            header("Location: account/dashboard.php");
            exit;
        } else {
            $error = "Invalid password.";
        }
    } else {
        $error = "User not found.";
    }
}

// ============================================
// FIXED: AJAX Biometric Login Verification
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action']) && $_POST['ajax_action'] === 'verify_biometric_login') {
    header('Content-Type: application/json');
    
    $credentialId = mysqli_real_escape_string($conn, $_POST['credential_id'] ?? '');
    
    if (empty($credentialId)) {
        echo json_encode(['success' => false, 'message' => 'No biometric credential provided.']);
        exit;
    }
    
    // Look up user by biometric credential ID
    // The credential_id stored in DB was base64 encoded during registration
    $checkSql = "SELECT `id`, `username`, `full_name`, `email`, `theme`, `biometric_enabled` 
                 FROM `users` 
                 WHERE `biometric_enabled` = 1 
                 AND `biometric_id` = '$credentialId' 
                 LIMIT 1";
                 
    $checkResult = mysqli_query($conn, $checkSql);
    
    if ($checkResult && mysqli_num_rows($checkResult) > 0) {
        $bioUser = mysqli_fetch_assoc($checkResult);
        
        // Set session variables
        $_SESSION['user_id'] = $bioUser['id'];
        $_SESSION['username'] = $bioUser['username'];
        $_SESSION['theme'] = $bioUser['theme'] ? $bioUser['theme'] : '#0ea5e9';
        
        echo json_encode([
            'success' => true, 
            'redirect' => 'account/dashboard.php',
            'message' => 'Biometric authentication successful'
        ]);
    } else {
        echo json_encode([
            'success' => false, 
            'message' => 'Biometric credential not recognized. Please register biometrics in your profile settings first, or use your password to log in.'
        ]);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Theinteractivebrokers</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        :root {
            --primary-color: <?php echo $user_theme; ?>; 
            --bg-body: #0b111a;
            --bg-card: #121a24;
            --text-main: #ffffff;
            --text-muted: #8b9bb4;
            --input-bg: #1c2635;
            --border-color: #2a3749;
        }

        body.light-mode {
            --bg-body: #f3f4f6;
            --bg-card: #ffffff;
            --text-main: #111827;
            --text-muted: #6b7280;
            --input-bg: #f9fafb;
            --border-color: #e5e7eb;
        }

        * { box-sizing: border-box; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        
        body {
            background-color: var(--bg-body);
            color: var(--text-main);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            transition: background-color 0.3s, color 0.3s;
        }

        .theme-toggle {
            position: absolute;
            top: 20px;
            right: 30px;
            cursor: pointer;
            font-size: 1.2rem;
            color: var(--text-muted);
        }

        .translator-container {
            position: absolute;
            bottom: 20px;
            left: 20px;
            background: var(--bg-card);
            padding: 5px;
            border-radius: 5px;
            border: 1px solid var(--border-color);
        }

        .login-card {
            background-color: var(--bg-card);
            padding: 40px;
            border-radius: 12px;
            width: 100%;
            max-width: 450px;
            border: 1px solid var(--border-color);
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
            text-align: center;
        }

        .logo-area h1 { margin: 10px 0 5px; font-size: 1.5rem; }
        .logo-area h2 { margin: 0; color: var(--primary-color); font-size: 1.2rem; font-weight: 600; }
        .logo-area p { color: var(--text-muted); font-size: 0.9rem; margin-bottom: 25px; }

        .indicators {
            display: flex;
            justify-content: center;
            gap: 20px;
            font-size: 0.75rem;
            margin-bottom: 30px;
            color: var(--text-muted);
        }
        .indicators span i { color: var(--primary-color); margin-right: 5px; }

        .form-group {
            text-align: left;
            margin-bottom: 20px;
            position: relative;
        }
        .form-group label {
            display: block;
            font-size: 0.85rem;
            margin-bottom: 8px;
            color: var(--text-main);
        }
        .input-wrapper {
            position: relative;
            display: flex;
            align-items: center;
            background: var(--input-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            overflow: hidden;
            transition: border 0.3s;
        }
        .input-wrapper:focus-within { border-color: var(--primary-color); }
        .input-wrapper i.icon-left { padding: 0 15px; color: var(--text-muted); }
        .input-wrapper input {
            flex: 1;
            background: transparent;
            border: none;
            padding: 12px 10px;
            color: var(--text-main);
            outline: none;
        }
        .input-wrapper .icon-right {
            padding: 0 15px;
            color: var(--text-muted);
            cursor: pointer;
        }

        .btn-submit {
            width: 100%;
            background: var(--primary-color);
            color: #fff;
            border: none;
            padding: 14px;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: opacity 0.3s;
        }
        .btn-submit:hover { opacity: 0.9; }

        .error-msg { color: #ef4444; font-size: 0.85rem; margin-bottom: 15px; }

        .divider {
            display: flex;
            align-items: center;
            text-align: center;
            margin: 25px 0;
            color: var(--text-muted);
            font-size: 0.85rem;
        }
        .divider::before, .divider::after {
            content: '';
            flex: 1;
            border-bottom: 1px solid var(--border-color);
        }
        .divider:not(:empty)::before { margin-right: .25em; }
        .divider:not(:empty)::after { margin-left: .25em; }

        .quick-access {
            display: flex;
            justify-content: center;
            gap: 15px;
        }
        .quick-btn {
            background: var(--input-bg);
            border: 1px solid var(--border-color);
            color: var(--text-main);
            width: 50px;
            height: 50px;
            border-radius: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            font-size: 1.2rem;
            transition: all 0.3s;
        }
        .quick-btn:hover { 
            border-color: var(--primary-color); 
            color: var(--primary-color);
            transform: translateY(-2px);
        }
        .quick-btn:active { transform: translateY(0); }

        .footer-links { margin-top: 30px; font-size: 0.85rem; color: var(--text-muted); }
        .footer-links a { color: var(--primary-color); text-decoration: none; }
        
        .security-footer {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 20px;
            font-size: 0.7rem;
            color: var(--text-muted);
        }
        .security-footer i { color: #10b981; }

        #reader { width: 100%; display: none; margin-top: 15px; border-radius: 8px; overflow: hidden; }
    </style>
</head>
<body>

    <div class="theme-toggle" onclick="toggleTheme()">
        <i class="fa-solid fa-moon" id="theme-icon"></i>
    </div>

    <div class="translator-container">
        <div id="google_translate_element"></div>
    </div>

    <div class="login-card">
        <div class="logo-area">
            <img src="account/logo.png" alt="Logo" style="height: 30px; filter: drop-shadow(0px 0px 1px white);">
            <h1>Welcome Back</h1>
            <h2>Theinteractivebrokers</h2>
            <p>Access your trading dashboard</p>
        </div>

        <div class="indicators">
            <span><i class="fa-solid fa-circle"></i> Live 24/7 Markets</span>
            <span><i class="fa-solid fa-bolt"></i> Fast Execution</span>
            <span><i class="fa-solid fa-shield-halved"></i> Secure Platform</span>
        </div>

        <?php if($error): ?>
            <div class="error-msg"><?php echo $error; ?></div>
        <?php endif; ?>

        <form method="POST" action="">
            <div class="form-group">
                <label>Email Address or Username</label>
                <div class="input-wrapper">
                    <i class="fa-regular fa-envelope icon-left"></i>
                    <input type="text" name="login_id" id="login_id" placeholder="user@gmail.com" required>
                </div>
            </div>

            <div class="form-group">
                <label>Password</label>
                <div class="input-wrapper">
                    <i class="fa-solid fa-lock icon-left"></i>
                    <input type="password" name="password" id="password" placeholder="••••••" required>
                    <i class="fa-regular fa-eye icon-right" onclick="togglePassword()"></i>
                </div>
            </div>

            <button type="submit" name="login" class="btn-submit">
                <i class="fa-solid fa-arrow-right-to-bracket"></i> Access Dashboard
            </button>
        </form>

        <div class="divider">Quick Access</div>

        <div class="quick-access">
            <button class="quick-btn" onclick="triggerBiometrics()" title="Fingerprint / Face ID Login">
                <i class="fa-solid fa-fingerprint"></i>
            </button>
            <button class="quick-btn" onclick="startQRScanner()" title="QR Code Login">
                <i class="fa-solid fa-qrcode"></i>
            </button>
        </div>

        <div id="reader"></div>

        <div class="footer-links">
            New to trading? <a href="register.php">Create your account</a>
        </div>

        <div class="security-footer">
            <span><i class="fa-solid fa-shield-check"></i> SSL Secured</span>
            <span><i class="fa-solid fa-lock"></i> 256-bit Encryption</span>
            <span><i class="fa-solid fa-building-columns"></i> Regulated</span>
        </div>
    </div>

    <script type="text/javascript">
        function googleTranslateElementInit() {
            new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
        }
    </script>
    <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
    <script src="https://unpkg.com/html5-qrcode"></script>

    <script>
        function toggleTheme() {
            const body = document.body;
            const icon = document.getElementById('theme-icon');
            body.classList.toggle('light-mode');
            
            if (body.classList.contains('light-mode')) {
                icon.classList.remove('fa-moon');
                icon.classList.add('fa-sun');
            } else {
                icon.classList.remove('fa-sun');
                icon.classList.add('fa-moon');
            }
        }

        function togglePassword() {
            const pwdInput = document.getElementById('password');
            const icon = document.querySelector('.icon-right');
            
            if (pwdInput.type === 'password') {
                pwdInput.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                pwdInput.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }

        // ============================================
        // FIXED BIOMETRIC LOGIN WITH SWEETALERT2
        // ============================================
        async function triggerBiometrics() {
            if (!window.PublicKeyCredential) {
                Swal.fire({
                    icon: 'error',
                    title: 'Not Supported',
                    text: 'Your browser does not support biometric authentication. Please use Chrome, Safari, Edge, or Firefox.',
                    confirmButtonColor: '#ef4444',
                    background: document.body.classList.contains('light-mode') ? '#ffffff' : '#121a24',
                    color: document.body.classList.contains('light-mode') ? '#111827' : '#ffffff'
                });
                return;
            }

            try {
                const available = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
                if (!available) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'No Biometric Sensor',
                        text: 'Your device does not have a built-in biometric sensor (Fingerprint/Face ID).',
                        confirmButtonColor: '#f59e0b',
                        background: document.body.classList.contains('light-mode') ? '#ffffff' : '#121a24',
                        color: document.body.classList.contains('light-mode') ? '#111827' : '#ffffff'
                    });
                    return;
                }

                Swal.fire({
                    title: 'Authenticating...',
                    text: 'Please use your fingerprint or Face ID to log in',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    showConfirmButton: false,
                    didOpen: () => { Swal.showLoading(); },
                    background: document.body.classList.contains('light-mode') ? '#ffffff' : '#121a24',
                    color: document.body.classList.contains('light-mode') ? '#111827' : '#ffffff'
                });

                const challenge = new Uint8Array(32);
                window.crypto.getRandomValues(challenge);

                const publicKeyCredentialRequestOptions = {
                    challenge: challenge,
                    timeout: 60000,
                    userVerification: "required",
                    rpId: window.location.hostname,
                    allowCredentials: []
                };

                const assertion = await navigator.credentials.get({
                    publicKey: publicKeyCredentialRequestOptions
                });

                if (assertion) {
                    const credentialId = btoa(String.fromCharCode(...new Uint8Array(assertion.rawId)));
                    
                    const formData = new FormData();
                    formData.append('ajax_action', 'verify_biometric_login');
                    formData.append('credential_id', credentialId);

                    const response = await fetch('', {
                        method: 'POST',
                        body: formData
                    });

                    const result = await response.json();

                    if (result.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Welcome Back!',
                            text: 'Biometric authentication successful. Redirecting...',
                            timer: 1500,
                            showConfirmButton: false,
                            background: document.body.classList.contains('light-mode') ? '#ffffff' : '#121a24',
                            color: document.body.classList.contains('light-mode') ? '#111827' : '#ffffff'
                        });
                        
                        setTimeout(() => {
                            window.location.href = result.redirect || 'account/dashboard.php';
                        }, 1500);
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Authentication Failed',
                            text: result.message || 'Biometric credential not recognized. Please use your password.',
                            confirmButtonColor: '#ef4444',
                            background: document.body.classList.contains('light-mode') ? '#ffffff' : '#121a24',
                            color: document.body.classList.contains('light-mode') ? '#111827' : '#ffffff'
                        });
                    }
                }

            } catch (err) {
                console.error("Biometric Error:", err);
                
                let errorTitle = 'Authentication Cancelled';
                let errorText = 'Biometric login was cancelled or failed.';
                let iconType = 'error';

                if (err.name === 'NotAllowedError') {
                    errorText = 'Permission denied. Please allow biometric access in your browser settings.';
                } else if (err.name === 'SecurityError') {
                    errorText = 'Security error. Make sure you are on a secure connection (HTTPS).';
                } else if (err.name === 'AbortError') {
                    errorTitle = 'Cancelled';
                    errorText = 'You cancelled the biometric prompt.';
                    iconType = 'info';
                }

                Swal.fire({
                    icon: iconType,
                    title: errorTitle,
                    text: errorText,
                    confirmButtonColor: '#ef4444',
                    background: document.body.classList.contains('light-mode') ? '#ffffff' : '#121a24',
                    color: document.body.classList.contains('light-mode') ? '#111827' : '#ffffff'
                });
            }
        }

        function startQRScanner() {
            const readerDiv = document.getElementById('reader');
            readerDiv.style.display = 'block';

            const html5QrCode = new Html5Qrcode("reader");
            const config = { fps: 10, qrbox: { width: 250, height: 250 } };

            html5QrCode.start({ facingMode: "environment" }, config, 
            (decodedText, decodedResult) => {
                html5QrCode.stop();
                readerDiv.style.display = 'none';
                document.getElementById('login_id').value = decodedText;
                
                Swal.fire({
                    icon: 'success',
                    title: 'QR Code Scanned',
                    text: 'ID placed in input field. Please enter your password.',
                    timer: 2000,
                    showConfirmButton: false,
                    background: document.body.classList.contains('light-mode') ? '#ffffff' : '#121a24',
                    color: document.body.classList.contains('light-mode') ? '#111827' : '#ffffff'
                });
            },
            (errorMessage) => {}).catch((err) => {
                Swal.fire({
                    icon: 'error',
                    title: 'Camera Error',
                    text: 'Camera permission denied or camera not found.',
                    confirmButtonColor: '#ef4444',
                    background: document.body.classList.contains('light-mode') ? '#ffffff' : '#121a24',
                    color: document.body.classList.contains('light-mode') ? '#111827' : '#ffffff'
                });
                readerDiv.style.display = 'none';
            });
        }
    </script>
</body>
</html>