<?php
namespace src\handlers;

use \src\models\User;

class LoginHandler {

	public static function checkLogin() {
		if(!empty($_SESSION['token'])) {
			$token = $_SESSION['token'];
			$data = User::select()
				->where('token', $token)
				->andWhere('status', 1)
			->one();

			if(!empty($data)) {

				$loggedUser = new User();
				$loggedUser->id = $data['id'];
				$loggedUser->name = $data['name'];
				$loggedUser->email = $data['email'];
				$loggedUser->group = $data['id_group'];

				return $loggedUser;
			}
		} 
		return false;
	}

	public static function verifyLogin($email, $password) {
		$user = User::select()
			->where('email', $email)
			->andWhere('status', 1)
		->one();

		if($user) {
			if(md5($password) === $user['password']) {
				$token = md5($user['id'].rand(0,999).time());

				User::update()
					->set('token', $token)
					->where('email', $email)
				->execute();

				return $token;
			}
		}
		return false;
	}

	public static function verifyForgetPassword($email) {
		$user = User::select('id')
			->where('email', $email)
			->andWhere('status', 1)
		->one();

		if($user) {
			return $user;
		}

		return false;
	}

	public static function saveLinkForget($id, $link) {
		User::update()
			->set('link_status', $link)
			->where('id', $id)
		->execute();
	}

	public static function verifyLink($linkHash) {
		$user = User::select()
			->where('link_status', $linkHash)
			->andWhere('status', 1)
		->one();

		if($user) {
			return true;
		}

		return false;
	}

	public static function update($password, $ref, $status) {
		User::update()
			->set('password', $password)
			->where('link_status', $ref)
			->andWhere('status', 1)
		->execute();

		User::update()
			->set('link_status', $status)
			->where('link_status', $ref)
		->execute();
	}
}