<?php

use Nette\Forms\Form;
use Instante\Bootstrap3Renderer\BootstrapRenderer;
use Nette\Security\Passwords;

function validate_unique_user($field) {
    global $db;
    $username = $field->getValue();
    return $db->table('user')->where(compact('username'))->count() == 0;
}

function registration_form() {
    $form = new Form;
    $form->setRenderer(new BootstrapRenderer);
    $form->setAction('register');

    $form->addText('username', _('Username'))
        ->setRequired()
        ->addRule(Form::MIN_LENGTH, null, 3)
        ->addRule(Form::MAX_LENGTH, null, 100)
        ->addRule(Form::PATTERN, _('Username may not contain whitespace or special characters'), '([a-zA-Z0-9-_])+')
        ->addRule('validate_unique_user', _('This username has already been taken'));
    $form->addPassword('password', _('Password'))
        ->setRequired();
    $form->addPassword('password_repeat', _('Confirm password'))
        ->setRequired()
        ->addConditionOn($form['password'], Form::FILLED)
            ->addRule(Form::EQUAL, _('Passwords must match'), $form['password']);
    $form->addSubmit('send', _('Register'));

    return $form;
}

$app->get('/register', function () use ($app, $user) {
    $form = registration_form();
    $app->render('register', compact('form'));
});

$app->post('/register', function () use ($app, $user, $db) {
    $form = registration_form();
    $form->validate();

    if (!$form->hasErrors()) {
        $values = $form->getValues();
        $db->table('user')->insert(array(
            'username' => $values->username,
            'password' => Passwords::hash($values->password)
        ));
        $user->login($values->username, $values->password);
        $app->redirect(ROOT_URL);
    }

    $app->render('register', compact('form'));
});