<?php
require_once 'includes/init.php';

$error = '';
$user = new User($pdo);

// Redirect if already logged in
if ($user->isLoggedIn()) {
    if ($user->isAdmin()) {
        header("Location: admin/dashboard.php");
    } else {
        header("Location: student/dashboard.php");
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    
    // Check if it's a PIN login (username has value, password empty) or standard login
    // Actually, let's allow a separate field or just check if password is empty?
    // User requirement: "Access via username/password or the generated Access PIN."
    
    // Let's assume if password is empty, we treat username field as PIN? 
    // Or we can add a toggle. For simplicity, let's check if the input looks like a PIN (numeric) and password is empty?
    // Better: Add a separate tab or just a unified login.
    
    // Let's try to login with username/password first
    if (!empty($password)) {
        if ($user->login($username, $password)) {
            try {
                $uid = $_SESSION['user_id'];
                $stmtLog = $pdo->prepare("INSERT INTO student_activity_log (user_id, activity) VALUES (?, ?)");
                $stmtLog->execute([$uid, 'login']);
            } catch(Exception $e) {}
            if ($user->isTeacher()) {
                header("Location: admin/dashboard.php");
            } else {
                header("Location: student/dashboard.php");
            }
            exit;
        } else {
            $error = "Invalid username or password.";
        }
    } else {
        // Try as PIN (using username field)
        if ($user->login($username)) {
            try {
                $uid = $_SESSION['user_id'];
                $stmtLog = $pdo->prepare("INSERT INTO student_activity_log (user_id, activity) VALUES (?, ?)");
                $stmtLog->execute([$uid, 'login']);
            } catch(Exception $e) {}
             if ($user->isTeacher()) {
                header("Location: admin/dashboard.php");
            } else {
                header("Location: student/dashboard.php");
            }
            exit;
        } else {
             $error = "Invalid Access PIN.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CBT Login</title>
    <style>
        body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f4f4f4; }
        .login-container { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); width: 300px; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; }
        .form-group input { width: 100%; padding: 8px; box-sizing: border-box; }
        .btn { width: 100%; padding: 10px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
        .btn:hover { background: #0056b3; }
        .error { color: red; margin-bottom: 10px; }
        .toggle-login { text-align: center; margin-top: 10px; font-size: 0.9em; }
        .toggle-login a { color: #007bff; cursor: pointer; text-decoration: underline; }
    </style>
    <script>
        function toggleLogin(type) {
            const userPassForm = document.getElementById('user-pass-form');
            const pinForm = document.getElementById('pin-form');
            if (type === 'pin') {
                userPassForm.style.display = 'none';
                pinForm.style.display = 'block';
            } else {
                userPassForm.style.display = 'block';
                pinForm.style.display = 'none';
            }
        }
    </script>
</head>
<body>
    <?php include 'includes/loader.php'; ?>
    <div class="login-container">
        <h2 style="text-align: center;">CBT Login</h2>
        <?php if ($error): ?>
            <div class="error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <div id="user-pass-form">
            <form method="POST" action="">
                <div class="form-group">
                    <label>Username</label>
                    <input type="text" name="username">
                </div>
                <div class="form-group">
                    <label>Password</label>
                    <input type="password" name="password">
                </div>
                <button type="submit" class="btn">Login</button>
            </form>
            <div class="toggle-login">
                <a onclick="toggleLogin('pin')">Login with Access PIN</a>
            </div>
        </div>

        <div id="pin-form" style="display:none;">
            <form method="POST" action="">
                <div class="form-group">
                    <label>Access PIN</label>
                    <input type="text" name="username" placeholder="Enter PIN">
                    <input type="hidden" name="password" value="">
                </div>
                <button type="submit" class="btn">Login with PIN</button>
            </form>
             <div class="toggle-login">
                <a onclick="toggleLogin('user')">Login with Username/Password</a>
            </div>
        </div>
    </div>
    <script>
        (function(){
            const userForm = document.querySelector('#user-pass-form form');
            const pinForm = document.querySelector('#pin-form form');
            function hook(form) {
                if (!form) return;
                form.addEventListener('submit', function(){
                    const loader = document.getElementById('global-loader');
                    if (loader) {
                        loader.classList.remove('hidden');
                        loader.style.display = 'flex';
                    }
                });
            }
            hook(userForm);
            hook(pinForm);
        })();
    </script>
</body>
</html>
