<?php
declare(strict_types=1);
require_once __DIR__ . '/../src/bootstrap.php';
require_once __DIR__ . '/../src/layout.php';

require_logged_out('You are already logged in.');

$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $identifier = trim($_POST['identifier'] ?? ''); // username OR email (work/personal)
    $password   = (string)($_POST['password'] ?? '');

    if ($identifier === '' || $password === '') {
        $err = 'Enter username/email and password.';
    } else {
        $sql = "
          SELECT
            HEX(id) AS id_hex,
            username,
            password_hash,
            status
          FROM accounts
          WHERE username = :u
             OR email_work = :ew
             OR email_personal = :ep
          LIMIT 1
        ";
        $st = system_pdo()->prepare($sql);
        $st->execute([
            ':u'  => $identifier,
            ':ew' => $identifier,
            ':ep' => $identifier,
        ]);
        $row = $st->fetch();

        if (!$row) {
            $err = 'Invalid credentials.';
        } elseif ($row['status'] !== 'enabled') {
            $err = 'Account is not enabled.';
        } elseif (!password_verify($password, $row['password_hash'])) {
            $err = 'Invalid credentials.';
        } else {
            $_SESSION['account_id_hex'] = strtolower($row['id_hex']);
            $_SESSION['username'] = $row['username'];
            ensure_default_system_admin_for_account((string)$row['id_hex'], (string)($row['username'] ?? ''));

            $ip = $_SERVER['HTTP_CF_CONNECTING_IP']
                ?? $_SERVER['HTTP_X_FORWARDED_FOR']
                ?? $_SERVER['REMOTE_ADDR']
                ?? null;

            $upd = system_pdo()->prepare("
                UPDATE accounts
                SET last_login_at=NOW(), last_login_ip=:ip, failed_login_count=0
                WHERE id=UNHEX(:hex)
            ");
            $upd->execute([
                ':ip'  => $ip,
                ':hex' => $row['id_hex'],
            ]);

            flash_add('success', 'Logged in successfully.');
            redirect('/');
        }
    }
}

page_header('Login');
?>
<div class="card">
  <h2>Login</h2>
  <?php if ($err): ?><p class="err"><?= e($err) ?></p><?php endif; ?>

  <form method="post" autocomplete="off">
    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">

    <label>Username or Email (work or personal)</label>
    <input name="identifier" value="<?= e($_POST['identifier'] ?? '') ?>" required>

    <label>Password</label>
    <input name="password" type="password" required>

    <div style="margin-top:14px">
      <button type="submit">Sign In</button>
      <span class="muted">·</span>
      <a href="/register.php">Create an account</a>
    </div>
  </form>
</div>
<?php page_footer(); ?>
