<?php
require_once __DIR__ . '/../lib/core.php';

if (dc_is_logged_in()) {
    dc_redirect('admin/index.php');
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    dc_require_csrf();
    $username = trim(isset($_POST['username']) ? $_POST['username'] : '');
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    $stmt = dc_db()->prepare('SELECT * FROM door_cert_admins WHERE username = ? LIMIT 1');
    $stmt->execute(array($username));
    $admin = $stmt->fetch();
    if ($admin && password_verify($password, $admin['password_hash'])) {
        $_SESSION['dc_admin_id'] = $admin['id'];
        $_SESSION['dc_admin_user'] = $admin['username'];
        dc_redirect('admin/index.php');
    }
    $error = 'Invalid username or password.';
}

dc_admin_header('Admin Login');
?>
<div class="dc-card">
  <?php if ($error): ?><div class="dc-alert error"><?php echo dc_h($error); ?></div><?php endif; ?>
  <form method="post">
    <?php echo dc_csrf_field(); ?>
    <label>Username</label>
    <input name="username" required>
    <label>Password</label>
    <input name="password" type="password" required>
    <p><button type="submit">Login</button></p>
  </form>
</div>
<?php dc_footer(); ?>
