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

class Api_staffmovement extends MY_Controller
{
	private $isValidUser = false;
	function __construct() 
	{
		echo "Hello 1";
		$this->load->module('template');
		$this->load->model('hr/model_sfmove','staff');
		$this->load->model('admin/model_user');
		$this->load->model('admin/model_company','company');
		$this->load->helper('jwt_helper');
		$this->load->model('CRM/model_crm','customer');
		$this->load->model('analysis/model_analysis','model_analysis'); //Fakru Add for analysis purpose


		/**
		 * token ni selalu ada error dekat sesetengah user, lebih baik buang jer
		 */
		$token = explode('.', $this->input->post('token'));
		list($headb64, $bodyb64, $cryptob64) = $token;
		$payload = json_e_decode(urlsafe_base64_decode($bodyb64));

		if(count($payload) >= 0)
		{
			$user_id = $payload[0]->user_id;
		}

		$key = $this->model_user->getUserToken($user_id);
		$isValidToken = jwt_decode($this->input->post('token'),$key->id_token,true);

		if($token)
		{
			$this->isValidUser = true;
		}else{
			$data = array(
				'status' => 'failed',
				'message'=>	'invalid token',
				'user_id'=>$user_id,
				'isValidToken'=>$payload
			);

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

	function index()
	{
		echo "Hello";
	}

	function editGroup()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		{
			$group_id 		= $this->input->post('groupid');
			$date 			= $this->input->post('date');
			$dept_id 		= $this->input->post('deptid');
			$client_id 		= $this->input->post('clientid');
			$destination 	= $this->input->post('destination');
			$type_id 		= $this->input->post('typeid');
			$desc 			= $this->input->post('desc'); 
			$staff 			= json_decode($this->input->post('staff'));

			$replacement_date = $this->input->post('replacement_date');
			$replacement_start= $this->input->post('replacement_start');
			$replacement_end  = $this->input->post('replacement_end');
		}

		$newDate = DateTime::createFromFormat('d-m-Y',$date);
		$groupdata 	= array
		(
			'customerid'	=>	$client_id,
			'date'			=> 	$newDate->format('Y-m-d'),
			'description'	=> 	$desc,
			'destination'	=> 	$destination,
			'movementType'	=>	$type_id
		);

		$detaildata = array();
		foreach ($staff as $stf) 
		{
			if(!empty($stf[0]->detailid)) 
			{
				$tmp = array
				(
					'detailid'	=> 	$stf[0]->detailid,
					'staffid'	=>	$stf[0]->staffId,
					'timeOut'	=>	date('G:i',strtotime($stf[0]->timeout)),
					'timeIn'	=>	date('G:i',strtotime($stf[0]->timein))
				);
			}else{
				$tmp = array
				(
					'detailid'	=> 	null,
					'staffid'	=>	$stf[0]->staffId,
					'timeOut'	=>	date('G:i',strtotime($stf[0]->timeout)),
					'timeIn'	=>	date('G:i',strtotime($stf[0]->timein))
				);
			}
			array_push($detaildata, $tmp);
		}

		//--------------- remove staff if the staff is removed from the edit group form
		{ 
			$staff_involved = $this->staff->getMovementStaff(null,null,null,null,null,null,null,null,null,$group_id);
			
			foreach ($staff_involved as $key => $staff) 
			{
					$is_removed = true;
					foreach ($detaildata as $key => $staff_input) 
					{

						if($staff->detailid == $staff_input['detailid'])
						{
							$is_removed = false;
						}
					}
					if($is_removed)
					{
						$this->staff->removeDetail($group_id,$staff->staffid,$staff->detailid);
					}
					
			}
		}
		//------------ remove staff if the staff is been removed from the edit group form 

		if(!empty($replacement_date) && !empty($replacement_start) && !empty($replacement_end))
		{
			$replace_date = DateTime::createFromFormat('d-m-Y',$replacement_date);
			$replacement_data = array
			(
				'date' 		=> $replace_date->format('Y-m-d'),
				'time_in'	=> date('G:i',strtotime($replacement_start)),
				'time_out'	=> date('G:i',strtotime($replacement_end))
			);
			$this->staff->editReplacement($replacement_data,$group_id);
		}


		if ($this->staff->editMovement($groupdata, $detaildata,$group_id)) 
		{
			$data = array
			(
				'status' 	=> 'success',
				'message'	=> 'update staff movement'
			);
		}else{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'unable to update staff movement'
			);
		}

		echo json_encode($data);
		return true;
	}
	
