<?php
declare(strict_types=1);

ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);

require __DIR__ . '/../config/bootstrap.php';

$db = \App\Core\Database::getInstance();

if (session_status() !== PHP_SESSION_ACTIVE) session_start();

$err = null;
$ok  = null;

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
  $email = trim((string)($_POST['email'] ?? ''));
  $pass  = (string)($_POST['password'] ?? '');

  $st = $db->prepare("SELECT id, password_hash, is_active FROM users WHERE email=:e LIMIT 1");
  $st->execute([':e'=>$email]);
  $u = $st->fetch();

  if (!$u) {
    $err = "User not found";
  } elseif ((int)($u['is_active'] ?? 1) !== 1) {
    $err = "User is inactive";
  } elseif (!password_verify($pass, (string)$u['password_hash'])) {
    $err = "Invalid password";
  } else {
    $_SESSION['user_id'] = (int)$u['id'];
    @session_regenerate_id(true);
    $ok = "Logged in OK. uid=" . $_SESSION['user_id'];
  }
}

?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>EasyChair Simple Login</title>
  <style>
    body{font-family:Arial, sans-serif; margin:40px;}
    .card{max-width:520px; padding:20px; border:1px solid #ddd; border-radius:12px;}
    input{width:100%; padding:10px; margin:6px 0 12px; border:1px solid #ccc; border-radius:8px;}
    button{padding:10px 14px; border:0; border-radius:8px; background:#0d6efd; color:#fff; cursor:pointer;}
    .err{background:#ffe6e6; padding:10px; border-radius:8px; margin-bottom:10px;}
    .ok{background:#e6ffed; padding:10px; border-radius:8px; margin-bottom:10px;}
    .meta{color:#666; font-size:12px; margin-top:10px;}
    a{color:#0d6efd;}
  </style>
</head>
<body>
  <div class="card">
    <h2>Simple Login (Direct)</h2>

    <?php if($err): ?><div class="err"><?= htmlspecialchars($err) ?></div><?php endif; ?>
    <?php if($ok): ?><div class="ok"><?= htmlspecialchars($ok) ?></div><?php endif; ?>

    <form method="post">
      <label>Email</label>
      <input name="email" type="email" required>
      <label>Password</label>
      <input name="password" type="password" required>
      <button type="submit">Login</button>
    </form>

    <div class="meta">
      cookie_path=<?= htmlspecialchars((string)ini_get('session.cookie_path')) ?><br>
      session_id=<?= htmlspecialchars(session_id()) ?><br>
      <a href="whoami.php" target="_blank">Open whoami.php</a>
    </div>
  </div>
</body>
</html>
