<?php
use System\Check;
use System\Session;
use System\Response;

// if no signups allowed
if(System\Config::app('allow_signup') !== 'yes'){
  Response::redirect('/');
}

if(Check::type('post')){

  if(!Check::post('username', 'email', 'password')){
    Session::flash('error', 'All fields are required');
    Response::redirect('register');
  }

  $email = escapeText($_POST['email']);
  $username = escapeText($_POST['username']);
  $password = escapeText($_POST['password']);

    //validate captcha
  $recaptcha = new \ReCaptcha\ReCaptcha(System\Config::google('secret'), new \ReCaptcha\RequestMethod\CurlPost());
  $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
 
  if(!$resp->isSuccess()){
      Session::flash('error', 'Captcha verification required');
      Response::redirect('login');
  }

  if(!preg_match('/^[a-zA-Z0-9_]{4,20}$/', $username)){
        Session::flash('error', 'Username is not valid. should be of 4 to 20 characters');
        System\Response::redirect('register');
   }

   if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        Session::flash('error', 'Email address is not valid');
        System\Response::redirect('register');
   }

   if(strlen($password) < 5){
        Session::flash('error', 'Password should be of minimum 5 characters');
        System\Response::redirect('register');
    }

    // check if username is availaible
   $checkQuery = $dbo->query('SELECT id FROM users WHERE username = ?', [$username]);

   if($checkQuery->count()){
     Session::flash('error', 'Username is not availaible');
     System\Response::redirect('register'); 
   }

   // check if dupciate email address
   $checkQuery = $dbo->query('SELECT id FROM users WHERE email = ?', [$email]);

   if($checkQuery->count()){
     Session::flash('error', '*Email already registered! try logging in.');
     System\Response::redirect('register'); 
   }

   $userFields = [
    'username' => $username,
    'email' => $email,
    'password' => System\Hash::make($password),
    'role' => 'user',
    'status' => 'active'
  ];

  $usero->create($userFields);

  Session::flash('success', 'success');
  System\Response::redirect('register');

}

// View Class Instance
$view = new System\View('register');

// include common
include('common.php');

$view->title = System\Config::meta('register')['title'];
$view->meta_desc = System\Config::meta('register')['desc'];
$view->canonicalUrl = System\Uri::full('/register');

$view->pageType = 'register';
$data = $view->render();

echo $data;