	function changeTime()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		{
			$id 		= $this->input->post('id');
			$groupid 	= $this->input->post('groupid');
			$staffid 	= $this->input->post('staffid');
			$timeout 	= date('G:i',strtotime($this->input->post('timeout')));
			$timein		= date('G:i',strtotime($this->input->post('timein')));
		}

		$data = array
		(
			'status' 		=> 	'success',
			'message'		=> 	'this is the message',
			'updated_row'	=> 	$this->staff->updateMovementTime(null,$groupid,$staffid,$timeout,$timein)
		);

		echo json_encode($data);
		return true;
	}

	function remove()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}


		$groupid = $this->input->post('groupid');
		$staffid = ($this->input->post('staffid'))?$this->input->post('staffid'):null;

		$this->staff->removeMovement($groupid,$staffid);	
		$data = array
		(
			'status'	=> 'success',
			'message'	=> 'data have been removed'
		);
		echo json_encode($data);
		return true;
	}

	function get()
	{
		$this->session->unset_userdata('movementLists');
		$this->session->unset_userdata('filter_start_date');
		$this->session->unset_userdata('filter_end_date');
		$this->session->unset_userdata('filter_type');
		$this->session->unset_userdata('filter_client');
		$this->session->unset_userdata('filter_dept');
		$this->session->unset_userdata('filter_staff');
		$this->session->unset_userdata('filter_client');

		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		{
			$start_date 	= (!empty($this->input->post('start_date')))?$this->input->post('start_date'):null;
			$end_date 		= (!empty($this->input->post('end_date')))?$this->input->post('end_date'):null;
			$dept_id		= (!empty($this->input->post('dept_id')) && $this->input->post('dept_id') != -1)?$this->input->post('dept_id'):null;
			$staff_id		= (!empty($this->input->post('staff_id')) && $this->input->post('staff_id') != -1)?$this->input->post('staff_id'):null;
			$type_id 		= (!empty($this->input->post('type_id')) && $this->input->post('type_id') != -1)?$this->input->post('type_id'):null;
			$customer_id 	= (!empty($this->input->post('customer_id')) && $this->input->post('customer_id') != -1)?$this->input->post('customer_id'):null;
		}
		
		if ($start_date != null) 
		{
			$temp = $start_date;
			$start_date = date("Y-m-d", strtotime($temp));
			$this->session->set_userdata('filter_start_date',$start_date);
		}else{
			$this->session->set_userdata('filter_start_date','ALL');

		}

		if ($end_date != null) 
		{
			$temp = $end_date;
			$end_date = date("Y-m-d", strtotime($temp));
			$this->session->set_userdata('filter_end_date',' - '.$end_date);
		}else{
			$this->session->set_userdata('filter_end_date','');
		}

		$data = array
		(
			'status' 	=> 'success',
			'message'	=> '',
			'table'		=> $this->staff->getMovementStaff(null, $customer_id, null, $start_date, $end_date, null, $type_id, $staff_id,$dept_id,null)
		);
		$this->session->set_userdata('movementLists',$data['table']);
		
		if($dept_id){
			$department = $this->company->getDepartments(null,$dept_id);
			$this->session->set_userdata('filter_dept',strtoupper($department['name']));
		}

		if($staff_id){
			$staff = $this->model_user->getUsers($staff_id);
			$this->session->set_userdata('filter_staff',strtoupper($staff['name']));
		}

		if($type_id){
			$movement = $this->staff->getMoveType($type_id);
			$this->session->set_userdata('filter_type',strtoupper($movement[0]->movementType));
		}

		if($customer_id){
			//create query to get customer id
			$customer = $this->customer->getCustomer($customer_id);
			$this->session->set_userdata('filter_client',strtoupper($customer[0]->name));
		}
		echo json_encode($data);
		return true;
	}

	function getGroup()
	{
		$this->session->unset_userdata('groupsList');
		$this->session->unset_userdata('filter_start_date');
		$this->session->unset_userdata('filter_end_date');
		$this->session->unset_userdata('filter_type');
		$this->session->unset_userdata('filter_client');
		$this->session->unset_userdata('filter_department');

		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		{
			$start_date 	= (!empty($this->input->post('start_date')))?$this->input->post('start_date'):null;
			$end_date 		= (!empty($this->input->post('end_date')))?$this->input->post('end_date'):null;
			$type_id 		= (!empty($this->input->post('type_id')) && $this->input->post('type_id') != -1)?$this->input->post('type_id'):null;
			$customer_id 	= (!empty($this->input->post('customer_id')) && $this->input->post('customer_id') != -1)?$this->input->post('customer_id'):null;
			$department_id 	= (!empty($this->input->post('department_id')) && $this->input->post('department_id') != -1)?$this->input->post('department_id'):null;
		}

		if ($start_date != null) 
		{
			$temp = $start_date;
			$start_date = date("Y-m-d", strtotime($temp));
		}

		if ($end_date != null) 
		{
			$temp = $end_date;
			$end_date = date("Y-m-d", strtotime($temp));
		}

		$data = array
		(
			'status' 	=> 	'success',
			'message'	=>	'' ,
			// 'table'		=>	$this->staff->getGroups(null, $customer_id,null, $start_date,$end_date,null,$type_id),
			'table'		=> $this->staff->getMovement(null,$customer_id,null,$start_date,$end_date,null,$type_id,null,$department_id,null),

		);
		$this->session->set_userdata('groupsList',$data['table']);

		if($start_date){
			$this->session->set_userdata('filter_start_date',$start_date);
		}else{
			$this->session->set_userdata('filter_start_date','ALL');
		}


		if($end_date){
			$this->session->set_userdata('filter_end_date',' - '.$end_date);

		}else{
			$this->session->set_userdata('filter_end_date','');
		}

		if($type_id){
			$movement = $this->staff->getMoveType($type_id);
			$this->session->set_userdata('filter_type',strtoupper($movement[0]->movementType));
		}

		if($type_id){
			$this->session->set_userdata('filter_department',$department_id);
		}

		if($customer_id){
			$customer = $this->customer->getCustomer($customer_id);
			$this->session->set_userdata('filter_client',$customer[0]->name);
		}

		echo json_encode($data);
		return true;
	}

	function create()
	{
		
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		{
			$date 			= $this->input->post('date');
			$dept_id 		= $this->input->post('deptid');
			$client_id 		= $this->input->post('clientid');
			$destination 	= $this->input->post('destination');
			$type_id 		= $this->input->post('typeid');
			$desc 			= $this->input->post('desc'); 
			$staff 			= json_decode($this->input->post('staff'));
			$created_by 	= $this->input->post('createdby');
			$date_replace 	= $this->input->post('date_replacement');
			$timein_replace = $this->input->post('timein_replacement');
			$timeout_replace= $this->input->post('timeout_replacement');
		}


		$newDate = DateTime::createFromFormat('d-m-Y',$date);	
		$groupdata = array
		(
			'customerid'	=> $client_id,
			'date'			=> $newDate->format('Y-m-d'),
			'description'	=> $desc,
			'destination'	=> $destination,
			'created_by'	=> $created_by,
			'department_id'	=> $dept_id,
			'movementType'	=> $type_id,
		);

		$detaildata = array();
		foreach ($staff as $stf) 
		{
			$tmp = array
			(
				'staffid'	=>	$stf[0]->staffId,
				'timeOut'	=>	date('G:i',strtotime($stf[0]->timeout)),
				'timeIn'	=>	(date('G:i',strtotime($stf[0]->timein)) != '0:00')?date('G:i',strtotime($stf[0]->timein)):'24:00'
			);
			array_push($detaildata, $tmp);
		}

		if ($id = $this->staff->createMovement($groupdata,$detaildata)) 
		{
			$data = array
			(
				'status' 	=> 'success',
				'message'	=> 'success create a new movement',
				'group_id'	=> $id,
				'table'		=> $this->staff->getMovementStaff(null,null,null,null,null,null,null,null,null,$id)
			);

			$detailContent 	= 	array();

			if(!empty($data['table'])) foreach ($data['table'] as $key => $content) 
			{
				if($key == 0)
				{
					$groupcontent['id'] 			= $content->id;
					$groupcontent['customerid'] 	= $content->customerid;
					$groupcontent['date']			= date('d-m-Y',strtotime($content->date));
					$groupcontent['description']	= $content->description;
					$groupcontent['destination']	= $content->destination;
					$groupcontent['movementType']	= $content->movementType;
					if($content->customerid != -1){
					$groupcontent['customerName']	= $content->customerName;	
					}else{
					$groupcontent['customerName']	= 'others';	
					}
					$groupcontent['departmentId']	= $content->movementDept;
				}
				
				$detailTemp = array
				(
					'name' 			=> $content->staffName,
					'department'	=> $content->departmentName,
					'position' 		=> $content->staffPosition,
					'timeout'		=> $content->timeOut,
					'timein'		=> $content->timeIn,
				);

				array_push($detailContent,$detailTemp);
			}

			$this->staff->create_replacement($id,date('Y-m-d',strtotime($date_replace)),date('G:i',strtotime($timein_replace)),date('G:i',strtotime($timeout_replace)));

			//----------------------------------------------------------------------------
			//	send email for approval to manager method
			//----------------------------------------------------------------------------
			// @TODO :
			//			- change this to send email to moderator for the department [DONE]
			// @NOTE :
			//	   		- Encik Aizat doesnt receive notification for this movement when it commented because he is admin not a moderator
			//			- There is also a cahnce that a manager is a normal user, so he will not receive notification if he is normal user
			//----------------------------------------------------------------------------

			$manager = $this->company->getCurrentPosition($groupcontent['departmentId'],12);
			$body = 'createstaffmovement';
			if(!empty($manager))
			{
				foreach ($manager as $key => $mgr) {
					$email_data = array
					(
						'email'   		=>  $mgr->email,
						'subject' 		=> 'Approval for staff movement',
						'group'			=>  $groupcontent,
						'detail'		=> 	$detailContent,
					);
					$env = $this->config->item('env');
					if($env == 'production'){
						$this->template->sendMail($email_data, $body);
					}
				}
			}

			//------------------------------------------------------------------------
			// send email for approval to moderator
			//------------------------------------------------------------------------
			// @todo :
			//		- replace method for sending email to manager to moderator
			//
			//------------------------------------------------------------------------

			$moderator = $this->company->getDepartmentModerator($groupcontent['departmentId'],4);

			$body = 'createstaffmovement';

			if($moderator)
			{
				foreach ($moderator as $key => $mode) 
				{
					$email_data = array
					(
						'email'   =>  $mode->email,
						'subject' => 'Approval for staff movement',
						'group'	  =>  $groupcontent,
						'detail'  =>  $detailContent,
					);
					
					$env = $this->config->item('env');
					if($env == 'production'){
						$this->template->sendMail($email_data, $body);
					}
				}
			}
			//end sending email to moderator
			$this->model_analysis->add_save($created_by,2); //Fakru Add for analysis purpose
		}else{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'error create a new movement',
			);
		}				
		echo json_encode($data);
		return true;
	}

	function createGroup()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$data = array
		(
			'status' 	=> 'success',
			'message' 	=> 'success create new group',
		);

		echo json_encode($data);
		return true;

	}

	function getDetails($edit = '')
	{
		$groupid = $this->input->post('groupid');
		if($edit == 'edit')
		{
			$movement = $this->staff->getMovementStaff_detail($groupid,null,null,null,null,null,null,null,null,null);
		}else{
			$movement = $this->staff->getMovementStaff($groupid,null,null,null,null,null,null,null,null,null);
		}

		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		
		if($movement != 'no result'){
			$data = array
			(
				'status' 		=> 'success',
				'message'	 	=> '',
				'group'			=> $this->staff->getGroups($groupid,null,null,null,null,null,null)[0],
				'table'			=> ($edit == 'edit')?$this->staff->getMovementStaff_detail(null,null,null,null,null,null,$movement[0]->typeid,null,null,$groupid):$this->staff->getMovementStaff(null,null,null,null,null,null,$movement[0]->typeid,null,null,$groupid)
			);
			$data['similar'] = $this->staff->getGroups(null, $data['table'][0]->customerid,null,null,null,null,$movement[0]->typeid);

		}else{
			$data = array
			(
				'status' 		=> 'success',
				'message'	 	=> '',
				'group'			=> $this->staff->getGroups($groupid,null,null,null,null,null,null)[0],
				'table'			=> ($edit == 'edit')?$this->staff->getMovementStaff(null,null,null,null,null,null,null,null,null,$groupid):$this->staff->getMovementStaff(null,null,null,null,null,null,null,null,null,$groupid)
			);
			$data['similar'] = $this->staff->getGroups();	
		}
		

		echo json_encode($data);
		return true;
	}

	function filterCalendar()
	{
		$date 		= ($this->input->post('date') && $this->input->post('date') != '')? date('Y-m-d',strtotime($this->input->post('date'))) : date('Y-m-d');
		$dept_id 	= ($this->input->post('dept_id') && $this->input->post('dept_id') != '-1')?$this->input->post('dept_id'):null;
		$type_id	= ($this->input->post('type_id') && $this->input->post('type_id') != '-1')?$this->input->post('type_id'):null;
		$client_id	= ($this->input->post('client_id') && $this->input->post('client_id') != '-1')?$this->input->post('client_id'):null;

		$movements = $this->staff->getMovement(null,$client_id,$date,null,null,null,$type_id,null,$dept_id,null);

		$fc_res 	= array();
		$fc_event 	= array();

		if($movements != 'no result')
		{
			foreach ($movements as $key => $move) 
			{
				$tmpRes 		= new stdClass(); $tmpEvent = new stdClass();
				$tmpRes->id  	= $move->staffid;
				$tmpRes->title 	= $move->staffName;

				$tmpEvent->id 			= $key;
				$tmpEvent->resourceId 	= $move->staffid;
				$tmpEvent->start 		= $move->date.' '.$move->timeOut;
				$tmpEvent->end 			= $move->date.' '.$move->timeIn;
				$tmpEvent->title 		= $move->customerName;
				$tmpEvent->color 		= $move->color_code;
                $tmpEvent->movement_type= $move->movementType;
				$tmpEvent->movement_date= $move->date;					
				$tmpEvent->destination = $move->destination;

				array_push($fc_res, $tmpRes);
				array_push($fc_event, $tmpEvent);
			}
		}


		$data = array(
			'date'			=> $date,
			'dept_id'		=> $dept_id,
			'type_id'		=> $type_id,
			'client_id'		=> $client_id,
			'fc_res'		=> json_encode($fc_res),
			'fc_event'		=> json_encode($fc_event)
		);

		echo json_encode($data);
		return true;
	}
	
	function changeStatus()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}	
		$groupid 	= $this->input->post('group_id');
		$status  	= $this->input->post('status');
		$updateBy 	= $this->input->post('update_by');

		if(!$this->staff->updateStatus($groupid,$status,$updateBy)){
			$data = array(
				'status' => 'failed',
				'message'=> 'unable to update status');
		}else{
			$data = array(
				'status' => 'success',
				'message'=> 'status have been updated'
				);
		}
		echo json_encode($data);
		return true;
    }
    
    /**
	 * Updated 	: farouq zakwan bin zulkifli
	 * date 	: 26 February 2019 
	 */
	function getUserMovementBetweenDate()
	{
		$input = $this->input->post();
		$data = array
		(
			'status'	=> 'ok',
			'input'		=> $input,
			// 'results'	=> ($this->staff->getMovement(null, null,null,$input['date_from'],$input['date_to'],null,null,$input['user_id'],null,null) != 'no result')?$this->staff->getMovement(null, null,null,$input['date_from'],$input['date_to'],null,null,$input['user_id'],null,null):null
			'results'	=> $this->staff->getUserMovementBetweenDate($input['date_from'],$input['date_to'],$input['user_id'],false),
		);

		echo json_encode($data);return true;
    }
    
    function getEightHourUserMovementBetweenDate()
	{
		$input = $this->input->post();
		$data = array
		(
			'status'	=> 'ok',
			'input'		=> $input,
			// 'results'	=> ($this->staff->getMovement(null, null,null,$input['date_from'],$input['date_to'],null,null,$input['user_id'],null,null) != 'no result')?$this->staff->getMovement(null, null,null,$input['date_from'],$input['date_to'],null,null,$input['user_id'],null,null):null
			'results'	=> $this->staff->getUserMovementBetweenDate($input['date_from'],$input['date_to'],$input['user_id'],true),
		);

		echo json_encode($data);return true;
	}

	//date : 20190926 - start
	function getUserMovementByDate()
	{
		$user_id = $this->input->post('user');
		$date = $this->input->post('date');

		$data = array(
			'status'	=> 'ok',
			// 'results'	=> $this->staff->getMovementStaff(null,null,$date,null,null,null,null,$user_id,null,null),
			// 'result'	=> $this->staff->getMovement(null,null,$date,null,null,null,null,$user_id,null,null),
			'results'	=> $this->staff->getUserMovement($date,$user_id),
			'user_id'	=> $user_id,
			'date'		=> $date
		);
		echo json_encode($data);return;
	}
	//date : 20190926 - end

	function testingApiMovement()
	{
		echo "here api movement";
		die();
	}
}
?>