<?php

declare(strict_types=1);

/**
 * Community-branded registration with email verification. Reuses the platform's
 * password policy + user table; creates a PENDING account and emails a rich,
 * on-brand confirmation link (via forum_send_verify_email). Falls back to
 * immediate-active only when no SMTP is configured, so sign-up never dead-ends.
 */

require __DIR__ . '/_shell.php';

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

$b = forum_base();
if (forum_logged_in()) {
    header('Location: ' . $b . '/');
    exit;
}
// Registration is open only when the app allows it AND a moderator hasn't flipped
// the anti-bot lock in the community admin dashboard.
$open = (bool) AuthGuard::get('allow_registration') && !forum_registration_locked();

$error = '';
$vals  = ['username' => '', 'email' => '', 'fullname' => ''];

if ($open && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $vals['username'] = trim((string) ($_POST['username'] ?? ''));
    $vals['email']    = trim((string) ($_POST['email'] ?? ''));
    $password = (string) ($_POST['password'] ?? '');
    $confirm  = (string) ($_POST['confirm_password'] ?? '');
    $hp       = trim((string) ($_POST['website'] ?? ''));   // honeypot

    if ($hp !== '') {
        // Bot filled the hidden field — pretend success, do nothing.
        $_SESSION['_flash'] = ['message' => 'Almost there — check your inbox to confirm your email.', 'type' => 'success'];
        header('Location: ' . $b . '/login');
        exit;
    }
    if (!Security::CSRF()->Check((string) ($_POST['_token'] ?? ''))) {
        $error = 'Your session expired — please submit again.';
    } elseif (!preg_match('/^[A-Za-z0-9_.-]{3,64}$/', $vals['username'])) {
        $error = 'Choose a username of 3–64 letters, numbers, dots, dashes or underscores.';
    } elseif (!filter_var($vals['email'], FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address.';
    } elseif ($password !== $confirm) {
        $error = 'The two passwords do not match.';
    } elseif (($pwErr = AuthGuard::passwordError($password, ['username' => $vals['username'], 'email' => $vals['email']])) !== '') {
        $error = $pwErr;
    } elseif (DB::FetchAll('SELECT id FROM users WHERE username = ? OR email = ?', [$vals['username'], $vals['email']])) {
        $error = 'That username or email is already registered.';
    } else {
        // Verify by email only when SMTP is available; otherwise activate so a
        // misconfigured mailer never leaves people unable to sign in.
        $mailConfigured = is_file(BASE_PATH . '/config/mail.php');
        $verify = $mailConfigured && (string) AuthGuard::get('activation_mode') === 'email';
        $sf = (string) AuthGuard::get('status_field') ?: 'status';

        $id = (int) DB::Insert('users', [
            'username' => $vals['username'],
            'email'    => $vals['email'],
            'password' => Security::HashPassword($password),
            'role'     => (string) AuthGuard::get('default_role') ?: 'member',
            $sf        => $verify ? 'pending' : 'active',
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        if ($id && $verify) {
            $hours = max(1, (int) AuthGuard::get('activation_hours') ?: 24);
            $tok = Security::GenerateToken();
            DB::Query('CREATE TABLE IF NOT EXISTS account_activations (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, user_id INT UNSIGNED NOT NULL, token VARCHAR(64) NOT NULL, expires_at DATETIME NOT NULL, created_at DATETIME NOT NULL, INDEX idx_aa_token (token), INDEX idx_aa_user (user_id))');
            DB::Insert('account_activations', ['user_id' => $id, 'token' => $tok, 'expires_at' => date('Y-m-d H:i:s', time() + 3600 * $hours), 'created_at' => date('Y-m-d H:i:s')]);
            $sch = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
            $base = ($_SERVER['HTTP_HOST'] ?? 'localhost');
            $verifyUrl = $sch . '://' . $base . $b . '/verify?token=' . rawurlencode($tok);
            forum_send_verify_email($vals['email'], $vals['username'], $verifyUrl, $hours . ' hours');
            $_SESSION['_flash'] = ['message' => 'Almost there! We sent a confirmation link to ' . $vals['email'] . ' — click it to activate your account.', 'type' => 'success'];
        } else {
            $_SESSION['_flash'] = ['message' => 'Your account is ready — you can sign in now.', 'type' => 'success'];
        }
        header('Location: ' . $b . '/login');
        exit;
    }
}

forum_auth_head('Create your account — PPPHP Community', '<meta name="robots" content="noindex,follow">');
?>
<div class="fx-auth-card">
  <h1>Join the community</h1>
  <p class="fx-auth-sub">Create an account to ask questions and share answers.</p>
  <?php if (!$open): ?>
    <div class="fx-formerr"><i class="bi bi-lock"></i> Registration is currently closed.</div>
  <?php else: ?>
    <?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 ?>/register">
      <input type="hidden" name="_token" value="<?= forum_e(forum_csrf()) ?>">
      <input class="fx-hp" type="text" name="website" tabindex="-1" autocomplete="off" aria-hidden="true">
      <div class="fx-field"><label>Username</label><input class="fx-input" type="text" name="username" value="<?= forum_e($vals['username']) ?>" required autofocus autocomplete="username" placeholder="Choose a username"></div>
      <div class="fx-field"><label>Email</label><input class="fx-input" type="email" name="email" value="<?= forum_e($vals['email']) ?>" required autocomplete="email" placeholder="you@example.com"></div>
      <div class="fx-field"><label>Password</label><input class="fx-input" type="password" name="password" required autocomplete="new-password" placeholder="Create a password"></div>
      <div class="fx-field"><label>Confirm password</label><input class="fx-input" type="password" name="confirm_password" required autocomplete="new-password" placeholder="Repeat your password"></div>
      <button class="fx-submit full" type="submit">Create account</button>
    </form>
  <?php endif; ?>
  <p class="fx-auth-alt">Already have an account? <a href="<?= $b ?>/login">Sign in</a></p>
</div>
<p class="fx-auth-note"><i class="bi bi-envelope-check"></i> We'll email you a link to confirm your address</p>
<?php forum_auth_foot(); ?>
