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

include_once "../../includes/auth.php";
$auth = array('customer_admin');
$authRes = checkAuth($auth, $user);
if(!$authRes)
{
    http_response_code(401);
	echo json_encode(array('error_text' => 'Authntication Error'));
	exit;
}
class addAjax extends database
{
    public function index($data)
    {
        $data['cl_password'] = password_hash($data['cl_password'], PASSWORD_DEFAULT);

        $count = $this->current_count();
        $data['cl_user_code'] = $count['cl_prefix'] . '-' . $count['cl_count'];
        $data1['cl_count']=$count['cl_count'] + 1;
        $where1['cl_id']=$count['cl_id'];

        $this->dbh = $this->connectPDO1();
        $this->dbh->beginTransaction();
        try
        {
            if($this->checkEmail($data['cl_email']))
            {
                $this->dbh->rollback();
                return 0;
                exit;
            }
            
            
            if($data['type'] == 'chef')
            {
                $chefCountArray = $this->checkRoleCount($data['cl_id'], 'chef');
                $chefCount = $chefCountArray['chefCount'];
                if($chefCount >= 1)
                {
                   $this->dbh->rollback();
                    return 0;
                    exit;
                }
            }
            else if($data['type'] == 'bar')
            {
                $chefCountArray = $this->checkRoleCount($data['cl_id'], 'bar');
                $chefCount = $chefCountArray['chefCount'];
                if($chefCount >= 1)
                {
                   $this->dbh->rollback();
                    return 0;
                    exit;
                }
            }
            else if($data['type'] == 'runner_head')
            {
                $chefCountArray = v->checkRoleCount($data['cl_id'], 'runner_head');
                $chefCount = $chefCountArray['chefCount'];
                if($chefCount >= 1)
                {
                    $this->dbh->rollback();
                    return 0;
                    exit;
                }
            }
            
            
            $autoID = $this->update1('tb_auto_incre', $data1, $where1);
            if(!$autoID)
            {
                    $this->dbh->rollback();
                    return 0;
                    exit;
            }

            $userID = $this->insert1($this->dbh,'tb_users', $data);
            if(!$userID)
            {
                    $this->dbh->rollback();
                    return 0;
                    exit;
            }

            $where2['cl_id'] = $userID;

            $data2['cl_code']= md5($userID);

            $res = $this->update1('tb_users', $data2, $where2);
            if(!$res)
            {
                    $this->dbh->rollback();
                    return 0;
                    exit;
            }




            $this->dbh->commit();
            return 1;
            exit;
        }
        catch (PDOException $e) {
            // roll back transaction
            $this->dbh->rollback();
            return 0;
        }

            //$this->update('tb_auto_incre', $data1,$where1);
            //return $this->insert('tb_user', $data);
    }

    public function checkEmail($email)
    {
        $where['cl_email'] = $email;
        return $this->fetchRow('tb_users', $where);
    }

    public function current_count()
    {
         return $this->fetchRow('tb_auto_incre', ['cl_type' => 'User']);
    }
    
    public function checkRoleCount($userID, $role)
    {
        $sql = 'SELECT COUNT(*) AS chefCount FROM tb_users WHERE cl_type=? AND cl_user_id=? AND deleted_at IS NULL';
        return $this->callQueryRow($sql, [$role, $userID]);
    }
}


$obj = new addAjax();   

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



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

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

$data['user_id'] = $user['cl_id'];

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


$htmlFields = array('first_name','last_name', 'email', 'password');
$return = $validation->checkHTML($htmlFields, $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;
}

$dateFields = array('birthday');
$return = $validation->checkDate($dateFields, $data, 'd M Y');
if($return)
{
	$res['error_description'][] = $return;
}


$obj = NEW AddAjax();
$emailCheck = $obj->checkEmail($data['email']);
if($emailCheck)
{
	$res['error_description'][] = ['email' => 'Email Already Exists'];
}


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;
}


if($data['type'] != 'chef' && $data['type'] != 'manager' && $data['type'] != 'bar' && $data['type'] != 'runner_head')
{
    $result['error_description'] = ['type' => 'Please enter a valid value'];
	$result['error_text'] = 'Following errors are found';

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

if($data['type'] == 'chef')
{
    $chefCountArray = $obj->checkRoleCount($user['cl_id'], 'chef');
    $chefCount = $chefCountArray['chefCount'];
    if($chefCount >= 1)
    {
        http_response_code(401);
	echo json_encode(array('error_text' => 'Chef count cannot be greater than 1'));
	exit;
    }
}
else if($data['type'] == 'bar')
{
    $chefCountArray = $obj->checkRoleCount($user['cl_id'], 'bar');
    $chefCount = $chefCountArray['chefCount'];
    if($chefCount >= 1)
    {
        http_response_code(401);
	echo json_encode(array('error_text' => 'Bar count cannot be greater than 1'));
	exit;
    }
}
else if($data['type'] == 'runner_head')
{
    $chefCountArray = $obj->checkRoleCount($user['cl_id'], 'runner_head');
    $chefCount = $chefCountArray['chefCount'];
    if($chefCount >= 1)
    {
        http_response_code(401);
	echo json_encode(array('error_text' => 'Runner Head count cannot be greater than 1'));
	exit;
    }
}


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


$res = $obj->index($data);
if(!$res)
{
	http_response_code(401);
	echo json_encode(array('error_text' => 'Something Went Wrong'));
	exit;
}

session_start();
$_SESSION['error_message'] = 'User Added Successfully';
$_SESSION['error_type'] = 'success';

http_response_code(200);
echo json_encode(array('message' => 'User Added Successfully'));
exit;