<?php
session_start();
require_once __DIR__ . '/includes/db_connect.php';

$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    if (!$username || !$password) {
        $err = 'Please provide username and password.';
    } else {
        $stmt = $pdo->prepare('SELECT id, password_hash, role FROM admins WHERE username = ? LIMIT 1');
        $stmt->execute([$username]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row && password_verify($password, $row['password_hash'])) {
            // login
            $_SESSION['admin_id'] = $row['id'];
            $_SESSION['admin_role'] = $row['role'];
            header('Location: dashboard.php');
            exit;
        } else {
            $err = 'Invalid credentials.';
        }
    }
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Admin Login</title>
  <link rel="stylesheet" href="assets/theme.css">
</head>
<body class="auth-page">
  <main class="auth-card">
    <h1 class="brand">Wake Word — Admin</h1>
    <p class="muted">Sign in with your admin account</p>
    <?php if ($err): ?><div class="alert"><?=htmlspecialchars($err)?></div><?php endif; ?>
    <form method="post" novalidate>
      <label class="field">
        <span>Username</span>
        <input name="username" type="text" required autofocus>
      </label>
      <label class="field">
        <span>Password</span>
        <input name="password" type="password" required>
      </label>
      <div style="display:flex;gap:10px;align-items:center;">
        <button class="btn primary" type="submit">Login</button>
        <a class="link muted" href="../index.php">Back to site</a>
      </div>
    </form>
    <p class="meta muted">Use admin credentials to access the control panel.</p>
  </main>
</body>
</html>
