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

$error = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $password = $_POST['password'];

    // Contoh query admin dulu, boleh tambah pelajar ikut username juga
    $sql = "SELECT * FROM admin WHERE username = '$username'";
    $result = mysqli_query($conn, $sql);

    if ($result && mysqli_num_rows($result) == 1) {
        $user = mysqli_fetch_assoc($result);
        if (password_verify($password, $user['kata_laluan'])) {
            $_SESSION['id_admin'] = $user['id'];
            $_SESSION['nama'] = $user['nama'];
            $_SESSION['role'] = 'admin';
            header('Location: dashboard.php');
            exit;
        } else {
            $error = 'Kata laluan salah.';
        }
    } else {
        $error = 'Nama pengguna tidak ditemui.';
    }
}
?>

<!DOCTYPE html>
<html lang="ms">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Login e-SPEKTRA</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body class="bg-light d-flex align-items-center" style="height:100vh;">

<div class="container" style="max-width: 400px;">
  <div class="card shadow-sm p-4">
    <h3 class="mb-4 text-center">Log Masuk e-SPEKTRA</h3>

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

    <form method="post" action="">
      <div class="mb-3">
        <label for="username" class="form-label">Nama Pengguna</label>
        <input type="text" class="form-control" id="username" name="username" required autofocus />
      </div>
      <div class="mb-3">
        <label for="password" class="form-label">Kata Laluan</label>
        <input type="password" class="form-control" id="password" name="password" required />
      </div>
      <button type="submit" class="btn btn-primary w-100">Log Masuk</button>
    </form>

    <div class="mt-3 text-center">
      <p>Belum ada akaun? <a href="register.php">Daftar sekarang</a></p>
    </div>
  </div>
</div>

</body>
</html>
