<?php
require_once __DIR__ . '/includes/bootstrap.php';

if (is_logged_in()) {
    redirect(APP_URL . '/main.php');
}

$errors = [];
$old = ['name' => '', 'email' => ''];
$race = (int)($_GET['race'] ?? 1);
if (!in_array($race, [1, 2], true)) $race = 1;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF kontrol
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        $errors[] = __('err_csrf');
    } else {
        $name  = trim((string)($_POST['name']  ?? ''));
        $email = trim((string)($_POST['email'] ?? ''));
        $pass  = (string)($_POST['password']  ?? '');
        $pass2 = (string)($_POST['password2'] ?? '');
        $agree = !empty($_POST['agree']);
        $race  = in_array((int)($_POST['race'] ?? 1), [1, 2], true) ? (int)$_POST['race'] : 1;

        $old['name'] = $name;
        $old['email'] = $email;

        // Validasyonlar
        if (mb_strlen($name) < 4 || mb_strlen($name) > 16) {
            $errors[] = __('err_name_length');
        } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $name)) {
            $errors[] = __('err_name_invalid');
        } elseif (User::findByName($name)) {
            $errors[] = __('err_name_taken');
        }

        if (mb_strlen($pass) < 6) {
            $errors[] = __('err_pass_length');
        } elseif ($pass !== $pass2) {
            $errors[] = __('err_pass_match');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = __('err_email_invalid');
        } elseif (User::findByEmail($email)) {
            $errors[] = __('err_email_taken');
        }

        if (!$agree) {
            $errors[] = __('err_must_agree');
        }

        // Kayıt
        if (empty($errors)) {
            try {
                $newId = User::register($name, $pass, $email, $race);
                $user = User::findById($newId);
                if ($user) {
                    User::loginSession($user);
                    flash_set('success', __('register_success'));
                    redirect(APP_URL . '/main.php');
                }
            } catch (Throwable $e) {
                $errors[] = APP_DEBUG ? $e->getMessage() : __('error');
            }
        }
    }
}

$page_title = __('register_title');
$hide_menu = true;
require __DIR__ . '/includes/header.php';
?>

<div class="auth-page">
    <h1><?= e(__('register_title')) ?></h1>

    <div class="tabs">
        <a href="<?= APP_URL ?>/login.php"><?= __('login') ?></a>
        <a href="<?= APP_URL ?>/register.php" class="active"><?= __('register') ?></a>
    </div>

    <?php foreach ($errors as $err): ?>
        <div class="flash flash-error"><?= e($err) ?></div>
    <?php endforeach; ?>

    <div style="text-align:center; margin-bottom: 1rem;">
        <img id="race-img" src="<?= APP_URL ?>/assets/img/race<?= $race ?>.gif"
             alt="<?= __($race === 1 ? 'race_vampire' : 'race_werewolf') ?>"
             class="race-preview">
    </div>
    <div style="text-align:center; margin-bottom: 1rem;">
        <strong><?= __('choose_race') ?>:</strong>
        <label style="margin-left: 1rem;">
            <input type="radio" name="race_display" <?= $race === 1 ? 'checked' : '' ?>
                   onclick="document.getElementById('race').value=1; document.getElementById('race-img').src='<?= APP_URL ?>/assets/img/race1.gif';">
            <img src="<?= APP_URL ?>/assets/img/race1small.gif" alt="" style="vertical-align:middle">
            <?= __('race_vampire') ?>
        </label>
        <label style="margin-left: 1rem;">
            <input type="radio" name="race_display" <?= $race === 2 ? 'checked' : '' ?>
                   onclick="document.getElementById('race').value=2; document.getElementById('race-img').src='<?= APP_URL ?>/assets/img/race2.gif';">
            <img src="<?= APP_URL ?>/assets/img/race2small.gif" alt="" style="vertical-align:middle">
            <?= __('race_werewolf') ?>
        </label>
    </div>

    <form method="post" action="<?= APP_URL ?>/register.php">
        <?= csrf_field() ?>
        <input type="hidden" name="race" id="race" value="<?= $race ?>">

        <div class="form-row">
            <label for="name"><?= __('username') ?></label>
            <input type="text" id="name" name="name" maxlength="16" required
                   value="<?= e($old['name']) ?>" autofocus>
        </div>

        <div class="form-row">
            <label for="email"><?= __('email') ?></label>
            <input type="email" id="email" name="email" maxlength="100" required
                   value="<?= e($old['email']) ?>">
        </div>

        <div class="form-row">
            <label for="password"><?= __('password') ?></label>
            <input type="password" id="password" name="password" minlength="6" required>
        </div>

        <div class="form-row">
            <label for="password2"><?= __('password_again') ?></label>
            <input type="password" id="password2" name="password2" minlength="6" required>
        </div>

        <div class="form-row">
            <label style="text-transform:none; display: flex; align-items: center;">
                <input type="checkbox" name="agree" value="1" required>
                <span><?= e(__('agree_terms')) ?></span>
            </label>
        </div>

        <button type="submit" style="width:100%;"><?= __('register') ?></button>
    </form>

    <p class="text-center mt-1 text-muted">
        <?= __('have_account') ?> <a href="<?= APP_URL ?>/login.php"><?= __('login') ?></a>
    </p>
</div>

<?php require __DIR__ . '/includes/footer.php'; ?>
