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

if(isset($params['hash']) && $params['hash']){

    $hash = $params['hash'];

    $hashCheck = $dbo->query('SELECT id, user_id, expires FROM user_resets WHERE hash = ?', [$hash]);

    if(!$hashCheck->count()) 
        Response::redirect('reset');

    $hashData = $hashCheck->first();

    // if hash expired or not present
    if(strtotime($hashData->expires) < time()){

        if(strtotime($hashData->expires) < time()){
            // delete if expired
            $dbo->delete('user_resets', array('id', '=', $hashData->id));
        }

        Session::flash('error', 'Reset Password Link has Expired !');
        Response::redirect('reset');
    }

}else{

    if(!Session::exists('error'))
            Session::flash('error', 'Invalid reset link');
}

// save new password
if(Check::type('post') && isset($hashData->user_id)){

    if(!Check::post('npassword', 'rpassword')){
        Session::flash('passerror', 'Both fields are required.');
        Response::redirect('reset/'.$hash);
    }

    $password = escapeText($_POST['npassword']);
    $repassword = escapeText($_POST['rpassword']);

    if(strlen($password) < 5){
        Session::flash('passerror', 'Password should be of minimum 5 characters');
        Response::redirect('reset/'.$hash);
    }

    if($password !== $repassword){
        Session::flash('passerror', 'Password doesn\'t match');
        Response::redirect('reset/'.$hash);
    }

    $usero->update(array(

    'password' => System\Hash::make($password),

    ), $hashData->user_id);

    $dbo->delete('user_resets', array('id', '=', $hashData->id));

    $findUser = $usero->find('id', $hashData->user_id);

    $usero->login($usero->data()->email, $password);

    Response::redirect('/');
}

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

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

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

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

echo $data;