<?php

class Register extends Page {
    
        function index()
        {
            $this->set('template', 'register.html');
        }
    
        function validate()
        {
            $email = trim($_REQUEST['email']);
            $password = trim($_REQUEST['password']);
            $password2 = trim($_REQUEST['password2']);

            $hash = password_hash($password, PASSWORD_DEFAULT);
            
            $u = new User();

            $err = false;
            if(!$email)
                $err = "Email is required";
            else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
                $err = "Email is invalid";
            else if(!$password)
                $err = "Password is required";
            else if($password != $password2)
                $err = "Passwords do not match";
            else if(strlen($password) < 8)
                $err = "Password must be at least 8 characters long";
            else if($u->exists($email))
                $err = "Email already exists";

            if($err)
            {
                $this->set('template', '/templates/partials/error.html');
                $this->set('errorTitle', 'Error');
                $this->set('errorMessage', $err);
                return;
            }
            else
            {
                $u->id = $email;
                $u->email = $email;
                $u->password = $hash;
                $u->active = 0;
                try
                {
                    $u->save();
                    $this->redirect('/register/success');
                }
                catch(Exception $e)
                {
                    $this->set('template', '/templates/partials/error.html');
                    $this->set('errorTitle', 'Error');
                    $this->set('errorMessage', $e->getMessage());
                    return;
                }
                
                return;
            }
    
            //return print_r(['email'=>$email,'password'=>$password,'password2'=>$password2], true);
        }

        function success()
        {
            $this->set('template', '/templates/partials/success.html');
            $this->set('successTitle', 'Success');
            $this->set('successMessage', 'You have successfully registered. Activate your account from the Link in your email');
        }

        function test()
        {
            $u = new User();
            $u->id = 'chris@chris.ch';
            $u->email = 'chris@chris.ch';
            $u->password = '123456';
            $u->save();
            
            return nl2br(print_r($u, true));
        }

        function test2()
        {
            $u = new User();
            $response = $u->load('chris@chasdris.ch');

            return nl2br(print_r($response, true));
        }
}