<?php
include_once "../../includes/config.php";
include_once "../../includes/database.php";
include_once "../../includes/validation.php";
include_once "../../includes/Helper.php";



class Login extends database{
	public function index($data)
	{
		$user = $this->fetchRow(TABLE_PREFIX . '_users', $data);
		if(!$user)
		{
			return 0;
			exit;
		}

		return $user;
		exit;
	}

	public function insertLog($data)
	{
		return $this->insert(TABLE_PREFIX . '_user_log', $data);
	}

	public function setSession($authCode, $userCode)
	{
		$data['cl_access_code'] = $authCode;
		$data['cl_client_code'] = $userCode;
		$data['cl_expiry_date'] = date('Y-m-d', strtotime('+ 5 days'));
		return $this->insert('tb_session_token', $data);
	}
}

if(!isset($_POST['data']))
{
	http_response_code(400);
	echo json_encode(array('No input found'));
	exit;
}

$data = $_POST['data'];
$helper = new Helper();
$validation = new validation();

$data = $helper->changeSerialzeArrayValues($data);

$res = array();
$requiredFields = array('email', 'password');
$return = $validation->checkRequired($requiredFields, $data);
if($return)
{
	$res['error_description'][] = $return;
}

$emailFields = array('email');
$return = $validation->checkEmail($emailFields, $data);
if($return)
{
	$res['error_description'][] = $return;
}

$passwordFields = array('password');
$return = $validation->checkPassword($passwordFields, $data);
if($return)
{
	$res['error_description'][] = $return;
}

if(!empty($res['error_description']))
{
	$result['error_description'] = $validation->setErrors($res['error_description']);
	$result['error_text'] = 'Following errors are found';

	http_response_code(400);
	echo json_encode($result);
	exit;
}

$data = $validation->removeEmptyValues($data);

$password = $data[COLUMN_PREFIX .'_password'];
unset($data[COLUMN_PREFIX . '_password']);
$obj = new Login();



$user = $obj->index($data);
if(!$user || ($user['cl_type'] != 'customer_admin' && $user['cl_type'] != 'manager' && $user['cl_type'] != 'chef' && $user['cl_type'] != 'bar' && $user['cl_type'] != 'runner_head'))
{
	http_response_code(401);
	echo json_encode(array('error_text' => 'Your username or password is wrong. Please check'));
	exit;
}

if(!password_verify($password, $user['cl_password'])) {
	http_response_code(401);
	echo json_encode(array('error_text' => 'Your username or password is wrong. Please check'));
	exit;
}


$authCode = hash('sha256', rand(10000000,99999999));
$session = $obj->setSession($authCode, $user['cl_code']);
if(!$session)
{
	http_response_code(401);
	echo json_encode(array('error_text' => 'Some thing went wrong while logging you in. Please try again.'));
	exit;
}

setcookie('token1',$authCode ,time() + (86400 * 30), "/");
setcookie('token2',$user[COLUMN_PREFIX . '_code'] ,time() + (86400 * 30), "/");
http_response_code(200);
echo json_encode(array('message' => 'You are logged in successfully. Please wait while you are being redirectred.', 'type' => $user[COLUMN_PREFIX . '_type']));
exit;