<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Overtime extends MY_Controller
{
	function __construct()
	{
		parent::__construct();	
		$this->load->model('admin/model_company');
        // $this->load->model('crm/Model_crm');
		$this->load->model('CRM/model_crm');
		$this->load->model('crm/Country');
		$this->load->model('crm/General_model');
		$this->load->model('hr/ot/model_ot');

		$this->logged_user = $this->session->userdata('user');

		if($this->logged_user)
		{
			$this->login->checkModuleAccess(4); //HR
			$this->logged_module = $this->session->userdata('module_data');
		}
		else
		{
			redirect(base_url()); 
		}	 
    }
    
	function index()
	{
		if ($this->isUser()) {
			redirect(base_url('hr/Overtime/yearList')); 
		}elseif ($this->isModerator()) {
			redirect(base_url('hr/Overtime/hodOt')); 
		}

		$data['role'] 		= $this->logged_module['role']; //ok
		$data['month']		= $this->model_crm->getMonth();
		$data['entity']		= $this->model_company->getBusinesses(); //notok
		$data['company'] 	= $this->model_company->getCompanies(1);
		$data['department'] = $this->model_company->getDepartments();
		$data['staff']		= $this->model_user->getUsers();
		$data['page_setup'] = $this->template->pageSetup('HR', 'home', 'Overtime');
		$data['yearList']   = $this->db->query('select distinct year from hr__ot order by year desc')->result();

		
		$this->template->view('hr/overtime/index', $data);
	}

    function yearList() 
	{
		$this->load->model('hr/ot/model_ot');
		$this->session->unset_userdata('groupsList');
		$this->session->unset_userdata('filter_year');
		$this->session->unset_userdata('filter_month');
		$user_id 			= $_SESSION['user']['id'];
		$data['role']		= $this->logged_module['role'];
        $data['page_setup'] = $this->template->pageSetup('HR', 'home', 'Overtime');
        $data['clients']	= $this->model_crm->getCustomer();
        $data['month']		= $this->model_crm->getMonth();
		$data['yearList']   = $this->db->query('select distinct year from hr__ot where peopleID ='.$user_id.' order by year desc')->result();
		$data['yearList2']   = (intval(date('m')) >= 11) ? range(date("Y"), date("Y")+1) : array(date("Y")) ;
		$data['otSubList']	= $this->model_ot->getOTSubList($user_id);
		$this->session->set_userdata('groupsList',$data['otSubList']);
		$this->template->view('hr/overtime/ot-year-list', $data);
    }

	function Rules()
	{
		$data['role'] = $this->logged_module['role'];
		$data['page_setup'] = $this->template->pageSetup('HR', 'home', 'Overtime');

		$this->template->view('hr/overtime/rules', $data);
	}

	function getOTMonth () 
	{
		$this->load->model('hr/ot/model_ot');

        $peopleID   = $this->input->post('peopleID');

		$getOTMonth = $this->model_ot->getOTSubList($peopleID); 
		
        if($getOTMonth)
        {
          print json_encode(array(
                "status"     => "success",
                "OT_month"    => $getOTMonth
            ));

        }
        else
        {
        	 print json_encode(array(
                "status" 	=> "failed",
                "message" 	=>  "failed"
            ));
        }
	}

	function otMonthSave()
	{
		$this->load->model('hr/ot/model_ot');

		$input['year'] 		= $this->input->post('year');
		$input['month'] 	= $this->input->post('month');
		$input['peopleID']	= $_SESSION['user']['id'];
		$input['claim_status'] 	= 0;
		$input['paid_status'] 	= 0;

		$checkExistingOT = $this->model_ot->getOTSubListByMonth($input['peopleID'],$input['month'],$input['year']);

		if($checkExistingOT){
			$data = array(
					'status' => 'failed',
					'msg'=> 'unable to save',
				);
			
			echo json_encode($data);return true;
		}else{

			$inserted_id = $this->model_general->insert('hr__ot', $input);

			if($inserted_id){
				$data = array(
					'status' => 'Success',
					'msg'=> 'OT Submission created.',
				);
			}else{
				$data = array(
					'status' => 'failed',
					'msg'=> 'unable to save',
				);
			}

			echo json_encode($data);return true;
		}
	}

	
	function monthList($otID=0) 
	{	
		$this->load->model('Admin/model_company');

		if($otID==0) return; 
		$data['otID'] 				= $otID;
		$user_id 					= $_SESSION['user']['id'];
		$userDetail 				= $this->model_user->getUsers($user_id);
		$data['name'] 				= $userDetail['name'];
		$data['ic_no'] 				= $userDetail['ic_no'];
		$data['staff_id'] 			= $userDetail['staff_id'];
		$data['department_name']	= $userDetail['department_name'];
		$data['position_name']		= $userDetail['title'];
		$data['role'] 				= $this->logged_module['role'];
		$data['page_setup'] 		= $this->template->pageSetup('HR', 'home', 'Overtime');
		$data['clients']			= $this->model_crm->getCustomer();
		$data['title']				= "My OT";
		$data['rsOt'] 			    = $this->model_general->fetchSingle('hr__ot ', array('*'), array('ID' => $otID));
		$data['otHoursApproved'] 	= $this->model_general->fetchSingle('view_ot ', array('*'), array('otID' => $otID));
		$data['supervisor']         = $this->model_user->getUsers();
		$data['department']         = $this->model_company->getDepartments();

		$select = array('a.*, d.id as deptID, d.name as deptName, b.name as name, e.name as clientName, b.ic_no as ic, b.staff_id as staffID, f.position as position, g.totalHoursApproved, g.totalHoursApplied as totalHoursAppliedTotal, h.totalClaim, h.totalConvertToLeave, i.name as status_by_name, j.name as svName, k.name as svDeptName');
		$where = array( 'a.otID' => $otID,'a.is_delete' => 0);
		$join = array(array('user b','b.id = a.peopleID','left'), 
			array('user__employment_detail c', 'c.user_id = b.id', 'left'),
			array('company__department d', 'd.id = c.department_id', 'left'), 
			array('view_ot g', 'g.otID = a.otID', 'left'), 
			array('customer e', 'e.id = a.clientID', 'left'), 
			array('hr__ot h', 'h.id = a.otID', 'left'),
			array('company__position f', 'f.id = c.position_id', 'left'),
			array('user i','i.id = a.status_by','left'),
			array('user j','j.id = a.svID','left'),
			array('company__department k','k.id = a.svDeptID','left')
		);
		$order = array();

		$data['otLists'] = $this->model_general->fetchAll('hr__ot__detail a', $select, $where, $join, $order);

		if($data['rsOt']['year'] == '2020' && $data['rsOt']['month'] >= 8){
			$this->template->view('hr/overtime/ot_lists_adjust', $data);
		}else if($data['rsOt']['year'] > '2020'){
			$this->template->view('hr/overtime/ot_lists_adjust_2021', $data);
		}else{
			$this->template->view('hr/overtime/ot_lists', $data);
		}
	}

	public function getStaffByDept()
	{
		$dept_id = $this->input->post('dept_id');
    	$this->load->model('hr/ot/model_ot');

    	$data['stafflist']=$this->model_ot->staff_list($dept_id);

    	if($data['stafflist']){
			print json_encode(array(
				"status" => "success",
				"message"	 => $data['stafflist']
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"message"	 => "Error"
			));
		}

	}

	function submitOTDetail() 
	{ 

		$OTDetailID = $this->input->post("otDetailID");

		$data['status'] 	= 1;
		//$data['approved'] 	= 1;

		$updateOTDetailStatus = $this->model_general->update('hr__ot__detail', $data, array('ID'=>$OTDetailID));

		if($updateOTDetailStatus){
			print json_encode(array(
				"status" => "success",
				"msg"	 => "OT Details updated successfully."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to update OT Details."
			));
		}
	}

	function submitOTClaim()
	{

		$otID = $this->input->post("otID");

		$data['claim_status'] 		 = 1;
		// $data['totalClaim'] 		 = $this->input->post("totalClaim");
		$data['totalClaim'] 		 = $this->input->post("totalMealAllowance");
		$data['submitTS']			 = date('Y-m-d H:i:s');
		
		if(!empty($this->input->post("totalConvertToLeave"))){
			$data['totalConvertToLeave'] = $this->input->post("totalConvertToLeave");
		}else{
			$data['totalConvertToLeave'] = 0;
		}

		if(!empty($this->input->post("balanceCarryForward"))){
			$data['balanceCarryForward'] = $this->input->post("balanceCarryForward");
		}else{
			$data['balanceCarryForward'] = 0;
		}
		
		$submitOT = $this->model_general->update('hr__ot', $data, array('ID'=>$otID));

		if($submitOT){
			print json_encode(array(
				"status" => "success",
				"msg"	 => "OT Claim submitted successfully."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to submit OT Claim."
			));
		}
		//$this->yearList();
	}

	function verifyOTClaim()
	{
		$this->load->model('hr/ot/model_ot');

		$otID 							= $this->input->post("otID");
		$user_id                        = $this->input->post("user_id");
		$year                           = $this->input->post("year");
		$data['claim_status'] 		 	= 2;
		$data['totalHoursApproved'] 	= $this->input->post("totalHoursApproved");
		// $data['totalClaim']				= $this->input->post("totalClaim");
		$data['totalClaim']				= $this->input->post("totalMealAllowance");
		$data['updatedBy']	   			= $_SESSION['user']['id'];

		if(!empty($this->input->post("balanceCarryForward"))){
			$data['balanceCarryForward'] = $this->input->post("balanceCarryForward");
		}else{
			$data['balanceCarryForward'] = 0;
		}

		if(!empty($this->input->post("totalConvertToLeave"))){

			$data['totalConvertToLeave'] = $this->input->post("totalConvertToLeave");
			$dataCO                      = $data['totalConvertToLeave'];

			$checkCOAllocation 			 = $this->model_ot->getCOAllocation($user_id,$year);

			if(!empty($checkCOAllocation)){

				$COAllocation            = $this->model_ot->updateCOAllocation($dataCO, $user_id, $year);

			}else{

				$data2['user_id'] 		   = $user_id;
				$data2['year']    		   = $year;
				$data2['type_id']		   = 8;
				$data2['balance_entitled'] = $dataCO;
				$data2['leave_balance']    = $dataCO;
				$data2['created_by']       = $_SESSION['user']['id'];

				$COAllocation              = $this->model_general->insert('hr__leave_allocation', $data2);

			}
			
		}else{
			$data['totalConvertToLeave'] = 0;
		};

		$verifyOTClaim = $this->model_general->update('hr__ot', $data, array('ID'=>$otID));

		if($verifyOTClaim){
			print json_encode(array(
				"status" => "success",
				"msg"	 => "OT Claim verified successfully."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to submit OT."
			));
		}
		//$this->yearList();
	}

	function approveAllOTDetail() 
	{
		$OTDetailID = $this->input->post("otDetailID");

		$data['status'] 	= 1;
		$data['status_by']  = $_SESSION['user']['id'];

		$updateOTDetailStatus = $this->model_general->update('hr__ot__detail', $data, array('ID'=>$OTDetailID));

		if($updateOTDetailStatus){
			print json_encode(array(
				"status" => "success",
				"msg"	 => "All OT Details approved successfully."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to approved all OT Details."
			));
		}
	}

	function approveOT($deptID=0, $year=0, $month=0, $status=0)
	{	
		$data['deptID'] = $deptID;
		$data['year'] = ($year== 0)?date('Y'):$year;
		$data['month'] = ($month == 0)?date('m'):$month;
		$data['status'] = $status;
		$data['months']		= $this->model_crm->getMonth();
		//die(debug($data));

		if($this->isModerator()){
			$data['title'] = "Supervisor OT Approval";
			$userid 			= $_SESSION['log_data']['user_id'];
			$userDetail 		= $this->model_user->getUsers($userid);
			$data['deptID'] 	= $userDetail['department_id'];
			$data['staff']		= $this->model_user->getUsers(1);
			$data['deptStaff']  = $this->model_general->fetchAll('user a', array('a.*'), array('b.department_id' => $data['deptID']), array(array('user__employment_detail b','b.user_id = a.id','left'), array('company__department c', 'c.id = b.department_id', 'left')), array());

		}
		elseif($this->isUser()){
			$data['title'] = "My OT List";
		}else{
			$data['title'] = "Admin OT List";
		}
		
		$userid 					= $_SESSION['log_data']['user_id'];
		$userDetail 				= $this->model_user->getUsers($userid);
		$data['department_name'] 	= $userDetail['department_name'];
		$data['department_id'] 		= $userDetail['department_id'];
		//die(debug($_SESSION['module_data']));
		$data['role']		= $this->logged_module['role'];
		$data['page_setup'] = $this->template->pageSetup('HR', 'home', 'Overtime');
		$data['client'] 	= $this->model_company->getDepartments();
		//$data['staff']		= $this->model_user->getUsers();
		//$data['month']		= $this->model_crm->getMonth();
		$data['company'] 	= $this->model_company->getDepartments();

		
		$select = array('a.*, c.name as department, d.name as name');
		$where 	= array('c.id' => $data['department_id'], 'a.is_delete' => 0);
		$join 	= array(array('user__employment_detail b','b.user_id = a.peopleID','left'), array('company__department c', 'c.id = b.department_id', 'left'),array('user d', 'd.id = b.user_id', 'left'));
		$order 	= array('month' => 'asc', 'year' => 'asc');
		$data['otLists'] = $this->model_general->fetchAll('hr__ot a', $select, $where, $join, $order);

		$temp = array();
		foreach ($data['otLists'] as $key => $ot) {
			$id = $ot['ID'];

			$arr = array(
				'pending' => 0,
				'approve' => 0,
				'reject'  => 0,
				'totalrs' => 0
			);

			$select = array('a.*,b.name as clientName, c.name as name, c.ic_no as ic, c.staff_id as employeeID, e.name as department, f.position as position');
			$where 	= array('otID' => $id);
			$join 	= array(array('customer b','b.id = a.clientID','left'), array('user c', 'c.id = a.peopleID', 'left'), array('user__employment_detail d','d.user_id = a.peopleID','left'), array('company__department e', 'e.id = d.department_id', 'left'), array('company__position f', 'f.id = d.position_id', 'left'));
			$order 	= array(); 

			$data['ot'] = $this->model_general->fetchAll('hr__ot__detail a', $select, $where, $join, $order);
			array_push($temp,$data['ot']);
			
			if($data['ot']) foreach ($data['ot'] as $otStat) {
				if ($otStat['status'] == 0) {
					$arr['pending']++;
				}else if ($otStat['status'] == 1) {
					$arr['approve']++;
				}else if ($otStat['status'] == 2) {
					$arr['reject']++;
				}
				$arr['totalrs'] = $arr['reject'] + $arr['approve'] + $arr['pending'];
			}
			//$data['totalrs'] = $arr['pending'] + $arr['approve'] + $arr['reject'];
			//die(debug($data['totalrs']));
			array_push($data['otLists'][$key],$arr);
			// if(){

			// }
			//die(debug($data['otLists']));
		}//die(debug($data['otLists']));

		$this->template->view('hr/overtime/ot-approve', $data);
	}

	function approveOtList($otID=0)
	{	//die(debug($otID));

		$userid 					= $_SESSION['log_data']['user_id'];
		$userDetail 				= $this->model_user->getUsers($userid);
		$data['otDate'] 			= $this->model_general->fetchSingle('hr__ot ', array('month', 'year'), array('ID' => $otID, 'is_delete' => 0));
		$data['name'] 				= $userDetail['name'];
		$data['ic_no'] 				= $userDetail['ic_no'];
		$data['staff_id'] 			= $userDetail['staff_id'];
		$data['department_name']	= $userDetail['department_name'];
		$data['position_name']		= $userDetail['position_name'];
		$data['staff_id'] 			= $userDetail['staff_id'];
		$data['staff_id'] 			= $userDetail['staff_id'];
		$data['user_name'] 			= $_SESSION['user']['name'];
		$data['role'] 				= $this->logged_module['role'];
		$data['page_setup'] 		= $this->template->pageSetup('HR', 'home', 'Overtime');
		$data['client'] 			= $this->model_company->getDepartments();
		$data['month']				= $this->model_crm->getMonth();

		$select = array('a.*,b.name as clientName, c.name as name, c.ic_no as ic, c.staff_id as employeeID, e.name as department, f.position as position');
		$where 	= array('otID' => $otID);
		$join 	= array(array('customer b','b.id = a.clientID','left'), array('user c', 'c.id = a.peopleID', 'left'), array('user__employment_detail d','d.user_id = a.peopleID','left'), array('company__department e', 'e.id = d.department_id', 'left'), array('company__position f', 'f.id = d.position_id', 'left'));
		$order 	= array(); 

		$data['otLists'] = $this->model_general->fetchAll('hr__ot__detail a', $select, $where, $join, $order);
		
		//die(debug($data['otLists']));
		$this->template->view('hr/overtime/ot-approve-list', $data);
	}

	function adminOt($deptID=0, $year=0, $month=0, $status=0)
	{	
		$this->load->model('hr/ot/model_ot');
		$this->session->unset_userdata('view_ot');
		$this->session->unset_userdata('filter_staff');

		$data['deptID']     = $deptID;
		$data['year'] 		= ($year == 0)?date('Y'): $year;
		$data['month'] 		= ($month == 0)?date('m'): $month;
		$data['status'] 	= $status;
		$data['monthList'] 	= $this->model_crm->getMonth();
		$data['yearList'] 	= $this->db->query('select distinct year from hr__ot')->result();

		$lastDay 	= date('t', strtotime($year.'/'.$month.'/01'));
		$from 		= date('Y-m-d',strtotime($year.'-'.$month.'-01'));
	  	$to 		= date('Y-m-d',strtotime($year.'-'.$month.'-'.$lastDay));

		$data['page_setup'] 		= $this->template->pageSetup('HR', 'home', 'Overtime');
		$data['department'] 		= $this->model_company->getDepartments();
		$data['staff']				= $this->model_user->getUsersByFilter($filters = array('department_id' => $deptID));
		$userid 					= $_SESSION['log_data']['user_id'];
		$userDetail 				= $this->model_user->getUsers($userid);
		$data['department_name'] 	= $userDetail['department_name'];
		$data['department_id'] 		= $userDetail['department_id'];
		$data['claimNotApproved']   = $this->model_ot->getclaimNotApproved($deptID,$data['year'],$data['month']);

		$select 	= array('a.*, a.department as deptName, b.name as name, e.claim_status, e.paid_status, e.submitTS');
		$where 		= array('a.deptID' => $deptID , 'a.month' => $month, 'a.year' => $year);
//		$join		= array(array('user b','b.id = a.peopleID','left'), array('user__employment_detail c', 'c.user_id = b.id', 'left'), array('company__department d', 'd.id = c.department_id', 'left'), array('hr__ot e', 'e.id = a.otID', 'left'));
		$join		= array(array('user b','b.id = a.peopleID','left'), array('company__department d', 'd.id = a.deptID', 'left'), array('hr__ot e', 'e.id = a.otID', 'left'));
		$order 		= array();
		$data['ot'] = $this->model_general->fetchAll('view_ot a', $select, $where, $join, $order);
//echo $this->db->last_query();
		$this->session->set_userdata('view_ot',$data['ot']);

		$this->template->view('hr/overtime/ot-approve', $data);
	}

	function adminOtList($otID =0, $user_id=0)
	{	
		$this->load->model('hr/ot/model_ot');

		$userid 					= $user_id;
		$userDetail 				= $this->model_user->getUsers($userid);
		$data['id'] 				= $userDetail['id'];
		$data['name'] 				= $userDetail['name']; 
		$data['ic_no'] 				= $userDetail['ic_no'];
		$data['staff_id'] 			= $userDetail['staff_id'];
		$data['department_name']	= $userDetail['department_name'];
		$data['position_name']		= $userDetail['title'];
		$data['position']			= $userDetail['position_name'];
		$data['user_name'] 			= $_SESSION['user']['name'];
		$data['role'] 				= $this->logged_module['role'];
		$data['page_setup'] 		= $this->template->pageSetup('HR', 'home', 'Overtime');
		$data['client'] 			= $this->model_crm->getCustomer();
		$data['month']				= $this->model_crm->getMonth();
		$data['rsOt'] 			    = $this->model_general->fetchSingle('hr__ot ', array('*'), array('ID' => $otID));
		$data['prev_balanceCarryForward'] = $this->model_ot->get_prev_balanceCarryForward($user_id);

		$data['OTSummaryByDept'] = $this->model_ot->getOTSummaryByDept($otID);
//var_dump($data['position']);
		$select = array('a.*, d.id as deptID, d.name as deptName, b.name as name, e.name as clientName, b.ic_no as ic, b.staff_id as staffID, f.position as position, g.totalHoursApproved, g.totalHoursApplied as totalHoursAppliedTotal, g.normal, g.rest, g.public, g.weekend, g.weekdays, g.NormalMeal, g.RestMeal, g.PublicMeal, g.WeekendMeal, g.WeekdaysMeal, h.totalClaim, h.totalConvertToLeave, h.claim_status, i.name as status_by_name, j.name as svName, k.name as svDeptName');
		$where = array( 'a.otID' => $otID,'a.is_delete' => 0);
		$join = array(array('user b','b.id = a.peopleID','left'), 
			array('user__employment_detail c', 'c.user_id = b.id', 'left'),
			array('company__department d', 'd.id = c.department_id', 'left'), 
			array('view_ot g', 'g.otID = a.otID', 'left'), 
			array('customer e', 'e.id = a.clientID', 'left'), 
			array('hr__ot h', 'h.id = a.otID', 'left'),
			array('company__position f', 'f.id = c.position_id', 'left'),
			array('user i','i.id = a.status_by','left'),
			array('user j','j.id = a.svID','left'),
			array('company__department k','k.id = a.svDeptID','left'));
		$order = array();
		$data['otLists'] 	   = $this->model_general->fetchAll('hr__ot__detail a', $select, $where, $join, $order);
		
		$data['basicSalary']   = $this->model_ot->getBasicSalary($userid);

		if($data['rsOt']['year'] == '2020' && $data['rsOt']['month'] >= 8){
			$this->template->view('hr/overtime/ot-admin-list_adjust', $data);
		}else if($data['rsOt']['year'] > '2020'){
			$this->template->view('hr/overtime/ot-admin-list_adjust_2021', $data);
		}else{
			$this->template->view('hr/overtime/ot-admin-list', $data);
		}

	}

	function addOvertimeDetail()
	{
		$data['otID'] 			= $this->input->post("otID");
		$otID 					= $data['otID'];
		$data['peopleID'] 		= $_SESSION['user']['id'];
		$data['otDate'] 		= date('Y-m-d', strtotime($this->input->post('DateNew')));
		$data['dayType'] 		= $this->input->post("day_type");
		$data['crossDept'] 		= $this->input->post("crossDept");
		$data['clientID'] 		= $this->input->post("client");
		$data['task'] 			= $this->input->post("task");

		if($this->input->post("supervisor") == NULL){
			$data['svID'] 		= 0;
		}else{
			$data['svID'] 		= $this->input->post("supervisor");
		}
		if($this->input->post("supervisorDept") == NULL){
			$data['svDeptID'] 	= 0;
		}else{
			$data['svDeptID'] 	= $this->input->post("supervisorDept");
		}

		if(!empty($this->input->post("meal_allowance"))){
			$data['mealAllowance']	= $this->input->post("meal_allowance"); 
		}else{
			if(!empty($this->input->post("meal_allowance_id"))){
				$data['mealAllowance']	= $this->input->post("meal_allowance_id");
			}else{
				$data['mealAllowance']	= 0;
			}
			
		};
		
		$data['startTime'] 		= date('H:i:s', strtotime($this->input->post('start_time')));
		$data['endTime'] 		= date('H:i:s', strtotime($this->input->post('end_time')));
		$data['refreshment'] 	= $this->input->post('refreshment'); 
		$data['totalHoursApplied'] 	= $this->input->post("total_hour");

		$insertDetail = $this->model_general->insert('hr__ot__detail', $data);

		if($insertDetail){
			$rsOT =  $this->model_general->fetchSingle('hr__ot', array('*'), array('ID' => $otID));
			$data_main['totalHoursApplied'] = $rsOT['totalHoursApplied'] + $data['totalHoursApplied'];
			$this->model_general->update('hr__ot', $data_main, array('ID' => $otID));
		}

		redirect(base_url('hr/overtime/monthList/'.$otID));
	}

	function editOvertime()
	{	
		$this->load->model('hr/ot/model_ot');

    	$otID					= $this->input->post("otID");
    	$data['peopleID']		= $_SESSION['user']['id'];
		$data['otDate'] 		= date('Y-m-d', strtotime($this->input->post('otDate')));	
		$data['dayType'] 		= $this->input->post("dayType");
		$data['clientID'] 		= $this->input->post("clientID");
		$data['crossDept'] 		= $this->input->post("crossDept");
		
		if($this->input->post("supervisor") == NULL){
			$data['svID'] 		= 0;
		}else{
			$data['svID'] 		= $this->input->post("supervisor");
		}
		if($this->input->post("supervisorDept") == NULL){
			$data['svDeptID'] 	= 0;
		}else{
			$data['svDeptID'] 	= $this->input->post("supervisorDept");
		}	

		$data['task'] 			= $this->input->post("task");
		$data['mealAllowance'] 	= $this->input->post("mealAllowance");
		$data['startTime'] 		= date('H:i:s', strtotime($this->input->post('startTime')));	
		$data['endTime'] 		= date('H:i:s', strtotime($this->input->post('endTime')));	
 		$data['refreshment'] 	= $this->input->post("refreshment");
 		$data['totalHoursApplied'] = $this->input->post("totalHoursApplied");
 		$data['updatedBy']	   = $_SESSION['user']['id'];

 		$updateDetail = $this->model_general->update('hr__ot__detail', $data, array('ID' => $otID));

 		$otIDMain   = $this->model_ot->getMainOTID($otID);
 		$data1['totalHoursApplied'] = $this->model_ot->getTotalHourByOTId($otIDMain->otID);

 		$ok = $this->model_general->update('hr__ot', $data1['totalHoursApplied'], array('ID' => $otIDMain->otID));

 		if($ok)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Overtime updated successfully."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to update Overtime."
				));
			}
	}

	function changeStatus()
	{
		$otID			  = $this->input->post("otID");
		$data['status']   = $this->input->post("status");
		$data['remarks']  = $this->input->post("reason");
		$data['status_by']= $_SESSION['user']['id'];

		$ok = $this->model_general->update('hr__ot__detail', $data, array('ID' => $otID));

 		if($ok)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Overtime updated successfully."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to update Overtime."
				));
			}
	}

	function changeStatusAdmin()
	{
		$otID			  = $this->input->post("otID");
		$data['status']   = $this->input->post("status");
		$data['status_by']= $_SESSION['user']['id'];
		$data['remarks']  = $this->input->post("reason");

		$ok = $this->model_general->update('hr__ot__detail', $data, array('ID' => $otID));

 		if($ok)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Overtime updated successfully."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to update Overtime."
				));
			}
	}

	function changeStatusPaid()
	{
		$otID			       = $this->input->post("otID");
		$data['paid_status']   = $this->input->post("paid_status");
		$data['updatedBy']	   = $_SESSION['user']['id'];

		$ok = $this->model_general->update('hr__ot', $data, array('ID' => $otID));

 		if($ok)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "OT Claim updated successfully."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to update Overtime."
				));
			}
	}

	function payAllOTClaim() 
	{
		$claimID 				= $this->input->post("claimID");

		$data['paid_status'] 	= 1;

		$ok = $this->model_general->update('hr__ot', $data, array('ID'=>$claimID));

		if($ok){
			print json_encode(array(
				"status" => "success",
				"msg"	 => "All OT Claims paid successfully."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to pay all OT Claims."
			));
		}
	}


	function hodOt()
	{	
		$user_id 	= $_SESSION['user']['id'];
		$userDetail = $this->model_user->getUsers($user_id);

		$data = array(
			'page_setup' 		=> $this->template->pageSetup('HR', 'home', 'Overtime'),
			'company'			=> $this->model_company->getBusinesses(),
			'month'				=> $this->model_crm->getMonth(),
			'staff'				=> $this->model_user->getUsersByFilter(array('d.department_id'=> $userDetail['department_id'])), 
			'name'				=> $userDetail['name'],
			'ic_no'				=> $userDetail['ic_no'],
			'staff_id'			=> $userDetail['staff_id'],
			'dept_id' 			=> $userDetail['department_id'],
			'department_name'	=> $userDetail['department_name'],
			'position_name'		=> $userDetail['title'],
		);

		$data['yearList'] = $this->db->query('select distinct year from hr__ot order by year desc')->result();

		$select = array('a.*','e.*', 'b.name as companyName', 'c.year', 'c.month', 
						'c.totalHoursApplied', 'c.totalHoursApproved', 'c.otID','c.noofclaim',
						'c.Pending as Pending',
						'c.Rejected as Rejected',
						'c.Approved as Approved','d.name');
		$join = array(array('view_ot c','a.ID = c.otID','left'),
				array('company__business_entity b','b.id = c.deptID', 'left'),
				array('user d','d.id = c.peopleid','left'),
				array('user__employment_detail e', 'e.user_id = a.peopleID','left'));
		$filters = array('c.deptId' => $userDetail['department_id'],'c.month' => date('n'), 'c.year' => date('Y'));
		$order = array('c.year desc','c.month desc');
		$group = array('b.id', 'c.peopleid', 'c.year', 'c.month'); 

		$data['otStaffLists'] 	= $this->model_general->fetchAll('hr__ot a', $select, $filters, $join, $order, $group);

		//job supervised
		$data['otStaffLists2'] 	= $this->model_ot->getOTSupervised($user_id, $userDetail['department_id']);

		$this->template->view('hr/overtime/hod-ot', $data);
	}

	function hodOtList($otID=0, $user_id=0)
	{
		$userid 					= $user_id;
		$data['user_id'] 			= $user_id;
		$userDetail 				= $this->model_user->getUsers($userid);
		$data['rsOt'] 				= $this->model_general->fetchSingle('hr__ot ', array('month', 'year','claim_status'), array('ID' => $otID, 'is_delete' => 0));
		//$data['rsOt'] 			    = $this->model_general->fetchSingle('hr__ot ', array('*'), array('ID' => $otID));
		$data['name'] 				= $userDetail['name'];
		$data['ic_no'] 				= $userDetail['ic_no'];
		$data['staff_id'] 			= $userDetail['staff_id'];
		$data['department_name']	= $userDetail['department_name'];
		$data['position_name']		= $userDetail['title'];
		$data['user_name'] 			= $_SESSION['user']['name'];
		$data['role'] 				= $this->logged_module['role'];
		$data['page_setup'] 		= $this->template->pageSetup('HR', 'home', 'Overtime');
		$data['client'] 			= $this->model_crm->getCustomer();
		$data['month']				= $this->model_crm->getMonth();
		$data['title']				= "HOD OT Lists";

		$select = array('a.*,b.name as clientName, c.name as name, c.ic_no as ic, c.staff_id as employeeID, d.title, e.name as department, f.position as position, g.totalHoursApproved, h.claim_status, i.name as status_by_name, j.name as svName, k.name as svDeptName');
		$where 	= array('a.otID' => $otID, 'a.is_delete' => 0);
		$join 	= array(array('customer b','b.id = a.clientID','left'), 
				array('user c', 'c.id = a.peopleID', 'left'), 
				array('user__employment_detail d','d.user_id = a.peopleID','left'), 
				array('company__department e', 'e.id = d.department_id', 'left'), 
				array('view_ot g', 'g.otID = a.otID', 'left'),
				array('hr__ot h', 'h.ID = a.otID', 'left'), 
				array('company__position f', 'f.id = d.position_id', 'left'),
				array('user i','i.id = a.status_by','left'),
				array('user j','j.id = a.svID','left'),
				array('company__department k','k.id = a.svDeptID','left')
		);
		$order 	= array(); 

		$data['otLists'] 	   = $this->model_general->fetchAll('hr__ot__detail a', $select, $where, $join, $order);
		$data['countOTListSV'] = $this->model_ot->getCountOTListSV($otID);

		if($data['rsOt']['year'] == '2020' && $data['rsOt']['month'] >= 8){
			$this->template->view('hr/overtime/ot-approve-list_adjust', $data);
		}else if($data['rsOt']['year'] > '2020'){
			$this->template->view('hr/overtime/ot-approve-list_adjust_2021', $data);
		}else{
			$this->template->view('hr/overtime/ot-approve-list', $data);
		}
	}

	function hodOtListSv($otID=0, $user_id=0)
	{
		$userid 					= $user_id;
		$data['user_id'] 			= $user_id;
		$userDetail 				= $this->model_user->getUsers($userid);
		$data['rsOt'] 				= $this->model_general->fetchSingle('hr__ot ', array('month', 'year','claim_status'), array('ID' => $otID, 'is_delete' => 0));
		$data['name'] 				= $userDetail['name'];
		$data['ic_no'] 				= $userDetail['ic_no'];
		$data['staff_id'] 			= $userDetail['staff_id'];
		$data['department_name']	= $userDetail['department_name'];
		$data['position_name']		= $userDetail['title'];
		$data['user_name'] 			= $_SESSION['user']['name'];
		$data['role'] 				= $this->logged_module['role'];
		$data['page_setup'] 		= $this->template->pageSetup('HR', 'home', 'Overtime');
		$data['client'] 			= $this->model_crm->getCustomer();
		$data['month']				= $this->model_crm->getMonth();
		$data['title']				= "HOD OT Lists";

		$select = array('a.*,b.name as clientName, c.name as name, c.ic_no as ic, c.staff_id as employeeID, d.title, e.name as department, f.position as position, g.totalHoursApproved, h.claim_status, i.name as status_by_name, j.name as svName, k.name as svDeptName');
		$where 	= array('a.otID' => $otID, 'a.is_delete' => 0);
		$join 	= array(array('customer b','b.id = a.clientID','left'), 
				array('user c', 'c.id = a.peopleID', 'left'), 
				array('user__employment_detail d','d.user_id = a.peopleID','left'), 
				array('company__department e', 'e.id = d.department_id', 'left'), 
				array('view_ot g', 'g.otID = a.otID', 'left'),
				array('hr__ot h', 'h.ID = a.otID', 'left'), 
				array('company__position f', 'f.id = d.position_id', 'left'),
				array('user i','i.id = a.status_by','left'),
				array('user j','j.id = a.svID','left'),
				array('company__department k','k.id = a.svDeptID','left')
		);
		$order 	= array(); 

		$data['otLists'] = $this->model_general->fetchAll('hr__ot__detail a', $select, $where, $join, $order);

		if($data['rsOt']['year'] == '2020' && $data['rsOt']['month'] >= 8){
			$this->template->view('hr/overtime/ot-approve-listSv_adjust', $data);
		}else if($data['rsOt']['year'] > '2020'){
			$this->template->view('hr/overtime/ot-approve-listSv_adjust_2021', $data);
		}else{
			$this->template->view('hr/overtime/ot-approve-listSv', $data);
		}
		
	}

	function otClaim()
	{
		$user_id 			= $_SESSION['user']['id'];
		$data['month']		= $this->model_crm->getMonth();
		$data['yearList']   = $this->db->query('select distinct year from hr__ot where peopleID ='.$user_id.' order by year desc')->result();
		$data['page_setup'] = $this->template->pageSetup('HR', 'home', 'Overtime');

		$data['otSubList']	= $this->model_ot->getOTSubList($user_id);

		$this->template->view('hr/overtime/my_ot_claim', $data);
	}

	function otClaimList($otID=0)
	{
		$this->load->model('hr/ot/model_ot');

		$data['page_setup'] = $this->template->pageSetup('HR', 'home', 'Overtime');
		$data['rsOt'] 		= $this->model_general->fetchSingle('hr__ot ', array('*'), array('ID' => $otID));

		$data['otID'] 				= $otID;
		$user_id 					= $_SESSION['user']['id'];
		$userDetail 				= $this->model_user->getUsers($user_id);
		$data['name'] 				= $userDetail['name'];
		$data['ic_no'] 				= $userDetail['ic_no'];
		$data['staff_id'] 			= $userDetail['staff_id'];
		$data['department_name']	= $userDetail['department_name'];
		$data['position_name']		= $userDetail['title'];
		$data['position']			= $userDetail['position_name'];

		$data['OTSummaryByDept'] = $this->model_ot->getOTSummaryByDept($otID);

		$select = array('a.*, d.id as deptID, d.name as deptName, b.name as name, e.name as clientName, b.ic_no as ic, b.staff_id as staffID, f.position as position, g.totalHoursApproved, g.totalHoursApplied as totalHoursAppliedTotal, h.totalClaim, h.totalConvertToLeave, h.claim_status, g.normal, g.rest, g.public, g.weekend, g.weekdays, g.NormalMeal, g.RestMeal, g.PublicMeal, g.WeekendMeal, g.WeekdaysMeal, i.name as status_by_name, j.name as svName, k.name as svDeptName');
		$where = array( 'a.otID' => $otID,'a.is_delete' => 0);
		$join = array(array('user b','b.id = a.peopleID','left'), 
			array('user__employment_detail c', 'c.user_id = b.id', 'left'),
			array('company__department d', 'd.id = c.department_id', 'left'), 
			array('view_ot g', 'g.otID = a.otID', 'left'), 
			array('customer e', 'e.id = a.clientID', 'left'), 
			array('hr__ot h', 'h.id = a.otID', 'left'),
			array('company__position f', 'f.id = c.position_id', 'left'),
			array('user i','i.id = a.status_by','left'),
			array('user j','j.id = a.svID','left'),
			array('company__department k','k.id = a.svDeptID','left'));
		$order = array();

		$data['otLists'] 	         = $this->model_general->fetchAll('hr__ot__detail a', $select, $where, $join, $order);
		$data['basicSalary']         = $this->model_ot->getBasicSalary($user_id);
		$data['otPendingDetails']	 = $this->model_ot->getPendingOTDetails($otID);
		$data['prev_balanceCarryForward'] = $this->model_ot->get_prev_balanceCarryForward($user_id);
		// echo $this->db->last_query();
		// die(debug($data['prev_balanceCarryForward'][0]->balanceCarryForward));

		if($data['rsOt']['year'] == '2020' && $data['rsOt']['month'] >= 8){
			$this->template->view('hr/overtime/my_ot_claim_list_adjust', $data);
		}else if($data['rsOt']['year'] > '2020'){
			$this->template->view('hr/overtime/my_ot_claim_list_adjust_2021', $data);
		}else{
			$this->template->view('hr/overtime/my_ot_claim_list', $data);
		}
		
	}

	function deleteOvertime($ID=0, $otID=0)
	{
		$this->load->model('hr/ot/model_ot');

		$otID = $this->input->post("otID");

		$data['is_delete'] 	= 1;
		$data['updatedBy']	= $_SESSION['user']['id'];

		$this->model_general->update('hr__ot__detail', $data, array('ID'=>$otID));

		$otIDMain   = $this->model_ot->getMainOTID($otID);
 		$data1['totalHoursApplied'] = $this->model_ot->getTotalHourByOTId($otIDMain->otID);

 		$ok = $this->model_general->update('hr__ot', $data1['totalHoursApplied'], array('ID' => $otIDMain->otID));

 		if($ok)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Overtime deleted successfully."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to delete Overtime."
				));
			}

		//$this->monthList($otID);
	}

	function convertTimestamp()
	{
		//var_dump($this->input->post("startTime"));
		$data['startTime'] 		= date('H:i:s', strtotime($this->input->post("startTime")));
		$data['endTime'] 		= date('H:i:s', strtotime($this->input->post("endTime")));

		if($data)
		{
			print json_encode(array(
				"status" => "Success",
				"calculateHours" => $data
			)); 
		} 
		else 
		{
			print json_encode(array(
				"status" => "failed",
				"calculateHours" => $data
			)); 
		}
	}

	function getOTDate() 
	{
		$this->load->model('hr/ot/model_ot');

        $peopleID    = $this->input->post('peopleID');
        $otDate 	 = $this->input->post('otDate');

		$otDateCheck = $this->model_ot->getOtDate($peopleID, $otDate); 
		
        if($otDateCheck)
        {
          print json_encode(array(
                "status"     => "success",
                "OT_date"    => $otDateCheck
            ));

        }
        else
        {
        	 print json_encode(array(
                "status" 	=> "failed",
                "message" 	=>  "failed"
            ));
        }	
	}

	function checkCOAllocation()
	{
		$this->load->model('hr/ot/model_ot');

		$user_id   = $this->input->post('user_id');
		$year      = $this->input->post('year');

		$COAllocation = $this->model_ot->getCOAllocation($user_id,$year);

		if($COAllocation)
        {

          	print json_encode(array(
                "status"     	=> "success",
                "COAllocation"  => $COAllocation
            ));
        }
        else
        {
        	
        	print json_encode(array(
                "status" 	=> "failed",
                "message" 	=>  "failed"
            ));
        }	
	}

	public function getStaffList()
	{
		$department_id = $this->input->post('department_id');
    	$this->load->model('hr/ot/model_ot');
    	$data['stafflist']=$this->model_ot->getStaffListByDept($department_id);
    	//echo $this->db->last_query();
    	print json_encode(array("status"=>"success", "message"=>$data['stafflist']));
	}

	public function getStatus()
	{	
		$this->load->model('hr/ot/model_ot');
		
		$otDetail_id = $this->input->post('id');
		$detailStatusData = $this->model_ot->getStatusByDetailID($otDetail_id);

		if($detailStatusData)
        {
          	print json_encode(array(
                "status" 	=> "success",
                "detailStatusData"	=> $detailStatusData
            ));

        }
        else
        {
        	print json_encode(array(
                "status" 	=> "failed",
                "message" 	=>  "failed"
            ));
        }
	}

	private function isModerator()
	{
		if ($_SESSION['module_data']['role'] != 'moderator') {
			return false;
		}
		return true;
	}

	private function isUser()
	{
		if ($_SESSION['module_data']['role'] != 'user') {
			return false;
		}
		return true;
	}

	public function isAdmin()
	{
		if ($_SESSION['module_data']['role'] != 'admin') {
			return false;
		}
		return true;
	}

	


}