<?php

declare(strict_types=1);

/**
 * Community-branded sign-in. Reuses the platform's auth primitives (lockout,
 * status/2FA checks, Security::Login) with the forum's own presentation.
 */

require __DIR__ . '/_shell.php';

use PpPhp\Core\Security;
use PpPhp\Core\DB;
use PpPhp\Core\Auth\AuthGuard;
use PpPhp\Core\Auth\TwoFactor;

$b = forum_base();
if (forum_logged_in()) {
    header('Location: ' . $b . '/');
    exit;
}

$error = '';
$username = trim((string) ($_POST['username'] ?? ''));
$lock = AuthGuard::loginLockState($username);

if ($lock['locked']) {
    $error = 'Too many failed sign-in attempts. Try again in ' . AuthGuard::retryText($lock['retry_after']) . '.';
} elseif (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    if (!Security::CSRF()->Check((string) ($_POST['_token'] ?? ''))) {
        $error = 'Your session expired — please try again.';
    } else {
        $password = (string) ($_POST['password'] ?? '');
        $remember = !empty($_POST['remember']);
        if (Security::CheckUsernamePassword($username, $password)) {
            $row = DB::FetchAll('SELECT id, email FROM users WHERE username = ? OR email = ? LIMIT 1', [$username, $username])[0] ?? null;
            $uid = (int) ($row['id'] ?? 0);
            $sf = (string) AuthGuard::get('status_field');
            $st = 'active';
            if ($sf !== '') {
                $sr = DB::FetchAll('SELECT `' . $sf . '` AS st FROM users WHERE id = ? LIMIT 1', [$uid]);
                if (isset($sr[0]['st'])) $st = strtolower(trim((string) $sr[0]['st']));
            }
            if ($st !== '' && $st !== 'active' && $st !== '1') {
                $error = $st === 'pending'
                    ? 'Please confirm your email first — we sent you a verification link when you signed up.'
                    : 'This account has been disabled. Please contact an administrator.';
            } else {
                AuthGuard::clearLoginFailures($username);
                if (defined('PP_2FA_ENABLED') && PP_2FA_ENABLED && TwoFactor::isEnabled($uid)) {
                    TwoFactor::setPending($username, $remember, $uid, (string) ($row['email'] ?? ''));
                    header('Location: ' . $b . '/two-factor');
                    exit;
                }
                Security::Login($username, $password, $remember);
                header('Location: ' . $b . '/');
                exit;
            }
        } else {
            AuthGuard::recordLoginFailure($username);
            $error = 'Invalid username or password.';
            $after = AuthGuard::loginLockState($username);
            if ($after['locked']) {
                $error = 'Too many failed sign-in attempts. Try again in ' . AuthGuard::retryText($after['retry_after']) . '.';
            }
        }
    }
}

$flash = $_SESSION['_flash'] ?? null;
unset($_SESSION['_flash']);

forum_auth_head('Sign in — PPPHP Community', '<meta name="robots" content="noindex,follow">');
?>
<div class="fx-auth-card">
  <h1>Welcome back</h1>
  <p class="fx-auth-sub">Sign in to ask, answer and vote in the community.</p>
  <?php if ($flash && ($flash['type'] ?? '') === 'success'): ?><div class="fx-ok"><i class="bi bi-check-circle-fill"></i> <?= forum_e($flash['message']) ?></div><?php endif; ?>
  <?php if ($error): ?><div class="fx-formerr"><i class="bi bi-exclamation-circle"></i> <?= forum_e($error) ?></div><?php endif; ?>
  <form method="post" action="<?= $b ?>/login">
    <input type="hidden" name="_token" value="<?= forum_e(forum_csrf()) ?>">
    <div class="fx-field"><label>Username or email</label><input class="fx-input" type="text" name="username" value="<?= forum_e($username) ?>" required autofocus autocomplete="username"></div>
    <div class="fx-field"><label>Password</label><input class="fx-input" type="password" name="password" required autocomplete="current-password"></div>
    <div class="fx-checkrow"><label><input type="checkbox" name="remember" value="1"> Keep me signed in</label><a href="<?= $b ?>/forgot-password">Forgot password?</a></div>
    <button class="fx-submit full" type="submit">Sign in</button>
  </form>
  <p class="fx-auth-alt">New to the community? <a href="<?= $b ?>/register">Create an account</a></p>
</div>
<p class="fx-auth-note"><i class="bi bi-shield-check"></i> Secure sign-in for the PPPHP Community</p>
<?php forum_auth_foot(); ?>
