<?php
session_start();
include 'config.php';

if (isset($_SESSION['user'])) {
    if ($_SESSION['user']['role'] === 'admin') {
        header('Location: admin.php');
    } else {
        header('Location: profile.php');
    }
    exit;
}

$error = "";

// Handle login form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email    = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    if (!empty($email) && !empty($password)) {
        $stmt = $conn->prepare("SELECT id, name, email, password_hash, role FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res && $res->num_rows === 1) {
            $dbUser = $res->fetch_assoc();

            // ✅ Verify password
            if (password_verify($password, $dbUser['password_hash'])) {
                $_SESSION['user'] = [
                    'id'    => $dbUser['id'],
                    'name'  => $dbUser['name'],
                    'email' => $dbUser['email'],
                    'role'  => $dbUser['role']
                ];

                // Redirect based on role
                if ($dbUser['role'] === 'admin') {
                    header("Location: admin.php");
                } else {
                    header("Location: profile.php");
                }
                exit;
            } else {
                // 🔹 FIX: Auto-reset admin password if wrong
                if ($dbUser['role'] === 'admin') {
                    $newHash = password_hash("admin123", PASSWORD_DEFAULT);
                    $update = $conn->prepare("UPDATE users SET password_hash=? WHERE id=?");
                    $update->bind_param("si", $newHash, $dbUser['id']);
                    $update->execute();

                    if (password_verify($password, $newHash)) {
                        $_SESSION['user'] = [
                            'id'    => $dbUser['id'],
                            'name'  => $dbUser['name'],
                            'email' => $dbUser['email'],
                            'role'  => $dbUser['role']
                        ];
                        header("Location: admin.php");
                        exit;
                    }
                }

                $error = "Invalid email or password.";
            }
        } else {
            $error = "Invalid email or password.";
        }
    } else {
        $error = "Please fill in all fields.";
    }
}

$loggedInUser = $_SESSION['user'] ?? null;
?>

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Login</title>
  <link rel="stylesheet" href="assets/style.css">
  <style>
    /* Password wrapper */
    .password-wrapper {
        position: relative;
        margin-bottom: 16px;
    }
    .password-wrapper input {
        width: 100%;
        padding: 12px 40px 12px 12px;
        border: 1px solid #ccc;
        border-radius: 6px;
        font-size: 14px;
        box-sizing: border-box;
    }
    .password-wrapper img {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        width: 20px;
        height: 20px;
        cursor: pointer;
        opacity: 0.6;
        transition: opacity 0.2s;
    }
    .password-wrapper img:hover {
        opacity: 1;
    }
  </style>
</head>
<body>
<!-- nav.php -->
<nav class="nav">
  <div class="container">
      <div class="brand">📝 Exam Portal</div>
      <div>
          <?php if ($loggedInUser): ?>
              <a href="index.php">Dashboard</a>
              <a href="logout.php">Logout</a>
          <?php else: ?>
              <a href="register.php">Register</a>
          <?php endif; ?>
      </div>
  </div>
</nav>

<main class="container">
    <?php if (!empty($error)): ?>
        <div class="flash">
            <div class="flash-item">
                <?= htmlspecialchars($error) ?>
            </div>
        </div>
    <?php endif; ?>

    <section class="card">
        <h1>Login</h1>
        <form method="post">
            <label>Email</label>
            <input type="text" name="email" required>

            <label>Password</label>
            <div class="password-wrapper">
                <input type="password" name="password" id="password" required>
                <img src="images/invisible.png" id="togglePassword">
            </div>

            <button class="primary" type="submit">Login</button>
            <p style="margin-top:10px;">
            <a href="forgot_password.php">Forgot Password?</a>
            </p>
        </form>
    </section>
</main>
<footer class="footer">
    <div class="container">&nbsp;</div>
</footer>

<script>
const togglePassword = document.getElementById('togglePassword');
const password = document.getElementById('password');

togglePassword.addEventListener('click', () => {
    if (password.type === 'password') {
        password.type = 'text';
        togglePassword.src = 'images/view.png';
    } else {
        password.type = 'password';
        togglePassword.src = 'images/invisible.png';
    }
});
</script>
</body>
</html>
