<?php
// login.php – hardened auth with rate limiting + CSRF + session regen
require_once __DIR__ . '/auth.php';

// If already logged in, send them home.
if (current_user()) {
    header('Location: dashboard.php');
    exit;
}

$error  = '';
$notice = '';

if (isset($_GET['reason']) && $_GET['reason'] === 'idle') {
    $notice = 'You were signed out due to inactivity. Please log in again.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_require();

    $username = v_clean_string($_POST['username'] ?? '', 100);
    $password = (string) ($_POST['password'] ?? '');
    $ip       = $_SERVER['REMOTE_ADDR'] ?? '';

    if ($username === '' || $password === '') {
        $error = 'Username and password are required.';
    } elseif (login_is_locked($pdo, $username, $ip)) {
        $error = 'Too many failed attempts. Try again in ' . login_lockout_minutes() . ' minutes.';
        audit_log($pdo, 'login_locked', ['username' => $username, 'ip' => $ip]);
    } else {
        $stmt = $pdo->prepare('SELECT * FROM users WHERE username = ? LIMIT 1');
        $stmt->execute([$username]);
        $u = $stmt->fetch();

        if ($u && (int)$u['active'] === 1 && password_verify($password, $u['password_hash'])) {
            // Optional: rehash if algorithm parameters have changed.
            if (password_needs_rehash($u['password_hash'], PASSWORD_DEFAULT)) {
                $newHash = password_hash($password, PASSWORD_DEFAULT);
                $pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ?')->execute([$newHash, $u['id']]);
            }
            login_attempt_success($pdo, $username, $ip);
            auth_login_user($pdo, $u);
            header('Location: dashboard.php');
            exit;
        }

        // Constant-time-ish path on miss
        if ($u) {
            // user exists but wrong password OR account disabled
            login_attempt_failed($pdo, $username, $ip);
            audit_log($pdo, 'login_failed', [
                'username' => $username,
                'reason'   => (int)$u['active'] === 0 ? 'disabled' : 'bad_password',
            ]);
        } else {
            // burn a few microseconds either way
            password_verify($password, '$2y$10$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123');
            login_attempt_failed($pdo, $username, $ip);
            audit_log($pdo, 'login_failed', ['username' => $username, 'reason' => 'no_user']);
        }

        $error = 'Invalid username or password.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>OSCE Nexus™ – Sign in</title>
<link rel="stylesheet" href="assets/css/app.css">
<style>
.login-shell { min-height: 90vh; display: flex; align-items: center; justify-content: center; padding: 16px; }
.login-card  { width: 100%; max-width: 420px; background: #fff; padding: 28px; border-radius: 10px; box-shadow: var(--shadow-lg); }
.login-card h1 { margin: 0 0 4px; }
.login-card .sub { color: var(--c-muted); margin: 0 0 18px; font-size: 14px; }
</style>
</head>
<body>
<div class="login-shell">
  <div class="login-card">
    <h1>OSCE Nexus™</h1>
    <p class="sub">Smart OSCE grading &amp; candidate management.<br>Developed by <strong>Khalaf Almazrouei</strong></p>

    <?php if ($notice): ?><div class="alert alert-info"><?php echo h($notice); ?></div><?php endif; ?>
    <?php if ($error):  ?><div class="alert alert-danger"><?php echo h($error); ?></div><?php endif; ?>

    <form method="post" autocomplete="on">
      <?php echo csrf_field(); ?>
      <div class="field mb-2">
        <label for="u">Username</label>
        <input type="text" id="u" name="username" required autocomplete="username" autofocus>
      </div>
      <div class="field mb-2">
        <label for="p">Password</label>
        <input type="password" id="p" name="password" required autocomplete="current-password">
      </div>
      <button type="submit" class="btn btn-primary btn-lg" style="width:100%;">Sign in</button>
    </form>

    <div style="text-align:center; margin:14px 0; color:#94a3b8; font-size:13px;">— or —</div>

    <a href="face_login.php" class="btn btn-lg" style="width:100%; display:block; text-align:center; background:#0f172a; color:#f1f5f9; border-color:#0f172a;">
        📷 Sign in with face
    </a>

    <small class="copyright">
      &copy; <?php echo date('Y'); ?> Khalaf Almazrouei. All Rights Reserved.<br>
      OSCE Nexus™ – Unauthorized access is prohibited.
    </small>
  </div>
</div>
</body>
</html>
