<?php
require __DIR__ . '/../vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->safeLoad();
require __DIR__ . '/i18n.php';

use App\Auth;
use App\Csrf;
Auth::init();

$errors = [];
$info = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Csrf::verify($_POST['_csrf'] ?? '')) {
        $errors[] = t('invalid_csrf');
    } else {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';

        if (!$name) $errors[] = 'Name is required';
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = t('staff_user');
        if (strlen($password) < 6) $errors[] = 'Password must be at least 6 characters';

        if (empty($errors)) {
            // Create new user with 'pending' status; admin must approve
            $pdo = App\Database::getConnection();
            try {
                $stmt = $pdo->prepare('SELECT id FROM roles WHERE name = :name LIMIT 1');
                $stmt->execute([':name' => 'user']);
                $r = $stmt->fetch(PDO::FETCH_ASSOC);
                $role_id = $r['id'] ?? null;

                $ins = $pdo->prepare('INSERT INTO users (name,full_name,username,email,password,password_hash,role_id,status) VALUES (:name,:full_name,:username,:email,:password,:password_hash,:role_id,:status)');
                $username = preg_replace('/[^a-z0-9_.-]+/i', '', explode('@',$email)[0]);
                $ins->execute([
                    ':name' => $name,
                    ':full_name' => $name,
                    ':username' => $username,
                    ':email' => $email,
                    ':password' => password_hash($password, PASSWORD_DEFAULT),
                    ':password_hash' => password_hash($password, PASSWORD_DEFAULT),
                    ':role_id' => $role_id,
                    ':status' => 'pending',
                ]);

                $info = t('reg_submitted');
            } catch (\PDOException $e) {
                $errors[] = 'Registration failed (email may already exist)';
            }
        }
    }
}
$csrf = Csrf::token();

include __DIR__ . '/header.php';
?>
<div class="auth-card" aria-live="polite">
  <div class="auth-logo"><span class="logo-pill">Create account</span></div>
  <h2><?=t('register_title')?></h2>
  <div class="sub"><?=t('register_sub')?></div>
  <?php if($info): ?>
    <div class="errors"><?=htmlspecialchars($info)?></div>
  <?php endif; ?>
  <?php if($errors): ?>
    <div class="errors"><?php foreach($errors as $e) echo '<div>'.htmlspecialchars($e).'</div>'; ?></div>
  <?php endif; ?>
  <form method="post" novalidate data-auth>
    <input type="hidden" name="_csrf" value="<?=htmlspecialchars($csrf)?>">
    <div class="form-group">
      <label for="name"><?=t('register_title')?></label>
      <input id="name" class="form-input" name="name" data-required value="<?=htmlspecialchars($_POST['name'] ?? '')?>" required>
    </div>
    <div class="form-group">
      <label for="email"><?=t('staff_user')?></label>
      <input id="email" class="form-input" name="email" type="email" data-required value="<?=htmlspecialchars($_POST['email'] ?? '')?>" required>
    </div>
    <div class="form-group">
      <label for="password"><?=t('staff_pass')?> <small style="color:var(--muted)"> (min 6 chars)</small></label>
      <input id="password" class="form-input" type="password" name="password" data-required required>
    </div>
    <div style="margin-top:12px">
      <button class="btn" type="submit"><?=t('btn_register')?></button>
      <a class="btn btn-outline" href="/login.php"><?=t('login_title')?></a>
    </div>
  </form>
  <div class="muted"><?=t('have_account')?></div>
</div>
<?php include __DIR__ . '/footer.php'; ?>
