<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/views.php';

$config = require __DIR__ . '/includes/config.php';
if (!is_file($config['installed_flag'])) {
    header('Location: install.php', true, 302);
    exit;
}

if (current_user()) {
    header('Location: dashboard.php', true, 302);
    exit;
}

$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $email = trim((string) ($_POST['email'] ?? ''));
    $password = (string) ($_POST['password'] ?? '');
    $result = attempt_login($email, $password);
    if ($result === true) {
        header('Location: dashboard.php', true, 302);
        exit;
    }
    if ($result === 'rate_limited') {
        $error = 'Too many attempts. Try again in a few minutes.';
    } else {
        $error = 'Invalid email or password.';
    }
}

portal_header('Sign in', null);
$flash = flash_take('info');
?>
<div class="portal-auth-card">
  <h1 class="portal-h1">Sign in</h1>
  <p class="portal-lead">Access your projects, tickets, and billing.</p>
  <?php if (!empty($_GET['installed'])): ?>
    <p class="portal-alert portal-alert-success" role="status">Installation complete. You can sign in now.</p>
  <?php endif; ?>
  <?php if ($flash): ?><p class="portal-alert portal-alert-success" role="status"><?= h($flash) ?></p><?php endif; ?>
  <?php if ($error): ?><p class="portal-alert portal-alert-error" role="alert"><?= h($error) ?></p><?php endif; ?>
  <form method="post" class="portal-form" autocomplete="on">
    <?= csrf_field() ?>
    <label class="portal-label">Email
      <input class="portal-input" type="email" name="email" required autocomplete="username" value="<?= h($_POST['email'] ?? '') ?>">
    </label>
    <label class="portal-label">Password
      <input class="portal-input" type="password" name="password" required autocomplete="current-password">
    </label>
    <button type="submit" class="portal-btn portal-btn-primary portal-btn-block">Sign in</button>
  </form>
  <p class="portal-auth-meta"><a href="forgot.php">Forgot password?</a></p>
  <p class="portal-auth-meta portal-auth-legal">By signing in you agree to our <a href="../index.html">site terms</a> and <a href="mailto:contact@galleys.pub">privacy practices</a>.</p>
</div>
<?php
portal_footer();
