<?php
declare(strict_types=1);
require_once __DIR__ . '/auth/auth.php';

dreamgirl_session_start();

$didSso = false;
// If the user is already logged-in to NCue (Google), auto-login to DreamGirl.
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
  $didSso = dreamgirl_try_ncue_sso_login();
  if ($didSso) {
    header('Location: ' . dreamgirl_url('index.php'));
    exit;
  }
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $username = isset($_POST['username']) ? (string)$_POST['username'] : '';
  $password = isset($_POST['password']) ? (string)$_POST['password'] : '';

  if (dreamgirl_check_credentials($username, $password)) {
    $_SESSION['dreamgirl_user'] = 'admin';
    header('Location: ' . dreamgirl_url('index.php'));
    exit;
  }

  $error = '아이디 또는 비밀번호가 올바르지 않습니다.';
}
?><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Login</title>
    <style>
      html, body { height: 100%; margin: 0; font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; background:#111; color:#eee; }
      .wrap { min-height: 100%; display:flex; align-items:center; justify-content:center; padding:24px; box-sizing:border-box; }
      .card { width: min(420px, 100%); background:#1b1b1b; border:1px solid #2a2a2a; border-radius:12px; padding:18px; }
      h1 { font-size:18px; margin:0 0 12px; }
      label { display:block; font-size:12px; color:#bbb; margin:10px 0 6px; }
      input { width:100%; padding:10px 12px; border-radius:10px; border:1px solid #333; background:#0f0f0f; color:#eee; box-sizing:border-box; }
      button { width:100%; margin-top:14px; padding:10px 12px; border-radius:10px; border:1px solid #3b82f6; background:#2563eb; color:#fff; cursor:pointer; }
      .error { margin-top:10px; color:#ff7b7b; font-size:13px; }
      .hint { margin-top:10px; color:#888; font-size:12px; }
    </style>
  </head>
  <body>
    <div class="wrap">
      <form class="card" method="post" action="<?php echo htmlspecialchars(dreamgirl_url('login.php'), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); ?>" autocomplete="off">
        <h1>로그인</h1>
        <label for="username">아이디</label>
        <input id="username" name="username" type="text" required autofocus />
        <label for="password">비밀번호</label>
        <input id="password" name="password" type="password" required />
        <button type="submit">접속</button>
        <?php if ($error): ?>
          <div class="error"><?php echo htmlspecialchars($error, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); ?></div>
        <?php endif; ?>
        <div class="hint">인증 성공 시 페이지가 표시됩니다.</div>
      </form>
    </div>
  </body>
</html>

