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

class Serviceform extends MY_Controller
{
	function __construct()
	{
		parent::__construct();

		if($this->logged_user = $this->session->userdata('user')){
			$this->login->checkModuleAccess(4);
			
			$this->logged_module = $this->session->userdata('module_data');
			
			$this->load->model('hr/model_form');
			$this->load->model('admin/model_company');
			$this->load->model('hr/model_service_form');
			$this->load->model('hr/model_approval');
			$this->load->model('hr/model_hotel');
			$this->load->model('hr/model_complaint');
			$this->load->model('CRM/model_crm');
		}else{
			redirect(base_url());
		}
	}
	
	function index()
	{
		$fc_event 	= array();
		$resource 	= array();

		$bookingCalendar = $this->model_form->getBooking();

		if(!empty($bookingCalendar))
		{
			foreach ($bookingCalendar as $key => $details) 
			{
				$startDate  = $details['start_date'];
				$endDate    = $details['end_date'];
				
				$tmpEvent = array();

				$tmpEvent['id'] 			= $key;
				$tmpEvent['resourceId'] 	= $details['requester_id'];
				$tmpEvent['start'] 			= $startDate;
				$tmpEvent['end'] 			= date('Y-m-d',strtotime($endDate."+1 days"));
				$tmpEvent['title'] 			= $details['department_name'];
				$tmpEvent['description']	= $details['department_name'].' request "'.$details['title'].'".';
				$tmpEvent['color']			= '#'.$details['color_code'];
				$tmpEvent['textColor']		= '#ffffff';

				array_push($fc_event, $tmpEvent);
				array_push($resource, $details);
			}
		}

		$data = array
		(
			'page_setup'			=> $this->template->pageSetup('Service Form', '', 'Service Form'),
			'forms'					=> $this->model_form->getForms(array('a.status'=>0)),
			// 'count_status'		=> $this->model_form->get_sv_status(),
			'booking_calendar'		=> $bookingCalendar,
			'booking_name'			=> $this->model_form->getBookingName(),
			// 'customer'				=> $this->model_crm->getCustomerActiveDormantOnly(),
			'fc_event'				=> json_encode($fc_event),
			'resource'				=> json_encode($resource),
			'categories' 			=> $this->model_general->fetchAll('hr__policyprocedure_category', array(), array('parent_id' => 0, 'is_delete' => 0)),
			'count_complaint'		=> $this->model_form->countComplaint(),
			'count_complaint_hod'	=> $this->model_form->countComplaint_hod($this->session->userdata('user')['department_id']),
			'get_hod'				=> $this->model_form->getHod($this->session->userdata('user')['department_id']),
			'business_entity'		=> $this->model_company->getBusinesses(),
			// 'count_finance'		=> $this->model_form->countFinanceForm(),
		);

		$this->template->view('hr/policyprocedure/service_form', $data);
	}

	function onlineForm($formName = null)
	{
		if($formName === null){
			$this->index();
		}else{
		/* $data['stationeryDetails'] = $this->model_service_form->getServiceStationery();
			//die(debug($data['stationeryDetails']));

			$data['page_setup'] = $this->template->pageSetup('Online Form', '', $formName);
			$this->template->view('hr/policyprocedure/form/'.$formName.'_list', $data); */ 
			redirect(base_url('hr/serviceform/'.$formName));
		}
	}

	function crm_submit()
	{
		$ID = $this->input->post('compname');

		redirect(base_url('crm/crm/timeline/'.$ID));
	}

	function stationery_list()
	{
		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access 	= $this->model_user->getUserByModuleAccess($filter1)[0];
        $year			= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');

		$this->load->model('hr/model_stationery');
		$data['department']						= $this->model_company->getDepartments();
		$data['rsStationeryRequestList'] 		= $this->model_stationery->getStationeryRequestList();
		$data['rsStationeryList'] 				= $this->model_stationery->getStationeryList();
		$data['rsStationeryBookingRequestList'] = $this->model_stationery->getStationeryBookingRequestList();
		//die(debug($this->session->userdata('user')));

		if($module_access['access_lvl'] == 'admin' || $this->logged_user['division_id'] == 4){
			$data['stationeryRequestList_new']		= $this->model_stationery->getStationeryList_new(null,null,$year);
		}
		else{
			$data['stationeryRequestList_new']		= $this->model_stationery->getStationeryList_new(null,$this->session->userdata('user')['id'],$year);
		}

		foreach ($data['stationeryRequestList_new'] as $key => $value) 
		{
			
			if(!empty($value['quantity']))
			{ 
				$data['stationeryRequestList_new'][$key]['qty'] = explode(',',$value['quantity']); 
			}else{
				$data['stationeryRequestList_new'][$key]['qty'] = '';
			}

			if(!empty($value['description']))
			{ 
				$data['stationeryRequestList_new'][$key]['desc'] = explode(',',$value['description']); 
			}else{
				$data['stationeryRequestList_new'][$key]['desc'] = '';
			}

			if(!empty($value['package']))
			{ 
				$data['stationeryRequestList_new'][$key]['pck'] = explode(',',$value['package']); 
			}else{
				$data['stationeryRequestList_new'][$key]['pck'] = '';
			}

			if(!empty($value['category_name']))
			{ 
				$data['stationeryRequestList_new'][$key]['category'] = explode(',',$value['category_name']); 
			}else{
				$data['stationeryRequestList_new'][$key]['category'] = '';
			}
		}

		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Stationery Request List');
		$this->template->view('hr/policyprocedure/form/stationery_list', $data);
	}

	function stationery_form($ID=0)
	{
		$this->load->model('hr/model_stationery','model_stationery');

		$data['ID']	= $ID; 
		// die(debug($data['ID']));

		$data['rsMasterStationeryReq'] 		= $this->model_stationery->getMasterStationeryReq($ID);
		$data['stationeryCategoryDetails'] 	= $this->model_stationery->getStationeryDetails($ID);
		$data['rsStationeryItem'] 			= $this->model_stationery->getAllStationeryItem($ID);

		// debug($data['rsMasterStationeryReq']);
		
		//else $data['stationeryCategoryDetails'] 	= $this->model_stationery->getStationeryCategoryDetails();
		//die(debug($data['rsMasterStationeryReq']));
	    $filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl'] == 'admin' || $this->logged_user['division_id'] == 4){
	        if(!empty($ID)){
	            $data_approval['tblname'] 		= 'sv__stationery';
	            $data_approval['ID'] 			= $ID;
	            $data_approval['link'] 			= 'stationery_form';
	            $data_approval['form_name'] 	= 'Stationery Request';
	            $data_approval['rsApproval'] 	= $this->model_approval->getApproval(array('a.table_name'=>'sv__stationery','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
	    }

		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Stationery Request Form');

		$this->template->view('hr/policyprocedure/form/stationery', $data);
	}

	function stationery_save()
	{
        $this->load->model('hr/model_stationery'); 
        
        $stationeryID = $this->input->post('stationery_id');
		
		$insertData = array(
			// 'user_id'    						=> $this->input->post('reqName_id'),
			// 'department_id'  					=> $this->input->post('department_id'),
			'date_taken'						=> date('Y-m-d',strtotime($this->input->post('datetaken'))),
			'updatedBY'     					=> $this->logged_user['id'],
			'updatedTS'     					=> date('Y-m-d H:i:s'),
        );

        // die(debug($insertData['date_taken']));
        
        $where = array 
		(
			'ID' => $stationeryID,
		);
		
		$newStationery = $this->model_general->insert('sv__stationery',$insertData,$where);

		// die(debug($newStationery));

		if($newStationery){

			$insertDataDetail = array(
						'sv_stationery_id'    				=> $newStationery,
					);

			$newStationeryDetail = $this->model_general->insert('sv__stationery__detail',$insertDataDetail);
		} else {
			return false;
		}

		redirect(base_url('/hr/serviceform/stationery_form/'.$stationeryID));
	}

	function get_stationery_list()
	{
		$this->load->model('hr/model_stationery');

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

		// die(debug($input));

		$data['stationeryCategoryDetails']	= $this->model_stationery->getStationeryCategoryDetails($input['categoryID']);

		$data['stationeryPackage'] = $this->model_stationery->getStationeryPackageDetails($input['packageGroupID']);
		//die(debug($data['stationeryCategoryDetails']));
		
		if($data['stationeryCategoryDetails'])
		{
			print json_encode(array(
				"status" 	=> "Success",
				"msg"	 	=> "Successfully get stationery details .",
				"details" 	=> $data
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to get stationery details."
			));
		}
	}

	function stationery_details_save()
	{
		$this->load->model('hr/model_stationery');
		$stationeryID = $this->input->post('stationery_id');

		// die(debug($stationeryID));

		$insertData = array(
		  'sv_stationery_category_detail_id'=> $this->input->post('listStationeryType'),
		  'quantity'					 	=> $this->input->post ('quantity'),
		  'category_package_id' 			=> $this->input->post ('package_group'),
		  'sv_stationery_id'				=> $this->input->post ('stationery_id'),
		  'createdBY' 						=> $this->logged_user['id']
		);

		$newStationeryDetails = $this->model_general->insert('sv__stationery__detail', $insertData);

		if(!empty($newStationeryDetails))
		{
			$this->session->set_flashdata('success',"Successfully request new stationery. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to request new stationery.");
		}
		
		redirect(base_url('/hr/serviceform/stationery_form/'.$stationeryID));
	}

	function stationery_edit_details_save()
	{
		$this->load->model('hr/model_stationery');

		$stationeryID = $this->input->post('stationery_id');
		$stationeryDetailID = $this->input->post('stationeryDetailID_edit');

		$data['stationeryBookingList'] = $this->model_stationery->getStationeryBookingList($stationeryDetailID);

		// die(debug($stationeryDetailID));

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

		// die(debug($input));

		$sets = array
		(
			'sv_stationery_category_detail_id'	=> $this->input->post('listStationeryType_edit'),
			'quantity' 							=> $this->input->post ('quantity_edit'),
			'category_package_id' 				=> $this->input->post ('package_group_edit'),
			'updatedBY'     					=> $this->logged_user['id'],
			'updatedTS'     					=> date('Y-m-d H:i:s'),
		);

		// die(debug($sets));

		$where = array 
		(
			'ID' => $stationeryDetailID,
		);

		// die(debug($where));

		$affected_rows = $this->model_stationery->update_stationery_details($sets,$where);
		// die(debug($affected_rows));
		
		if(!empty($affected_rows))
		{
			$this->session->set_flashdata('success',"Successfully update stationery. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update stationery.");
		}
		
		redirect(base_url('/hr/serviceform/stationery_form/'.$stationeryID));
	}

	function stationery_details_edit()
	{
		$this->load->model('hr/model_stationery');

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

		$sets = array
		(
            'date_taken'						=> date('Y-m-d',strtotime($this->input->post('datetaken'))),
			'updatedBY'     					=> $this->logged_user['id'],
			'updatedTS'     					=> date('Y-m-d H:i:s'),
		);

		$where = array 
		(
			'ID' => $stationeryID,
		);

		$affected_rows = $this->model_stationery->update_stationery($sets,$where);
		//die(debug($affected_rows));
		if(!empty($affected_rows))
		{
			$user_email 			= array();
			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$this->input->post('reqName_id')))[0];
			$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));

			$form_detail = array
			(
				'name' 					=> $this->input->post('reqName'),
				'email_address'			=> ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']),
				'department'			=> $this->input->post('department'),
				'date_request'  		=> $this->input->post('datereq'),
				'date_taken'  			=> $this->input->post('datetaken'),
			);

			$admin_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 4'));
			if($admin_detail) foreach($admin_detail as $admin_email) 
			{
				array_push($user_email, ($admin_email['primary_email']) ? $admin_email['primary_email'] : (($admin_email['secondary_email']) ? $admin_email['secondary_email'] : $admin_email['email']));
			}
			
			$form_requestor_name 	= $this->model_user->getUserDetail($this->input->post('reqName_id'))['name'];

			if($user_email)
			{
				$emailSubject 		= 'Stationery Request - '.$form_requestor_name.' ['.str_pad($stationeryID,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $form_requestor_name.' has request stationery on '.$this->input->post('datereq').'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->session->set_flashdata('success',"Thank you for your requets.");
		}else{
			$this->session->set_flashdata('error',"System failed to submit requested stationery.");
		}

		redirect(base_url('hr/serviceform/stationery_list'));
	}

	function deleteStationeryListForm()
	{
		$this->load->model('hr/model_stationery');

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

		// die(debug($stationery_id));

		$sets = array
		(
			'is_delete'   => 1,
			'updatedBY'     => $this->logged_user['id'],
			'updatedTS'   => date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $stationery_id,
		);

		$affected_rows = $this->model_stationery->update_stationery_details($sets,$where);

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

	function deleteStationeryList()
	{
		$this->load->model('hr/model_stationery');

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

		$sets = array
		(
			'is_delete'  	=> 1,
			'updatedBY'    	=> $this->logged_user['id'],
			'updatedTS'	 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $stationeryID,
		);

		$affected_rows = $this->model_stationery->update_stationery($sets,$where);

		if($affected_rows)
		{
			$this->model_approval->update_sv_status('sv__stationery',$stationeryID);

			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted request item ."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete request item."
			));
		}
	}

	function stationery_list_save()
	{
        $this->load->model('hr/model_stationery');

		$insertData = array(
			'user_id'               => $this->input->post('reqName_id'),
			'department_id'         => $this->input->post('department_id'),
			'date_taken'			=> date('Y-m-d',strtotime($this->input->post('date_taken'))),
			'createdTS '            => date('Y-m-d',strtotime($this->input->post('datereq'))),
			'createdBY'             => $this->logged_user['id']
		);
		
        // die(debug($insertData['date_taken']));
		$newStationery = $this->model_general->insert('sv__stationery',$insertData);

		if($newStationery)
		{
			$this->model_approval->updateOrCreateNew('sv__stationery',$newStationery,'Pending',0);

			print json_encode(array(
				"status" 		=> "Success",
				"msg"  			=> "Successfully add new form.",
				"redirect"		=> base_url('/hr/serviceform/stationery_form/'.$newStationery)
			)); 
		}
		else
		{
			print json_encode(array(
				"status" 		=> "Error",
				"msg"  			=> "System failed to add new form",
				"redirect"		=> base_url('/hr/serviceform/stationery_list')
			));
		}
	}

	function stationery_new_details_save()
	{
		$input = $this->input->post();
		$new_detail_category 	= $input['new_detail_category'];
		$new_detail_type 		= $input['new_detail_type'];
		$stationeryID 			= $input['new_detail_stationery_id'];

		$insert = array
		(
			'category_id'	=> $new_detail_category,
			'description'	=> $new_detail_type,
		);

		$new_detail = $this->model_general->insert('sv__stationery__category_detail',$insert);

		if($new_detail)
		{
			$this->session->set_flashdata('success',"Successfully add new stationery detail. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new stationery detail. Please try again.");
		}

		redirect(base_url('hr/serviceform/stationery_form/'.$stationeryID));
	}

	function stationery_detail_setup()
	{
		$this->load->model('hr/model_stationery');

		$data = array
		(
			'page_setup'					=> $this->template->pageSetup('Online Form', '', 'Stationery Detail Package Setup'),
			'stationery_category' 			=> $this->model_stationery->getStationeryItemDetail(),
			'stationery_package'			=> $this->model_stationery->getStationeryPackageDetails(0,true),
		);
		// debug($data['stationery_category']);
		// die();
		$this->template->view('hr/policyprocedure/form/stationery_item_setup', $data);
	}

	function stationery_save_category()
	{
		$input = $this->input->post();

		if($input['mode'] == 'new')
		{
			$insert = array
			(
				'category_name'		=> $input['category'],
				'package_group_id'	=> $input['package_id'],
			);

			$submitStationeryCategory = $this->model_general->insert('sv__stationery__category',$insert);
		}elseif($input['mode'] == 'delete'){
			$update = array
			(
				'is_delete'		=> 1,
			);

			$where = array('ID' => $input['cat_id']);

			$submitStationeryCategory = $this->model_general->update('sv__stationery__category',$update,$where);
		}else{ // update
			$update = array
			(
				'category_name'		=> $input['category'],
				'package_group_id'	=> $input['package_id'],
			);

			$where = array('ID' => $input['cat_id']);

			$submitStationeryCategory = $this->model_general->update('sv__stationery__category',$update,$where);
		}

		if($submitStationeryCategory)
		{
			print json_encode(array(
				"status" 	=> "success",
				"msg"	 	=> "Successfully submit stationery category.",
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "error",
				"msg"	 => "Failed to submit stationery category.",
			));
		}
	}

	function stationery_save_item()
	{
		$input = $this->input->post();
		
		if($input['mode'] == 'new')
		{
			$insert = array
			(
				'category_id'	=> $input['category_id'],
				'description'	=> $input['item'],
				'price'			=> $input['price'],
			);

			$submitStationeryCategory = $this->model_general->insert('sv__stationery__category_detail',$insert);
		}elseif($input['mode'] == 'delete'){
			$update = array
			(
				'is_delete'		=> 1,
			);

			$where = array('ID' => $input['item_id']);

			$submitStationeryCategory = $this->model_general->update('sv__stationery__category_detail',$update,$where);
		}else{ // update
			$update = array
			(
				'description'	=> $input['item'],
				'price'			=> $input['price'],
			);

			$where = array('ID' => $input['item_id']);

			$submitStationeryCategory = $this->model_general->update('sv__stationery__category_detail',$update,$where);
		}

		if($submitStationeryCategory)
		{
			print json_encode(array(
				"status" 	=> "success",
				"msg"	 	=> "Successfully submit stationery item detail.",
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "error",
				"msg"	 => "Failed to submit stationery item detail.",
			));
		}
	}

	function maintenance_list()
	{
		$this->load->model('hr/model_maintenance'); 
		$MaintenanceList 	= $this->model_maintenance->getMaintenanceRequestList();
		$year				= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');
		// die(debug($MaintenanceList));

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

		if(!empty($MaintenanceList))
		{
			foreach ($MaintenanceList as $key => $detail) 
			{
				$createdTS  = date('Y-m-d',strtotime($detail['createdTS']));
				$fixedDate    = $detail['date_fixed'];
				
				$tmpRes 					= array(); $tmpEvent = array();
				$tmpRes['id']  				= $detail['ID'];
				$tmpRes['title'] 			= $detail['dept_name'].'/'.$detail['branchName'];

				$tmpEvent['id'] 			= $key;
				$tmpEvent['resourceId'] 	= $detail['user_id'];
				$tmpEvent['start'] 			= $createdTS;
				$tmpEvent['end'] 			= date('Y-m-d',strtotime($fixedDate."+1 days"));
				$tmpEvent['title'] 			= $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']	= $detail['dept_name'].' request to perform "'.$detail['complain_category'].'" maintenance.';

				if($detail['complain_category'] == 'Lights')
				{
					$tmpEvent['color']			= '#0033cc';
				}

				if($detail['complain_category'] == 'Aircond')
				{
					$tmpEvent['color']			= '#0099ff';
				}

				if($detail['complain_category'] == 'Washroom')
				{
					$tmpEvent['color']			= '#00b359';
				}

				if($detail['complain_category'] == 'Copier Machine')
				{
					$tmpEvent['color']			= '#009900';
				}

				if($detail['complain_category'] == 'Furniture')
				{
					$tmpEvent['color']			= '#ff9900';
				}

				if($detail['complain_category'] == 'Others General')
				{
					$tmpEvent['color']			= '#9900cc';
				}

				if($detail['complain_category'] == 'Cleanliness Floor')
				{
					$tmpEvent['color']			= '#ff3300';
				}

				if($detail['complain_category'] == 'Other')
				{
					$tmpEvent['color']			= '#990099';
				}

				$tmpEvent['textColor']		= '#ffffff';

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

		$complain = array
		(
			$datas = array
			(
				'Complaint' 	=> 'Lights',
				'color_code' 	=> '#0033cc',
				'short_name'	=> 'LT',
			),

			$datas = array
			(
				'Complaint' 	=> 'Aircond',
				'color_code' 	=> '#0099ff',
				'short_name'	=> 'A/C',
			),

			$datas = array
			(
				'Complaint' 	=> 'Washroom',
				'color_code' 	=> '#00b359',
				'short_name'	=> 'WC',
			),

			$datas = array
			(
				'Complaint' 	=> 'Copier Machine',
				'color_code' 	=> '#009900',
				'short_name'	=> 'CPM',
			),

			$datas = array
			(
				'Complaint' 	=> 'Furniture',
				'color_code' 	=> '#ff9900',
				'short_name'	=> 'FURN',
			),

			$datas = array
			(
				'Complaint' 	=> 'Cleanliness Floor',
				'color_code' 	=> '#ff3300',
				'short_name'	=> 'CLN FLR',
			),

			$datas = array
			(
				'Complaint' 	=> 'Others General',
				'color_code' 	=> '#9900cc',
				'short_name'	=> 'OTH GNRL',
			),

			$datas = array
			(
				'Complaint' 	=> 'Other',
				'color_code' 	=> '#990099',
				'short_name'	=> 'OTH',
			),
		);

		foreach($complain as $ckey => $cval)
		{
			$complain[$ckey]['total_request'] = $this->model_maintenance->getCountMaintenanceList($cval['Complaint'],$year)[0]['total_request'];
		}

		$data = array
		(
			'page_setup'		=> $this->template->pageSetup('Online Form', '', 'Maintenance Request List'),
			//'rsMaintenanceList'	=> $this->model_maintenance->getMaintenanceRequestList(),
			'department' 		=> $this->model_company->getDepartments(),
			'complain'			=> $complain,
			'fc_res'			=> json_encode($fc_res),
			'fc_event'			=> json_encode($fc_event),
			'resource'			=> json_encode($resource),
		);

		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl']=='admin' || $this->logged_user['division_id'] == 4){
			$data['rsMaintenanceList']		= $this->model_maintenance->getMaintenanceRequestList(null,null,$year);
		}
		else{
			$data['rsMaintenanceList']		= $this->model_maintenance->getMaintenanceRequestList(null,$this->session->userdata('user')['id'],$year);
		}

		$this->template->view('hr/policyprocedure/form/maintenance_list', $data);
	}

	function maintenance_calendar()
	{
		$this->load->model('hr/model_maintenance');

		$maintenanceDetail	= $this->model_maintenance->getMaintenanceRequestList();
		$fc_res 	= array();
		$fc_event 	= array();
		$resource 	= array();

		if(!empty($maintenanceDetail))
		{
			foreach ($maintenanceDetail as $key => $detail) 
			{
				$createdTS  = date('Y-m-d',strtotime($detail['createdTS']));
				$fixedDate    = $detail['date_fixed'];
				
				$tmpRes 					= array(); $tmpEvent = array();
				$tmpRes['id']  				= $detail['ID'];
				$tmpRes['title'] 			= $detail['dept_name'].'/'.$detail['branchName'];

				$tmpEvent['id'] 			= $key;
				$tmpEvent['resourceId'] 	= $detail['user_id'];
				$tmpEvent['start'] 			= $createdTS;
				$tmpEvent['end'] 			= date('Y-m-d',strtotime($fixedDate."+1 days"));
				$tmpEvent['title'] 			= $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']	= $detail['dept_name'].' request to perform "'.$detail['complain_category'].'" maintenance.';

				if($detail['complain_category'] == 'Lights')
				{
					$tmpEvent['color']			= '#0033cc';
				}

				if($detail['complain_category'] == 'Aircond')
				{
					$tmpEvent['color']			= '#0099ff';
				}

				if($detail['complain_category'] == 'Washroom')
				{
					$tmpEvent['color']			= '#00b359';
				}

				if($detail['complain_category'] == 'Copier Machine')
				{
					$tmpEvent['color']			= '#009900';
				}

				if($detail['complain_category'] == 'Furniture')
				{
					$tmpEvent['color']			= '#ff9900';
				}

				if($detail['complain_category'] == 'Others General')
				{
					$tmpEvent['color']			= '#9900cc';
				}

				if($detail['complain_category'] == 'Cleanliness Floor')
				{
					$tmpEvent['color']			= '#ff3300';
				}

				if($detail['complain_category'] == 'Other')
				{
					$tmpEvent['color']			= '#990099';
				}

				$tmpEvent['textColor']		= '#ffffff';

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

		$complain = array
		(
			$datas = array
			(
				'Complaint' 	=> 'Lights',
				'color_code' 	=> '#0033cc',
			),

			$datas = array
			(
				'Complaint' 	=> 'Aircond',
				'color_code' 	=> '#0099ff',
			),

			$datas = array
			(
				'Complaint' 	=> 'Washroom',
				'color_code' 	=> '#00b359',
			),

			$datas = array
			(
				'Complaint' 	=> 'Copier Machine',
				'color_code' 	=> '#009900',
			),

			$datas = array
			(
				'Complaint' 	=> 'Furniture',
				'color_code' 	=> '#ff9900',
			),

			$datas = array
			(
				'Complaint' 	=> 'Cleanliness Floor',
				'color_code' 	=> '#ff3300',
			),

			$datas = array
			(
				'Complaint' 	=> 'Others General',
				'color_code' 	=> '#9900cc',
			),

			$datas = array
			(
				'Complaint' 	=> 'Other',
				'color_code' 	=> '#990099',
			),
		);
			
		$data = array
		(
			'page_setup' 		=> $this->template->pageSetup('Online Form', '', 'Maintenance Request Calendar'),
			'calendar_detail'	=> $fc_event,
			'complain'			=> $complain,
			'fc_res'			=> json_encode($fc_res),
			'fc_event'			=> json_encode($fc_event),
			'resource'			=> json_encode($resource),
		);

		// debug($data['complain']);
		// die();
		
		$this->template->view('hr/policyprocedure/calendar/maintenance_calendar', $data);
	}

	function maintenance_form($ID=null)
	{
		$this->load->model('hr/model_maintenance'); 
		
		$maintenanceDetail	= $this->model_maintenance->getMaintenanceRequestList();
		$fc_res 	= array();
		$fc_event 	= array();
		$resource 	= array();

		if(!empty($maintenanceDetail))
		{
			foreach ($maintenanceDetail as $key => $detail) 
			{
				$start_date  	= date('Y-m-d',strtotime($detail['createdTS']));
				$end_date   	= $detail['date_fixed'];
				
				$tmpRes 					= array(); $tmpEvent = array();
				$tmpRes['id']  				= $detail['ID'];
				$tmpRes['title'] 			= $detail['dept_name'].'/'.$detail['branchName'];

				$tmpEvent['id'] 			= $key;
				$tmpEvent['resourceId'] 	= $detail['user_id'];
				$tmpEvent['start'] 			= $start_date;
				$tmpEvent['end'] 			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title'] 			= $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']	= $detail['dept_name'].' request to perform "'.$detail['complain_category'].'" maintenance.';

				if($detail['complain_category'] == 'Lights')
				{
					$tmpEvent['color']			= '#0033cc';
				}

				if($detail['complain_category'] == 'Aircond')
				{
					$tmpEvent['color']			= '#0099ff';
				}

				if($detail['complain_category'] == 'Washroom')
				{
					$tmpEvent['color']			= '#00b359';
				}

				if($detail['complain_category'] == 'Copier Machine')
				{
					$tmpEvent['color']			= '#009900';
				}

				if($detail['complain_category'] == 'Furniture')
				{
					$tmpEvent['color']			= '#ff9900';
				}

				if($detail['complain_category'] == 'Others General')
				{
					$tmpEvent['color']			= '#9900cc';
				}

				if($detail['complain_category'] == 'Cleanliness Floor')
				{
					$tmpEvent['color']			= '#ff3300';
				}

				if($detail['complain_category'] == 'Other')
				{
					$tmpEvent['color']			= '#990099';
				}

				$tmpEvent['textColor']		= '#ffffff';

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

		$complain = array
		(
			$datas = array
			(
				'Complaint' 	=> 'Lights',
				'color_code' 	=> '#0033cc',
				'short_name'	=> 'LT',
			),

			$datas = array
			(
				'Complaint' 	=> 'Aircond',
				'color_code' 	=> '#0099ff',
				'short_name'	=> 'A/C',
			),

			$datas = array
			(
				'Complaint' 	=> 'Washroom',
				'color_code' 	=> '#00b359',
				'short_name'	=> 'WC',
			),

			$datas = array
			(
				'Complaint' 	=> 'Copier Machine',
				'color_code' 	=> '#009900',
				'short_name'	=> 'CPM',
			),

			$datas = array
			(
				'Complaint' 	=> 'Furniture',
				'color_code' 	=> '#ff9900',
				'short_name'	=> 'FURN',
			),

			$datas = array
			(
				'Complaint' 	=> 'Cleanliness Floor',
				'color_code' 	=> '#ff3300',
				'short_name'	=> 'CLN FLR',
			),

			$datas = array
			(
				'Complaint' 	=> 'Others General',
				'color_code' 	=> '#9900cc',
				'short_name'	=> 'OTH GNRL',
			),

			$datas = array
			(
				'Complaint' 	=> 'Other',
				'color_code' 	=> '#990099',
				'short_name'	=> 'OTH',
			),
		);
        
        $data = array
        (
			'page_setup'			=> $this->template->pageSetup('Online Form', '', 'Maintenance Request Form'),
			'ID' 					=> $ID,
			'maintenanceDetails' 	=> $this->model_maintenance->getMaintenanceDetails($ID),
			'listAdmin' 			=> $this->model_maintenance->getAdminList(),
			'complain'				=> $complain,
			'upcoming_request'		=> $this->model_maintenance->getMaintenanceByWeek(),
			'fc_res'				=> json_encode($fc_res),
			'fc_event'				=> json_encode($fc_event),
			'resource'				=> json_encode($resource),
        );

        $filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl'] == 'admin' || $this->logged_user['division_id'] == 4){
	        if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__maintenance';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'maintenance_list';
	            $data_approval['form_name'] = 'Maintenance Request';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__maintenance','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
	    }

		$this->template->view('hr/policyprocedure/form/maintenance', $data);
	}

	function maintenance_save()
	{
		$insertData = array(
			'user_id'    		=> $this->input->post('reqName_id'),
            'department_id'  	=> $this->input->post('department_id'),
            'createdTS'	        => date('Y-m-d',strtotime($this->input->post('reqDate'))),
			'office_unit'  		=> $this->input->post('officeUnit'),
			'floor'  			=> $this->input->post('maintenanceFloor'),
			'complain_category' => $this->input->post('complaintCategory'),
			'problem'  			=> $this->input->post('prob'),
			'createdBY' 		=> $this->logged_user['id']
		);

		$newMaintenance = $this->model_general->insert('sv__maintenance',$insertData);

		$this->load->library('File_upload');

		$upload_directory = 'assets/upload/hr/Form/maintenanceForm/';

		$upload_status = $this->file_upload
			->set_file_type(FILE_TYPE_UPLOAD)
			->set_directory_public()
			->set_upload_directory($upload_directory)
			->uploads('picture_upload');

		if(is_array($upload_status)) 
		{
			$uploadPhoto = array
			(
				'photo_title'         	=> (!empty($upload_status['file_name']))? $upload_status['file_name']:'',
				'sv_maintenance_id'     => $newMaintenance,
				'file_location'     	=> (!empty($upload_status['file_name']))?$upload_directory:'', 
				'is_delete'         	=> 0,
			);

			$newMaintenance2 = $this->model_general->insert('sv__maintenance__photo',$uploadPhoto);
		} else {
			echo 'Upload Failed. Please Try Again.';
		}

		if(!empty($newMaintenance) || !empty($newMaintenance2))
		{
			$form_detail = array 
			(
				'name' 					=> $this->input->post('reqName'),
				'email_address'			=> $this->input->post('email'),
				'department'			=> $this->input->post('department'),
				'date_request'			=> $this->input->post('reqDate'),
				'office_unit'  			=> $this->input->post('officeUnit'),
				'floor'  				=> $this->input->post('maintenanceFloor'),
				'complaint_category' 	=> $this->input->post('complaintCategory'),
				'problem'  				=> $this->input->post('prob'),
			);

			$user_email 	= array();
			$admin_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 4'));
			if($admin_detail) foreach($admin_detail as $admin_email) 
			{
				array_push($user_email, ($admin_email['primary_email']) ? $admin_email['primary_email'] : (($admin_email['secondary_email']) ? $admin_email['secondary_email'] : $admin_email['email']));
			}

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

			$send_copy_form_email = (isset($send_email_checkbox) && $send_email_checkbox == 'on')?$send_email_checkbox:'off';

			if($send_copy_form_email == 'on')
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$this->input->post('reqName_id')))[0];
				$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			}
			
			$form_requestor_name 	= $this->model_user->getUserDetail($this->input->post('reqName_id'))['name'];

			if($user_email)
			{
				$emailSubject 		= 'New Maintenance Request - '.$form_requestor_name.' ['.str_pad($newMaintenance,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $form_requestor_name.' has request maintenance services on '.$this->input->post('reqDate').'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->model_approval->updateOrCreateNew('sv__maintenance',$newMaintenance,'Pending',0);

			$this->session->set_flashdata('success',"Successfully add new request for maintenance. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new request for maintenance. Please try again.");
		}

		redirect(base_url('hr/serviceform/maintenance_list'));
	}

	function maintenance_edit()
	{
		$this->load->model('hr/model_maintenance');

		$maintID 	= $this->input->post('maintenanceID');
		$pictID 	= $this->input->post('picture_id');

		$updateData = array(
			'office_unit'  		=> $this->input->post('officeUnit'),
			'floor'  			=> $this->input->post('maintenanceFloor'),
			'complain_category' => $this->input->post('complaintCategory'),
			'problem'  			=> $this->input->post('prob'),
            'date_fixed'		=> (!empty($this->input->post('fixDate')))?date('Y-m-d',strtotime($this->input->post('fixDate'))):'',
			'sqft'  			=> (!empty($this->input->post('sqft')))?$this->input->post('sqft'):'',
			'total_price'		=> (!empty($this->input->post('sqft')))?(5.5 * $this->input->post('sqft')):'',
			'approvedBy'  		=> (!empty($this->input->post('approveBy')))?$this->input->post('approveBy'):'',
			'updatedBY' 		=> $this->logged_user['id'],
			'updatedTS'	 		=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $maintID,
		);

		// debug($this->input->post());
		// debug($updateData);
		// die();

		$affected_rows = $this->model_maintenance->update_maintenance($updateData,$where);


		if(!empty($_FILES['picture_upload']['name']))
		{
			$this->load->library('File_upload');

			$upload_directory = 'assets/upload/hr/Form/maintenanceForm/';
			

			$upload_status = $this->file_upload
				->set_file_type(FILE_TYPE_UPLOAD)
				->set_directory_public()
				->set_upload_directory($upload_directory)
				->uploads('picture_upload');

				// die(debug($upload_status));

			if(is_array($upload_status)) {
				$uploadPhoto = array
				(
					'photo_title'         	=> (($upload_status['file_name']))?$upload_status['file_name']:$input['picture_upload'],
					'file_location'     	=> (!empty($upload_status['file_name']))?$upload_directory:'', 
					'is_delete'         	=> 0,
				);

				if(empty($pictID))
				{
					$uploadPhoto['sv_maintenance_id'] = $maintID;
				}

				$where = array
				(
					'ID' => $pictID,
				);

				// $affected_rows = $this->model_maintenance->update_picture($uploadPhoto, $where);

				// die(debug($where));
				if(!empty($pictID)){
					$affected_rows2 = $this->model_maintenance->update_picture($uploadPhoto, $where);
				} else {	
					$affected_rows2 = $this->model_general->insert('sv__maintenance__photo',$uploadPhoto);
				}
			// die(debug($affected_rows));
			
			} else {
				'Upload Error';
			}
		}

		if(!empty($affected_rows) || !empty($affected_rows2))
		{
			$this->session->set_flashdata('success',"Successfully update requested maintenance. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update requested maintenance.");
		}

		redirect(base_url('hr/serviceform/maintenance_list'));
	}

	function deleteMaintenanceList()
	{
		$this->load->model('hr/model_maintenance');

		$input 		= $this->input->post();
		$maintID 	= $this->input->post('maintenanceID');

		$sets = array
		(
			'is_delete'  	=> 1,
			'updatedBY'    	=> $this->logged_user['id'],
			'updatedTS'	 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $maintID,
		);

		$affected_rows = $this->model_maintenance->update_maintenance($sets,$where);

		if($affected_rows)
		{
			$this->model_approval->update_sv_status('sv__maintenance',$maintID);
			
			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted maintenance ."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete maintenance."
			));
		}
	}

	function meeting_list()
	{
		$this->load->model('hr/model_booking_meeting','room');

		$bookingDetail	= $this->room->getBookingRoom(null);
		$year			= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');

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

		if(!empty($bookingDetail))
		{
			foreach ($bookingDetail as $key => $booking) 
			{
				$createdTS  = date('Y-m-d',strtotime($booking['createdTS']));
				$startDate  = $booking['start_date'];
				$endDate    = $booking['end_date'];
				
				$tmpRes 					= array(); $tmpEvent = array();
				$tmpRes['id']  				= $booking['ID'];
				$tmpRes['title'] 			= $booking['dept_name'];

				$tmpEvent['id'] 			= $key;
				$tmpEvent['resourceId'] 	= $booking['staff_id'];
				$tmpEvent['start'] 			= $startDate;
				$tmpEvent['end'] 			= date('Y-m-d',strtotime($endDate."+1 days"));
				$tmpEvent['title'] 			= $booking['dept_name'].'/'.$booking['branchName'];
				
				if(!empty($booking['other_room'])):
					$tmpEvent['description']	= $booking['dept_name'].' request to book "'.$booking['other_room'].'"';
					// $tmpEvent['color']			= '#660066';
				else:
					$tmpEvent['description']	= $booking['dept_name'].' request to book "'.$booking['room'].'"';
				endif;
					$tmpEvent['color']			= '#'.$booking['color_code'];

				$tmpEvent['textColor']		= '#ffffff';

				array_push($fc_res, $tmpRes);
				array_push($fc_event, $tmpEvent);
				array_push($resource, $booking);
			}
		// debug($booking);
		}
		
		$data = array
		(
			'page_setup' 	=> $this->template->pageSetup('Online Form', '', 'Meeting & Training Booking List'),
			//'booking_room'	=> $this->room->getBookingRoom(null),
			'room_type'		=> $this->room->getBookingRoomType2($year),
			'departments'	=> $this->model_company->getDepartments(),
			'fc_res'		=> json_encode($fc_res),
			'fc_event'		=> json_encode($fc_event),
			'resource'		=> json_encode($resource),
		);

		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl']=='admin' || $this->logged_user['division_id'] == 4){
			$data['booking_room']		= $this->room->getBookingRoom(null,null,$year,5);
		}
		else{
			$data['booking_room']		= $this->room->getBookingRoom(null,$this->session->userdata('user')['id'],$year,5);
		}

		// debug($data['room_type']);

		$this->template->view('hr/policyprocedure/form/meeting_list', $data);
	}

	function meeting_calendar()
	{
		$this->load->model('hr/model_booking_meeting','room');

		$bookingDetail	= $this->room->getBookingRoom(null);

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

		if(!empty($bookingDetail))
		{
			foreach ($bookingDetail as $key => $booking) 
			{
				$createdTS  = date('Y-m-d',strtotime($booking['createdTS']));
				$startDate  = $booking['start_date'];
				$endDate    = $booking['end_date'];
				
				$tmpRes 					= array(); $tmpEvent = array();
				$tmpRes['id']  				= $booking['ID'];
				$tmpRes['title'] 			= $booking['dept_name'].'/'.$booking['branchName'];

				$tmpEvent['id'] 			= $key;
				$tmpEvent['resourceId'] 	= $booking['staff_id'];
				$tmpEvent['start'] 			= $startDate;
				$tmpEvent['end'] 			= date('Y-m-d',strtotime($endDate."+1 days"));
				$tmpEvent['title'] 			= $booking['dept_name'];
				
				if(!empty($booking['other_room'])):
					$tmpEvent['description']	= $booking['dept_name'].' request to book "'.$booking['other_room'].'"';
					// $tmpEvent['color']			= '#660066';
				else:
					$tmpEvent['description']	= $booking['dept_name'].' request to book "'.$booking['room'].'"';
				endif;
					$tmpEvent['color']			= '#'.$booking['color_code'];

				$tmpEvent['textColor']		= '#ffffff';

				array_push($fc_res, $tmpRes);
				array_push($fc_event, $tmpEvent);
				array_push($resource, $booking);
			}
		}
			// debug($fc_event);die();
		$data = array
		(
			'page_setup' 	=> $this->template->pageSetup('Online Form', '', 'Meeting & Training Booking Calendar'),
			'room_type'		=> $this->room->getBookingRoomType2(),
			'fc_res'		=> json_encode($fc_res),
			'fc_event'		=> json_encode($fc_event),
			'resource'		=> json_encode($resource),
		);

		// debug($data['booking_room']);

		$this->template->view('hr/policyprocedure/calendar/meeting_calendar', $data);
	}

	function meeting_form($ID = null)
	{
		$this->load->model('hr/model_booking_meeting','room');
		
		$bookingDetail	= $this->room->getBookingRoom(null);

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

		if(!empty($bookingDetail))
		{
			foreach ($bookingDetail as $key => $booking) 
			{
				$createdTS  = date('Y-m-d',strtotime($booking['createdTS']));
				$startDate  = $booking['start_date'];
				$endDate    = $booking['end_date'];
				
				$tmpRes 					= array(); $tmpEvent = array();
				$tmpRes['id']  				= $booking['ID'];
				$tmpRes['title'] 			= $booking['dept_name'].'/'.$booking['branchName'];

				$tmpEvent['id'] 			= $key;
				$tmpEvent['resourceId'] 	= $booking['staff_id'];
				$tmpEvent['start'] 			= $startDate;
				$tmpEvent['end'] 			= date('Y-m-d',strtotime($endDate."+1 days"));
				$tmpEvent['title'] 			= $booking['dept_name'].'/'.$booking['branchName'];
				
				if(!empty($booking['other_room'])):
					$tmpEvent['description']	= $booking['dept_name'].' request to book "'.$booking['other_room'].'"';
					// $tmpEvent['color']			= '#660066';
				else:
					$tmpEvent['description']	= $booking['dept_name'].' request to book "'.$booking['room'].'"';
				endif;
					$tmpEvent['color']			= '#'.$booking['color_code'];

				$tmpEvent['textColor']			= '#ffffff';

				array_push($fc_res, $tmpRes);
				array_push($fc_event, $tmpEvent);
				array_push($resource, $booking);
			}
		}
			// debug($fc_event);die();

		$data = array
		(
			'ID'					=> $ID,
			'page_setup' 			=> $this->template->pageSetup('Online Form', '', 'Meeting & Training Booking Form'),
			'room_type'				=> $this->room->getBookingRoomType(),
			'count_booking'			=> $this->room->getBookingRoomDaily(),
			'booking_room'			=> $this->room->getBookingRoom($ID),
			'fc_res'				=> json_encode($fc_res),
			'fc_event'				=> json_encode($fc_event),
			'resource'				=> json_encode($resource),
			'meal_menu'				=> $this->room->getMealMenu(),
			'package'				=> $this->room->getPackage(),
			'equipment'				=> $this->room->getEquipment(),
		);

		// die(debug($data['booking_room']));

        $filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl']=='admin' || $this->logged_user['division_id'] == 4){
	        if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__booking__room';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'meeting_list';
	            $data_approval['form_name'] = 'Meeting & Training Booking';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__booking__room','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
		}
        
        $this->template->view('hr/policyprocedure/form/meeting', $data);       
	}

	function meeting_form_save()
	{
		$this->load->model('hr/model_booking_meeting','room');

		$input 				= $this->input->post();
		// $package_price 		= explode(' = ',$input['package_id'])[1];
		// $package_price1		= str_replace('RM','',$package_price);
		// $package_price2		= str_replace('per pax','',$package_price1);

		$room_type 	= $this->room->getBookingRoomType($input['room_id'])[0];

		$insert = array
		(
			// 'room_id'			=> $input['']
			'requester_id'		=> $input['requester_id'],
			'department_id'		=> $input['department_id'],
			'package_id'		=> $input['package_id'],
			'event_title'		=> $input['event_title'],
			'client'			=> $input['client_name'],
			'start_date'		=> date('Y-m-d',strtotime($input['start_date'])),
			'start_time'		=> $input['start_time'],
			'end_date'			=> date('Y-m-d',strtotime($input['end_date'])),
			'end_time'			=> $input['end_time'],
			'pax'				=> $input['no_pax'],
			// 'total_price'		=> $package_price2 * $input['no_pax'],
			'createdBY'			=> $this->logged_user['id'],
		);

		if(!empty($input['other_room_id']))
		{
			$insert['room_id'] 		= 7;
			$insert['other_room'] 	= $input['other_room_id'];
		} else {
			$insert['room_id'] 		= $input['room_id'];
		}

		if(!empty($input['table_setup'])) $insert['table_setup'] = $input['table_setup'];
		// if(!empty($input['equipment_id'])) $insert['equipment'] = $input['equipment_id'];
		if(!empty($input['breakfast'])) $insert['breakfast'] = $input['breakfast'];
		if(!empty($input['lunch'])) $insert['lunch'] = $input['lunch'];
		if(!empty($input['tea'])) $insert['hi_tea'] = $input['tea'];
		if(!empty($input['other_menu'])) $insert['other_menu'] = $input['other_menu'];
		if(!empty($input['special_request'])) $insert['special_request'] = $input['special_request'];
		if(!empty($input['vip'])) $insert['vip'] = $input['vip'];
		// debug($insert);
		// die();

		if(!empty($input['other_room_id']))
		{
			$roomID 	= 7;
			$otherRoom 	= $input['other_room_id'];
		} else {
			$roomID 	= $input['room_id'];
			$otherRoom 	= null;
		}

		$startDate 	= date('Y-m-d',strtotime($input['start_date']));
		$startTime 	= date('H:i:s',strtotime($input['start_time']));
		$endDate 	= date('Y-m-d',strtotime($input['end_date']));
		$endTime 	= date('H:i:s',strtotime($input['end_time']));

		$where = array
		(
			"(('".$startDate."' BETWEEN start_date AND end_date OR '".$endDate."' BETWEEN start_date AND end_date)
			OR 
			(start_date BETWEEN '".$startDate."' AND '".$endDate."' OR end_date BETWEEN '".$startDate."' AND '".$endDate."'))
			AND
			(('".$startTime."' BETWEEN start_time AND end_time OR '".$endTime."' BETWEEN start_time AND end_time)
			OR 
			(start_time BETWEEN '".$startTime."' AND '".$endTime."' OR end_time BETWEEN '".$startTime."' AND '".$endTime."'))",
			'a.room_id = '.$roomID,
			'(select status from sv__approval where table_name="sv__booking__room" and id_table=a.ID and is_delete=0 order by ID desc limit 1) in ("In_progress","Verified","Completed")',
		);
		
		$getBookingRoomData = $this->room->getExistingBookingRoomDate($where);
		// $getBookingRoomData = $this->room->getBookingRoomDate($roomID, $dateApplied, $otherRoom, $timeApplied);

		if(!empty($getBookingRoomData)){ //date have been booked.
			$this->session->set_flashdata('error',"Date requested have already been booked. Please choose another date.");
			// redirect(base_url('hr/serviceform/meeting_form'));
		} else { //date approved
			$addroombooking = $this->model_general->insert('sv__booking__room', $insert);
			
			if($input['equipment_id']){
				$equipmentDetail 	= (!empty($equipment = $input['equipment_id']))?$equipment:array();
				$equipment_add 		= $this->room->updateOrCreateNew($addroombooking,$equipmentDetail);
			}
			
			if(!empty($addroombooking))
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$this->input->post('requester_id')))[0];

				$form_detail = array 
				(
					'name' 					=> $this->input->post('reqName'),
					'email_address'			=> ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']),
					'department'			=> $this->input->post('department'),
					'date_request'			=> $this->input->post('reqDate'),
					'event_title'  			=> $this->input->post('client_name'),
					'start_date'  			=> $this->input->post('start_date').' / '.$this->input->post('start_time'),
					'end_date'  			=> $this->input->post('end_date').' / '.$this->input->post('end_time'),
					'meeting_room' 			=> $room_type['room'],
				);

				$user_email 	= array();
				$admin_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 4'));
				if($admin_detail) foreach($admin_detail as $admin_email) 
				{
					array_push($user_email, ($admin_email['primary_email']) ? $admin_email['primary_email'] : (($admin_email['secondary_email']) ? $admin_email['secondary_email'] : $admin_email['email']));
				}

				$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
				
				$form_requestor_name 	= $this->model_user->getUserDetail($this->input->post('reqName_id'))['name'];

				if($user_email)
				{
					$emailSubject 		= 'New Meeting & Training Booking Request - '.$form_requestor_name.' ['.str_pad($addroombooking,5,0,STR_PAD_LEFT).']';
					$emailMessage 		= $form_requestor_name.' has request meeting & training booking on '.$this->input->post('reqDate').'. Below is the detail:- ';
					$emailDetailForm	= $form_detail;

					// $emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
				}

				$this->model_approval->updateOrCreateNew('sv__booking__room',$addroombooking,'Pending',0);
			
				$this->session->set_flashdata('success',"Successfully add new request for room booking. Thank you.");
			}else{
				$this->session->set_flashdata('error',"System failed to add new request for room booking. Please try again.");
			}
		}
		redirect(base_url('hr/serviceform/meeting_list'));
	}

    function meeting_edit()
	{
		$input = $this->input->post();
		$this->load->model('hr/model_booking_meeting','room');

		$meetingID = $input['meetingID'];

		// $package_price 		= explode(' = ',$input['package_id'])[1];
		// $package_price1		= str_replace('RM','',$package_price);
		// $package_price2		= str_replace('per pax','',$package_price1);
		
		$update = array
		(
			'requester_id'		=> $input['requester_id'],
			'department_id'		=> $input['department_id'],
			'package_id'		=> $input['package_id'],
			'event_title'		=> $input['event_title'],
			'client'			=> $input['client_name'],
			'table_setup'		=> $input['table_setup'],
			// 'equipment'			=> $input['equipment_id'],
			'breakfast'			=> (!empty($input['breakfast']) && $input['breakfast'] != '-- Please Select --')?$input['breakfast']:'',
			'lunch'				=> (!empty($input['lunch']) && $input['lunch'] != '-- Please Select --')?$input['lunch']:'',
			'hi_tea'			=> (!empty($input['tea']) && $input['tea'] != '-- Please Select --')?$input['tea']:'',
			'other_menu'		=> $input['other_menu'],
			'special_request'	=> $input['special_request'],
			'vip'				=> $input['vip'],
			'start_date'		=> date('Y-m-d',strtotime($input['start_date'])),
			'start_time'		=> $input['start_time'],
			'end_date'			=> date('Y-m-d',strtotime($input['end_date'])),
			'end_time'			=> $input['end_time'],
			'pax'				=> $input['no_pax'],
			// 'total_price'		=> $package_price2 * $input['no_pax'],
			'updatedBY' 		=> $this->logged_user['id'],
			'updatedTS'	 		=> date('Y-m-d H:i:s'),
		);

		if(!empty($input['other_room_id']))
		{
			$update['room_id'] 		= 7;
			$update['other_room'] 	= $input['other_room_id'];
		} else {
			$update['room_id'] 		= $input['room_id'];
		}

		$where = array
		(
			'ID' => $meetingID,
		);

		if(!empty($input['other_room_id']))
		{
			$roomID 	= 7;
			$otherRoom 	= $input['other_room_id'];
		} else {
			$roomID 	= $input['room_id'];
			$otherRoom 	= null;
		}

		$startDate 	= date('Y-m-d',strtotime($input['start_date']));
		$startTime 	= date('H:i:s',strtotime($input['start_time']));
		$endDate 	= date('Y-m-d',strtotime($input['end_date']));
		$endTime 	= date('H:i:s',strtotime($input['end_time']));

		$wheres = array
		(
			"(('".$startDate."' BETWEEN start_date AND end_date OR '".$endDate."' BETWEEN start_date AND end_date)
			OR 
			(start_date BETWEEN '".$startDate."' AND '".$endDate."' OR end_date BETWEEN '".$startDate."' AND '".$endDate."'))
			AND
			(('".$startTime."' BETWEEN start_time AND end_time OR '".$endTime."' BETWEEN start_time AND end_time)
			OR 
			(start_time BETWEEN '".$startTime."' AND '".$endTime."' OR end_time BETWEEN '".$startTime."' AND '".$endTime."'))",
			"a.ID != ".$meetingID,
			"a.room_id = ".$roomID,
		);
		
		$getBookingRoomData = $this->room->getExistingBookingRoomDate($wheres);
		// $getBookingRoomData = $this->room->getBookingRoomDate($roomID, $dateApplied, $otherRoom, $timeApplied);

		if(!empty($getBookingRoomData)){ //date have been booked.
			$this->session->set_flashdata('error',"Date requested have already been booked. Please choose another date.");
		} else { //date approved
			$updateroombooking = $this->room->updateBookingRoom($update, $where);
			
			if($input['equipment_id']){
				$equipmentDetail = (!empty($equipment = $input['equipment_id']))?$equipment:array();
				$editequipment 	= $this->room->updateOrCreateNew($meetingID,$equipmentDetail);
			}
			
			if(!empty($updateroombooking))
			{
				$this->session->set_flashdata('success',"Successfully update requested room booking. Thank you.");
			}else{
				$this->session->set_flashdata('error',"System failed to update requested room booking.");
			}
		}
		
		redirect(base_url('hr/serviceform/meeting_list'));
	}

	function deleteMeetingList()
	{
		$this->load->model('hr/model_booking_meeting','room');

		$input 		= $this->input->post();
		$meetingID 	= $this->input->post('meetingsID');;

		$sets = array
		(
			'is_delete'  	=> 1,
			'updatedBY'    	=> $this->logged_user['id'],
			'updatedTS'	 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $meetingID,
		);

		// die(debug($where));

		$affected_rows = $this->room->updateBookingRoom($sets,$where);

		// die(debug($affected_rows));

		if($affected_rows)
		{
			$this->model_approval->update_sv_status('sv__booking__room',$meetingID);

			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted meeting booking."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete meeting booking."
			));
		}
	}

	function getMealMenu()
	{
		$this->load->model('hr/model_booking_meeting','room');

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

		if($input['type'] == "Breakfast") $meal_type = 0;
		if($input['type'] == "Lunch") $meal_type = 1;
		if($input['type'] == "Hi-Tea") $meal_type = 2;

		$menu 		= $this->room->getMealMenu($meal_type);

		if($menu)
		{
			print json_encode(array(
				"status" 	=> "Success",
				"msg"	 	=> "Successfully retrieve data.",
				"menu"		=> $menu
			)); 
		}
		else
		{
			print json_encode(array(
				"status" 	=> "Error",
				"msg"	 	=> "System failed to retrieve data.",
				"menu"		=> "No data."
			));
		}
	}

	function updateMealMenu($mode = null)
	{
		$input 		= $this->input->post();

		if($mode == 'delete')
		{
			$menu 		= $input['menu'];
			$type 		= $input['type'];
			$menu_id	= $input['menu_id'];

			$where = array('ID' => $menu_id);

			$updateData = array
			(
				'is_delete'		=> 1,
				'updated_by'	=> $this->logged_user['id'],
				'updated_ts'	=> date('Y-m-d H:i:s')
			);

			$affected_rows = $this->model_general->update('sv__ref_meal_menu', $updateData, $where);

			// debug($this->db->last_query());

			if($affected_rows)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Successfully deleted ".$menu." from ".$type." list."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to delete ".$menu." from ".$type." list."
				));
			}
		}
		elseif($mode == 'add')
		{
			$type 		= $input['type'];
		    $type_id 	= $input['type_id'];
		    $menu 		= $input['menu'];

		    $inserData = array
		    (
		    	'menu'			=> $menu,
		    	'type'			=> $type_id,
		    	'created_by'	=> $this->logged_user['id']
		    );
			
			$affected_rows = $this->model_general->insert('sv__ref_meal_menu',$inserData);

			if($affected_rows)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Successfully added ".$menu." to ".$type." list."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to added ".$menu." to ".$type." list."
				));
			}
		}else{
			$menu 		= $input['menu'];
			$menu_id	= $input['menu_id'];

			$where = array('ID' => $menu_id);

			$updateData = array
			(
				'menu'			=> $menu,
				'updated_by'	=> $this->logged_user['id'],
				'updated_ts'	=> date('Y-m-d H:i:s')
			);

			$affected_rows = $this->model_general->update('sv__ref_meal_menu', $updateData, $where);

			// debug($this->db->last_query());

			if($affected_rows)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Successfully update ".$menu."."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to update ".$menu."."
				));
			}
		}
	}

	function updateMeetingPackage($mode = null)
	{
		$input 		= $this->input->post();

		if($mode == 'delete')
		{
			$package_id 	= $input['package_id'];
			$package 		= $input['package'];
			$package_price	= $input['package_price'];

			$where = array('ID' => $package_id);

			$updateData = array
			(
				'is_delete'		=> 1,
				'updated_by'	=> $this->logged_user['id'],
				'updated_ts'	=> date('Y-m-d H:i:s')
			);

			$affected_rows = $this->model_general->update('sv__ref_room_package', $updateData, $where);

			// debug($this->db->last_query());

			if($affected_rows)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Successfully deleted ".$package." = RM".number_format($package_price,2)." from the list."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to delete ".$package." = RM".number_format($package_price,2)." from the list."
				));
			}
		}
		elseif($mode == 'add')
		{
			$package 		= $input['package'];
			$package_price	= $input['package_price'];

		    $inserData = array
		    (
		    	'package'		=> $package,
		    	'price'			=> $package_price,
		    	'created_by'	=> $this->logged_user['id']
		    );
			
			$affected_rows = $this->model_general->insert('sv__ref_room_package',$inserData);

			if($affected_rows)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Successfully added ".$package." = RM".number_format($package_price,2)." to the list."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to add ".$package." = RM".number_format($package_price,2)." to the list."
				));
			}
		}else{
			$package_id 	= $input['package_id'];
			$package 		= $input['package'];
			$package_price	= $input['package_price'];

			$where = array('ID' => $package_id);

			$updateData = array
			(
				'package'		=> $package,
				'price'			=> $package_price,
				'updated_by'	=> $this->logged_user['id'],
				'updated_ts'	=> date('Y-m-d H:i:s')
			);

			$affected_rows = $this->model_general->update('sv__ref_room_package', $updateData, $where);

			// debug($this->db->last_query());

			if($affected_rows)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Successfully updated ".$package." = RM".number_format($package_price,2)."."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to update ".$package." = RM".number_format($package_price,2)."."
				));
			}
		}
	}

	function getBookingDate($form = null)
	{
		$input 				= $this->input->post();
		$msg 				= '';
		$getBookingData		= array();
		$where				= array();
		$where_or			= array();

		$startDate 	= (isset($input['start_date']) && !empty($input['start_date']))?date('Y-m-d',strtotime($input['start_date'])):'';
		$startTime 	= (isset($input['start_time']) && !empty($input['start_time']))?date('H:i:s',strtotime($input['start_time'])):'';
		$endDate 	= (isset($input['end_date']) && !empty($input['end_date']))?date('Y-m-d',strtotime($input['end_date'])):'';
		$endTime 	= (isset($input['end_time']) && !empty($input['end_time']))?date('H:i:s',strtotime($input['end_time'])):'';
		// $mode_value = (isset($input['mode_value']) && !empty($input['mode_value']))?explode('->',$input['mode_value']):'';

		if((strtotime($startDate) <= strtotime($endDate)) && (strtotime($startTime) <= strtotime($endTime)))
		{
			if($form == 'meeting')
			{
				$this->load->model('hr/model_booking_meeting','room');

				if(!empty($startDate) && !empty($startTime) && !empty($endDate) && !empty($endTime))
				{
					$where = array
					(
						// "(a.start_date between '".$startDate."' and '".$endDate."' or a.end_date between '".$startDate."' and '".$endDate."')",
						// "(a.start_time between '".$startTime."' and '".$endTime."' or a.end_time between '".$startTime."' and '".$endTime."')",

						"(('".$startDate."' BETWEEN start_date AND end_date OR '".$endDate."' BETWEEN start_date AND end_date)
						OR 
						(start_date BETWEEN '".$startDate."' AND '".$endDate."' OR end_date BETWEEN '".$startDate."' AND '".$endDate."'))
						AND
						(('".$startTime."' BETWEEN start_time AND end_time OR '".$endTime."' BETWEEN start_time AND end_time)
						OR 
						(start_time BETWEEN '".$startTime."' AND '".$endTime."' OR end_time BETWEEN '".$startTime."' AND '".$endTime."'))",
					);

					if(!empty($input['room_id'])) array_push($where,'a.room_id != '.$input['room_id']);
					if(!empty($input['id'])) array_push($where,'(a.requester_id != '.$this->logged_user['id'].' AND a.createdBY != '.$this->logged_user['id'].')');

				// }elseif(!empty($startDate) && !empty($endDate))
				// {
				// 	$tempt_where = array("(a.start_date between '".$startDate."' and '".$endDate."' or a.end_date between '".$startDate."' and '".$endDate."')");

				// 	array_push($where, $tempt_where[0]);
					
				// 	if(empty($startTime) || empty($endTime))
				// 	{
				// 		$tempt_where = array("(a.start_time between '".date('H:i:s',strtotime($mode_value[1]))."' and '".date('H:i:s',strtotime($mode_value[1]))."' or a.end_time between '".date('H:i:s',strtotime($mode_value[1]))."' and '".date('H:i:s',strtotime($mode_value[1]))."')");
				// 	}else{
				// 		$tempt_where = array("(a.start_time between '".$startTime."' and '".$endTime."' or a.end_time between '".$startTime."' and '".$endTime."')");
				// 	}

				// 	array_push($where, $tempt_where[0]);
				// }
				}else{
					// if(empty($startDate) || empty($endDate))
					// {
					// 	$tempt_where = array("(a.start_date between '".date('Y-m-d',strtotime($mode_value[1]))."' and '".date('Y-m-d',strtotime($mode_value[1]))."' or a.end_date between '".date('Y-m-d',strtotime($mode_value[1]))."' and '".date('Y-m-d',strtotime($mode_value[1]))."')");
					// }elseif(empty($startTime) || empty($endTime))
					// {
					// 	$tempt_where = array("(a.start_time between '".date('H:i:s',strtotime($mode_value[1]))."' and '".date('H:i:s',strtotime($mode_value[1]))."' or a.end_time between '".date('H:i:s',strtotime($mode_value[1]))."' and '".date('H:i:s',strtotime($mode_value[1]))."')");
					// }

					// array_push($where, $tempt_where[0]);

					return false;
				}

				$getBookingData = $this->room->getExistingBookingRoomDate($where);
				// debug($this->db->last_query());

				if($getBookingData) 
				{
					$msg = "Your requested room have been booked by others. Please try another room / date. Thank you.";
				}
			}elseif($form == 'car')
			{
				$this->load->model('hr/model_car_booking');
				// debug($input);

				if(!empty($startDate) && !empty($startTime) && !empty($endDate) && !empty($endTime))
				{
					$where = array
					(
						// "(a.start_date between '".$startDate."' and '".$endDate."' or a.end_date between '".$startDate."' and '".$endDate."')",
						// "(a.start_time between '".$startTime."' and '".$endTime."' or a.end_time between '".$startTime."' and '".$endTime."')",

						"(('".$startDate."' BETWEEN start_date AND end_date OR '".$endDate."' BETWEEN start_date AND end_date)
						OR 
						(start_date BETWEEN '".$startDate."' AND '".$endDate."' OR end_date BETWEEN '".$startDate."' AND '".$endDate."'))
						AND
						(('".$startTime."' BETWEEN start_time AND end_time OR '".$endTime."' BETWEEN start_time AND end_time)
						OR 
						(start_time BETWEEN '".$startTime."' AND '".$endTime."' OR end_time BETWEEN '".$startTime."' AND '".$endTime."'))",
					);
				}else{
					return false;
				}
				
				$getBookingData = $this->model_car_booking->getCarBookingDate(null, null, null, $where);

				if($getBookingData) 
				{
					$msg = "Your requested car have been booked by others. Please try another car / date. Thank you.";
				}
			}elseif($form == 'zoom')
			{
				$this->load->model('hr/model_zoom_booking');

				if(!empty($startDate) && !empty($startTime) && !empty($endDate) && !empty($endTime))
				{
					$where = array
					(
						"(('".$startDate."' BETWEEN start_date AND end_date OR '".$endDate."' BETWEEN start_date AND end_date)
						OR 
						(start_date BETWEEN '".$startDate."' AND '".$endDate."' OR end_date BETWEEN '".$startDate."' AND '".$endDate."'))
						AND
						(('".$startTime."' BETWEEN start_time AND end_time OR '".$endTime."' BETWEEN start_time AND end_time)
						OR 
						(start_time BETWEEN '".$startTime."' AND '".$endTime."' OR end_time BETWEEN '".$startTime."' AND '".$endTime."'))
						OR 
						(select status from sv__approval where table_name = 'sv__zoom_booking' and id_table = ID and is_delete = 0 order by ID desc limit 1) NOT IN ('Cancel','Rejected')",
					);

					if(!empty($input['account_id'])) array_push($where,'account_id != '.$input['account_id']);
					if(!empty($input['id'])) array_push($where,'(requester_id != '.$this->logged_user['id'].' AND createdBY != '.$this->logged_user['id'].')');

				}else{
					return false;
				}
				
				$getBookingData = $this->model_zoom_booking->getZoomBookingDate(null, $where);
				
				if($getBookingData) 
				{
					$msg = "Your requested zoom account have been booked by others. Please try another zoom account / date. Thank you.";
				}
			}
		}else{
			$getBookingData = 1;
			$msg = "Date or Time selected is invalid. Please try again.";
		}

		if(!$getBookingData)
		{
			print json_encode(array(
				"status" 			=> "Success",
				"msg"	 			=> "No data found. You may proceeed with booking. Thank you.",
				"getBookingData"	=> $getBookingData
			));
		}
		else
		{
			print json_encode(array(
				"status" 			=> "Error",
				"msg"	 			=> $msg,
				"getBookingData"	=> $getBookingData
			)); 
		}
	}

	function car_booking_list()
	{
		$this->load->model('hr/model_car_booking'); 
		$carbookingList = $this->model_car_booking->getCarRequestList();
		$year			= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');

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

		if(!empty($carbookingList))
		{
			foreach ($carbookingList as $key => $detail) 
			{
				$createdTS   = date('Y-m-d',strtotime($detail['createdTS']));
				$start_date  = $detail['start_date'];
				$end_date	 = $detail['end_date'];
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['dept_name'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = $detail['staff_id'];
				$tmpEvent['start']          = $start_date;
				$tmpEvent['end']			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title']          = $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']    = $detail['dept_name'].' request to perform "'.$detail['car_type_name'].'" carbooking.';
				$tmpEvent['color']          = $detail['color_code'];
				$tmpEvent['textColor']      = '#ffffff';

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

		$carbooking = $this->model_car_booking->getCarList();

		if($carbooking) foreach($carbooking as $key => $value)
		{
			$carbooking[$key]['short_name'] = substr($value['car_name'], 0, 4);
		}

		$data = array
		(
			'page_setup'        => $this->template->pageSetup('Online Form', '', 'Car Booking Request List'),
			//'rsCarBookingList'  => $this->model_car_booking->getCarRequestList(),
			'car_type'			=> $this->model_car_booking->getCarBookingType2($year),
			'department' 		=> $this->model_company->getDepartments(),
			'carbooking'        => $carbooking,
			'fc_res'            => json_encode($fc_res),
			'fc_event'          => json_encode($fc_event),
			'resource'          => json_encode($resource),
		);

		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl']=='admin' || $this->logged_user['division_id'] == 4){
			$data['rsCarBookingList']		= $this->model_car_booking->getCarRequestList(null,null,null,$year);
		}
		else{
			$data['rsCarBookingList']		= $this->model_car_booking->getCarRequestList(null,$this->session->userdata('user')['id'],null,$year);
		}

		$this->template->view('hr/policyprocedure/form/car_booking_list', $data);
	}

	function car_booking_calendar()
	{
		$this->load->model('hr/model_car_booking');

		$carbookingDetail   = $this->model_car_booking->getCarRequestList();
		$fc_res     = array();
		$fc_event   = array();
		$resource   = array();

		if(!empty($carbookingDetail))
		{
			foreach ($carbookingDetail as $key => $detail) 
			{
				$start_date  = date('Y-m-d',strtotime($detail['start_date']));
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['dept_name'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = $detail['user_id'];
				$tmpEvent['start']          = $start_date;
				$tmpEvent['title']          = $detail['dept_name'];
				$tmpEvent['description']    = $detail['dept_name'].' request to perform "'.$detail['car_type_name'].'" carbooking.';

				if($detail['car_type_name'] == 'Avanza (WA 7012 M)')
				{
					$tmpEvent['color']          = '#0033cc';
				}

				if($detail['car_type_name'] == 'Honda (WC 1426 R)')
				{
					$tmpEvent['color']          = '#990099';
				}

				$tmpEvent['textColor']      = '#ffffff';

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

		$carbooking = array
		(
			$datas = array
			(
				'carType'   => 'Avanza (WA 7012 M)',
				'color_code'    => '#0033cc',
			),

			$datas = array
			(
				'carType'   => 'Honda (WC 1426 R)',
				'color_code'    => '#990099',
			),
		);
			
		$data = array
		(
			'page_setup'        => $this->template->pageSetup('Online Form', '', 'Car Booking Request Calendar'),
			'calendar_detail'   => $fc_event,
			'carbooking'        => $carbooking,
			'fc_res'            => json_encode($fc_res),
			'fc_event'          => json_encode($fc_event),
			'resource'          => json_encode($resource),
		);

		// debug($data['complain']);
		// die();
		
		$this->template->view('hr/policyprocedure/calendar/car_booking_calendar', $data);		
	}

	function car_booking_form($ID=null)
	{
		$this->load->model('admin/model_user');
		$this->load->model('hr/model_car_booking');

		$carbookingList = $this->model_car_booking->getCarRequestList();

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

		if(!empty($carbookingList))
		{
			foreach ($carbookingList as $key => $detail) 
			{
				$createdTS   = date('Y-m-d',strtotime($detail['createdTS']));
				$start_date  = $detail['start_date'];
				$end_date	 = $detail['end_date'];
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['dept_name'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = $detail['staff_id'];
				$tmpEvent['start']          = $start_date;
				$tmpEvent['end']			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title']          = $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['car_name']       = $detail['car_type_name'];
				$tmpEvent['description']    = $detail['dept_name'].' request to perform "'.$detail['car_type_name'].'" carbooking.';
				$tmpEvent['color']          = '#'.$detail['color_code'];
				$tmpEvent['textColor']      = '#ffffff';

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

		$carbooking = $this->model_car_booking->getCarList();

		if($carbooking) foreach($carbooking as $key => $value) $carbooking[$key]['short_name'] = substr($value['car_name'], 0, 4);

		$data = array
		(
			'ID'         		=> $ID,
			'listName'			=> $this->model_user->getUsers2(),
			'rsCarGetList' 		=> $this->model_car_booking->getCarListForm($ID),
			'listAdmin'			=> $this->model_car_booking->getAdminList(),
			'carname' 			=> $this->model_car_booking->getCarListForm(),
			'upcoming_request'	=> $this->model_car_booking->getBookingCarByWeek(),
			'carbooking'        => $carbooking,
			'fc_res'            => json_encode($fc_res),
			'fc_event'          => json_encode($fc_event),
			'resource'          => json_encode($resource),
		);
		

        //$data['carBookingDetails']  = $this->model_car_booking->getCarBookingDetails();
        $filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl']=='admin' || $this->logged_user['division_id'] == 4){
	        if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__car_booking';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'car_booking_list';
	            $data_approval['form_name'] = 'Car Booking';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__car_booking','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
		}

		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Car Booking Form');
		$this->template->view('hr/policyprocedure/form/car_booking', $data);
	}

	function carbooking_save()
	{
		$this->load->model('hr/model_car_booking'); 
		//$carbookingList = $this->model_car_booking->getCarBookingDate();
		$input 			= $this->input->post();

		$user_dept_id 	= $this->model_user->getUsers2(isset($input['guest_details'])?$input['guest_details']:$input['reqName_id'])['department_id'];
		$user_id 		= (isset($input['guest_details']))?$input['guest_details']:$input['reqName_id'];
		$car_type		= $this->model_car_booking->getCarList($input['car_id'])[0];

		$insertData = array(
			'car_id' 		=> $this->input->post('car_id'),
			'user_id' 		=> $user_id,
			'location' 		=> $this->input->post('location'),
			'purpose' 		=> $this->input->post('purpose'),
			'department_id' => $user_dept_id,
            'start_date'	=> date('Y-m-d',strtotime($input['start_date'])),
			'start_time' 	=> date('H:i:s',strtotime($this->input->post('start_time'))),
			'end_date' 		=> date('Y-m-d',strtotime($input['end_date'])),
			'end_time' 		=> date('H:i:s',strtotime($this->input->post('end_time'))),
			'createdBY' 	=> $this->logged_user['id']
		);

		$carType		= $this->input->post('car_id');
		$dateApplied	= date('Y-m-d',strtotime($this->input->post('start_date')));
		$timeApplied	= date('H:i:s',strtotime($this->input->post('start_time')));



		$getBookingData = $this->model_car_booking->getCarBookingDate($carType,$dateApplied,$timeApplied);

		if(!empty($getBookingData)){ //date have been booked.
			$this->session->set_flashdata('error',"Date requested have already been booked. Please choose another date.");
		} else { //date approved
			$newCarbooking = $this->model_general->insert('sv__car_booking', $insertData);
			if(!empty($newCarbooking))
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$this->input->post('reqName_id')))[0];

				$form_detail = array 
				(
					'name' 					=> $this->input->post('reqName'),
					'email_address'			=> ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']),
					'department'			=> $this->input->post('department'),
					'date_request'			=> $this->input->post('reqDate'),
					'car_type'  			=> $car_type['car_name'],
					'start_date'  			=> $this->input->post('start_date').' / '.$this->input->post('start_time'),
					'end_date'  			=> $this->input->post('end_date').' / '.$this->input->post('end_time'),
					'purpose' 				=> $this->input->post('purpose'),
				);

				$user_email 	= array();
				$admin_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 4'));
				if($admin_detail) foreach($admin_detail as $admin_email) 
				{
					array_push($user_email, ($admin_email['primary_email']) ? $admin_email['primary_email'] : (($admin_email['secondary_email']) ? $admin_email['secondary_email'] : $admin_email['email']));
				}

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

				$send_copy_form_email = (isset($send_email_checkbox) && $send_email_checkbox == 'on')?$send_email_checkbox:'off';

				if($send_copy_form_email == 'on')
				{
					// $form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$this->input->post('reqName_id')))[0];
					$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
				}
				
				$form_requestor_name 	= $this->model_user->getUserDetail($this->input->post('reqName_id'))['name'];

				if($user_email)
				{
					$emailSubject 		= 'New Car Booking Request - '.$form_requestor_name.' ['.str_pad($newCarbooking,5,0,STR_PAD_LEFT).']';
					$emailMessage 		= $form_requestor_name.' has request car booking on '.$this->input->post('reqDate').'. Below is the detail:- ';
					$emailDetailForm	= $form_detail;

					$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
				}

				$this->model_approval->updateOrCreateNew('sv__car_booking',$newCarbooking,'Pending',0);

				$this->session->set_flashdata('success',"Successfully add new request for car. Thank you.");
			}else{
				$this->session->set_flashdata('error',"System failed to add new request for car.Please try again.");
			}
		}
		
		redirect(base_url('hr/serviceform/car_booking_list')); 
	}

	function carbooking_edit()
	{
		$this->load->model('hr/model_car_booking');
		$input = $this->input->post();

		$carbookID 		= $this->input->post('carBookingID');
		$user_dept_id 	= $this->model_user->getUsers2((isset($input['guest_details']))?$input['guest_details']:((isset($input['guest_details_input']))?$input['guest_details_input']:$input['reqName_id']))['department_id'];
		$user_id 		= (isset($input['guest_details']))?$input['guest_details']:((isset($input['guest_details_input']))?$input['guest_details_input']:$input['reqName_id']);


		$sets = array
		(
			'car_id'    	=> $this->input->post('car_id'),
			'user_id'     	=> $user_id,
			'location'    	=> $this->input->post('location'),
			'purpose'     	=> $this->input->post('purpose'),
			'department_id' => $user_dept_id,
            'start_date'	=> date('Y-m-d',strtotime($input['start_date'])),
			'start_time'  	=> $this->input->post('start_time'),
			'end_date' 		=> date('Y-m-d',strtotime($input['end_date'])),
			'end_time'    	=> $this->input->post('end_time'),
			'approvedBy'    => $this->input->post('approveBy'),
			'updatedBY'     => $this->logged_user['id'],
			'updatedTS'     => date('Y-m-d H:i:s'),
		);

		$carType		= $this->input->post('car_id');
		$dateApplied	= date('Y-m-d',strtotime($this->input->post('start_date')));
		$timeApplied	= date('H:i:s',strtotime($this->input->post('start_time')));

		$where = array 
		(
			'ID' => $carbookID,
		);

		
		$getBookingData = $this->model_car_booking->getCarBookingDate($carType,$dateApplied,$timeApplied);

		if(!empty($getBookingData)){ //date have been booked.
			$this->session->set_flashdata('error',"Date requested have already been booked. Please choose another date.");
		} else { //date approved
			$affected_rows = $this->model_car_booking->update_carBooking($sets,$where);
			if($affected_rows){	
				$this->session->set_flashdata('success',"Successfully update requested car. Thank you.");
			} else {
				$this->session->set_flashdata('error',"System failed to update requested car.");
			}
		}

		redirect(base_url('hr/serviceform/car_booking_list'));
	}

	function deleteCarBookingList()
	{
		$this->load->model('hr/model_car_booking');

		$input    = $this->input->post();
		$carBookID  = $this->input->post('carBookingID');

		$sets = array
		(
			'is_delete'   => 1,
			'updatedBY'     => $this->logged_user['id'],
			'updatedTS'   => date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $carBookID,
		);

		$affected_rows = $this->model_car_booking->update_carBooking($sets,$where);

		if($affected_rows)
		{
			$this->model_approval->update_sv_status('sv__car_booking',$carBookID);

			print json_encode(array(
				"status" => "Success",
				"msg"  => "Successfully deleted booking ."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"  => "System failed to delete booking."
			));
		}
	}

	function getCar()
	{
		$this->load->model('hr/model_car_booking');

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

		$carbooking = $this->model_car_booking->getCarList();

		if($carbooking)
		{
			print json_encode(array(
				"status" 	=> "Success",
				"msg"	 	=> "Successfully retrieve data.",
				"car"		=> $carbooking
			)); 
		}
		else
		{
			print json_encode(array(
				"status" 	=> "Error",
				"msg"	 	=> "System failed to retrieve data.",
				"car"		=> "No data."
			));
		}
	}

	function updateCarList($mode = null)
	{
		$input 		= $this->input->post();
		$hex_color  = sprintf("%02x%02x%02x", rand(0,255), rand(0,255), rand(0,255));

		if($mode == 'delete')
		{
			$car_id 		= $input['car_id'];
			$car_name		= $input['car_name'];

			$where = array('ID' => $car_id);

			$updateData = array('is_delete' => 1);

			$affected_rows = $this->model_general->update('sv__car_booking__type', $updateData, $where);

			// debug($this->db->last_query());
			// die();

			if($affected_rows)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Successfully deleted ".$car_name." from car list."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to delete ".$car_name." from car list."
				));
			}
		}
		elseif($mode == 'add')
		{
		    $car_name 		= $input['car_name'];
		    $car_color 		= $hex_color;
		    $car_price 		= $input['car_price'];

		    $inserData = array
		    (
		    	'car_name'		=> $car_name,
		    	'color_code'	=> $car_color,
		    	'price'			=> $car_price,
		    );
			
			$affected_rows = $this->model_general->insert('sv__car_booking__type',$inserData);

			if($affected_rows)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Successfully added ".$car_name." to car list."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to added ".$car_name." to car list."
				));
			}
		}else{
			$car_id 		= $input['car_id'];
		    $car_name 		= $input['car_name'];
		    $car_price 		= $input['car_price'];

			$where = array('ID' => $car_id);

			$updateData = array
			(
				'car_name'		=> $car_name,
				'price'			=> $car_price,
			);

			$affected_rows = $this->model_general->update('sv__car_booking__type', $updateData, $where);

			// debug($this->db->last_query());
			// die();

			if($affected_rows)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Successfully update ".$car_name."."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to update ".$car_name."."
				));
			}
		}
	}

	function meeting_crm_form($ID = null)
	{
		$this->load->model('hr/model_booking_meeting');
		$data = array
		(
			'ID' 						=> $ID,
			'meetingCrmListByID' 		=> $this->model_booking_meeting->getBookingMeetingCrmListByID($ID),
			'companyList' 				=> $this->model_booking_meeting->getCompanyList(),
            'listNames' 				=> $this->model_booking_meeting->getlistNames(),
            //'attendedNames'           => $this->model_booking_meeting->getattendListName(),
            //'attendName'        		=> $this->model_booking_meeting->getBookingRoomAttendName(),
		);

		// die(debug($data['meetingCrmListByID']));
		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Meeting Report Form');
		$this->template->view('hr/policyprocedure/form/meeting_crm', $data);
	}

	function meeting_crm_list()
	{
		$this->load->model('hr/model_booking_meeting');
		$attendID = $this->input->post('attendListNameID');
		// die(debug($attendID));

		$data = array
		(
			//'meetingCrmList' 	=> $this->model_booking_meeting->getBookingMeetingCrmList(),
			'attendListName' 	=> $this->model_booking_meeting->getattendListName(),
            'department' 		=> $this->model_company->getDepartments(),
            'companyList' 		=> $this->model_booking_meeting->getCompanyList(),
            //'attendName'      => $this->model_booking_meeting->getattendedListName(),
		);	

		if($_SESSION['module_data']['role']=='admin'){
			$data['meetingCrmList']		= $this->model_booking_meeting->getBookingMeetingCrmList();
		}
		else{
			$data['meetingCrmList']		= $this->model_booking_meeting->getBookingMeetingCrmList(null,$this->session->userdata('user')['id']);
		}
		
		//die(debug($data['meetingCrmListIncludeAttend']));

		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Meeting Report List');
		$this->template->view('hr/policyprocedure/form/meeting_crm_list', $data);
	}

	function add_new_meeting_crm()
	{
		$input = $this->input->post();

		// die(debug($input));

		if (isset($input['engagements3'])) $input['engagements1'] = $input['engagements3'];;
		if (isset($input['potentialServices3'])) $input['potentialServices1'] = $input['potentialServices3'];
			$meetingCrm = array
			(
				'user_id'					=> $input['name_id'],
				'department_id'				=> $input['department_id'],
				'crm_id'    				=> $input['compname'],
				'director_info'				=> $input['info'],
				'objective_meeting'			=> $input['obj'],
				'contact_person'			=> $input['contact'].','. $input['contactno'].','. $input['contactemail'],
				'principle_business'		=> $input['princip'],
				'prepared_by'				=> $input['prepare'],
				// 'attended_by'				=> $row,
				'recommended_direction'		=> $input['recommended'],
				'fee'						=> $input['fees'],
				'engagement'				=> $input['engagements1'],
				'potential_services'		=> $input['potentialServices1'],
				'action_required'			=> $input['actionReq'],
				'meeting_result'			=> $input['result'],
				'createdBY'					=> $this->logged_user['id']
			);

			$meetingCRM = $this->model_general->insert('sv__meeting__crm_report', $meetingCrm);

			foreach ($input['attend'] as $key => $row) {
				if($meetingCRM){

					$insertAttendBy = array(
											'meeting_crm_report_id'   	=> $meetingCRM,
											'attended_by'				=> $row,				
											'createdBY'					=> $this->logged_user['id']
											);
											
											// die(debug($insertAttendBy['attended_by']));

					$newMeetingCRM = $this->model_general->insert('sv__meeting__crm_attended_by',$insertAttendBy);
				} else {
					return false;
				}
			}
		redirect(base_url('hr/serviceform/meeting_crm_list'));
	}

	function edit_meeting_crm()
	{
		$this->load->model('hr/model_booking_meeting');
		$input = $this->input->post();
		$meetingID = $this->input->post('meetingCrmID');

		if (isset($input['engagements3'])) $input['engagements1'] = $input['engagements3'];;
		if (isset($input['potentialServices3'])) $input['potentialServices1'] = $input['potentialServices3'];
		$meetingCrm = array
		(
			'user_id'					=> $input['name_id'],
			'department_id'				=> $input['department_id'],
			'crm_id'					=> $input['compname'],
			'director_info'				=> $input['info'],
			'objective_meeting'			=> $input['obj'],
			'contact_person'			=> $input['contact'],
			'contact_number'			=> $input['contactno'],
			'contact_email'				=> $input['contactemail'],
			'principle_business'		=> $input['princip'],
			'prepared_by'				=> $input['prepare'],
			//'attended_by'				=> $input['attend'],
			'recommended_direction'		=> $input['recommended'],
			'fee'						=> $input['fees'],
			'engagement'				=> $input['engagements1'],
			'potential_services'		=> $input['potentialServices1'],
			'action_required'			=> $input['actionReq'],
			'meeting_result'			=> $input['result'],
			'createdBY'					=> $this->logged_user['id']
		);

		$where = array 
		(
			'ID' => $meetingID,
		);

		$meetingCRM = $this->model_booking_meeting->updateMeetingCRM($meetingCrm, $where);
		//die(debug($affected_rows));
	
		
			if($meetingCRM){ //sebab sini dah check. So xperlu check 2 kali
				//if($meetingID && $row[){
				$deleteAttendBy = array(
										'is_delete'                 => 1,				
										'updatedBY'					=> $this->logged_user['id']
										);
				$where = array 
				(
					'meeting_crm_booking_id' => $meetingID,
				);

				$deleteAttendedBy = $this->model_general->update('sv__meeting__crm_attended_by',$deleteAttendBy, $where); //delete semua attended_by dalam meeting tu
				//}
				foreach ($input['attend'] as $key => $row) {
					//if($meetingCRM){ sini dah xperlu
					$insertAttendBy = array(
											'meeting_crm_booking_id'   	=> $meetingID,
											'attended_by'				=> $row,				
											'createdBY'					=> $this->logged_user['id']
											);

					$updateAttendedBy = $this->model_general->insert('sv__meeting__crm_attended_by',$insertAttendBy);
					// } else {
					//     return false;
					// }
				}
		}    

		if($affected_rows || $updateAttendedBy)
		{
			print json_encode(array(
				"status" => "Success",
				"msg"  => "Successfully update report meeting form."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"  => "System failed to update report meeting form."
			));
		}
		redirect(base_url('hr/serviceform/meeting_crm_list'));
	}
	
	function deleteMeetingCRMList()
	{
		$this->load->model('hr/model_booking_meeting');

		$input      = $this->input->post();
		$meetingID  = $this->input->post('meetingCrmID');

		$sets = array
		(
			'is_delete'   => 1,
			'updatedBY'   => $this->logged_user['id'],
			'updatedTS'   => date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $meetingID,
		);

		$affected_rows = $this->model_booking_meeting->updateMeetingCRM($sets,$where);

		if($affected_rows)
		{
			print json_encode(array(
				"status" => "Success",
				"msg"  => "Successfully deleted meeting report ."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"  => "System failed to delete meeting report."
			));
		}
	}

	function hotel_list($mode = '')
	{
		if($mode == 'submit') 
		{
			$this->session->set_flashdata('success',"Thank you for your requets.");
			redirect(base_url('hr/serviceform/hotel_list'));
		}

        $hotelList 	= $this->model_hotel->getHotelBookingList();
        $year	   	= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');

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

		if(!empty($hotelList))
		{
			foreach ($hotelList as $key => $detail) 
			{
				$createdTS  = date('Y-m-d',strtotime($detail['createdTS']));
				$checkin	= $detail['checkin_date'];
				$checkout	= $detail['checkout_date'];
								
				$tmpRes 					= array(); $tmpEvent = array();
				$tmpRes['id']  				= $detail['ID'];
				$tmpRes['title'] 			= $detail['dept_name'].'/'.$detail['branchName'];

				$tmpEvent['id'] 			= $key;
				$tmpEvent['resourceId'] 	= $detail['requestor_id'];
				$tmpEvent['start'] 			= $checkin;
				$tmpEvent['end']			= date('Y-m-d',strtotime($checkout."+1 days"));
				$tmpEvent['title'] 			= $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']	= $detail['dept_name'].' request "'.$detail['hotel_name'].'" booking.';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',0.5)';
				$tmpEvent['textColor']		= '#ffffff';

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

		$data = array
		(
            //'rsHotelList' 		=> $this->model_hotel->getHotelBookingList(),
            'page_setup'        => $this->template->pageSetup('Online Form', '', 'Hotel Booking List'),
			'department' 		=> $this->model_company->getDepartments(),
			'count_request'		=> $this->model_hotel->getRequestByCompany($year),
            'fc_res'			=> json_encode($fc_res),
			'fc_event'			=> json_encode($fc_event),
			'resource'			=> json_encode($resource),
		);	

		if($_SESSION['module_data']['role']=='admin'){
			$data['rsHotelList']		= $this->model_hotel->getHotelBookingList(null,null,$year);
		}
		else{
			$data['rsHotelList']		= $this->model_hotel->getHotelBookingList(null,$this->session->userdata('user')['id'],$year);
		}

		$this->template->view('hr/policyprocedure/form/hotel_list', $data);
	}

	function hotel_form($ID = null, $mode = '')
	{
		$this->load->model('admin/model_user');

		$hotelList = $this->model_hotel->getHotelBookingList();

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

		if(!empty($hotelList))
		{
			foreach ($hotelList as $key => $detail) 
			{
				$createdTS  = date('Y-m-d',strtotime($detail['createdTS']));
				$checkin	= $detail['checkin_date'];
				$checkout	= $detail['checkout_date'];
								
				$tmpRes 					= array(); $tmpEvent = array();
				$tmpRes['id']  				= $detail['ID'];
				$tmpRes['title'] 			= $detail['dept_name'].'/'.$detail['branchName'];

				$tmpEvent['id'] 			= $key;
				$tmpEvent['resourceId'] 	= $detail['requestor_id'];
				$tmpEvent['start'] 			= $checkin;
				$tmpEvent['end']			= date('Y-m-d',strtotime($checkout."+1 days"));
				$tmpEvent['title'] 			= $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']	= $detail['dept_name'].' request to perform "'.$detail['hotel_name'].'" hotellist.';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',1.0)';
				$tmpEvent['textColor']		= '#ffffff';

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

		$data = array
		(
			'mode'				=> $mode,
			'listName'			=> $this->model_user->getUsers2(),
			'ID' 				=> $ID,
			'rsHotelList'   	=> $this->model_hotel->getHotelListForm($ID),
			'roomDetailList'	=> $this->model_hotel->getHotelBookingRoomDetails($ID),
			'page_setup' 		=> $this->template->pageSetup('Online Form', '', 'Hotel Booking Form'),
			'upcoming_request'	=> $this->model_hotel->getBookingHotelByWeek(),
            'fc_res'			=> json_encode($fc_res),
			'fc_event'			=> json_encode($fc_event),
			'resource'			=> json_encode($resource),
		);

		if($this->logged_module['role'] == 'admin')
		{
			if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__hotel';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'hotel_list';
	            $data_approval['form_name'] = 'Hotel Booking';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__hotel','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
		}

		$this->template->view('hr/policyprocedure/form/hotel', $data);
	}

	function hotel_save()
	{
        $input 					= $this->input->post();
        $guest_id 	= (isset($input['guest_details']))?$input['guest_details']:$input['name_id'];

        if(isset($input['guest_details']))
        {
        	$guest_id 	= $input['guest_details'];
        }else
        {
        	$guest_id 	= $input['name_id'];
        }

		$insertData = array(
			'requestor_id'			=> $guest_id,
			'hotel_name'			=> $input['hotelname'],
			'location'				=> $input['location'],
			'checkin_date'			=> date('Y-m-d',strtotime($input['checkin_date'])),
			'checkin_time'			=> date('H:i:s',strtotime($input['checkin_time'])),
			'checkout_date'			=> date('Y-m-d',strtotime($input['checkout_date'])),
			'checkout_time'			=> date('H:i:s',strtotime($input['checkout_time'])),
			'createdBY'				=> $this->logged_user['id']

		);

		$newHotelBooking = $this->model_general->insert('sv__hotel', $insertData);
		// $newHotelBooking = 1;

		if(!empty($newHotelBooking))
		{
			$form_detail = array 
			(
				'name' 				=> $input['name'],
				'email_address'		=> $input['email'],
				'department'		=> $input['department'],
				'date_request'		=> $input['datereq'],
				'hotel_name'		=> $input['hotelname'],
				'location'			=> $input['location'],
				'check_in_date'		=> $input['checkin_date'].' '.$input['checkin_time'],
				'check_out_date'	=> $input['checkout_date'].' '.$input['checkout_time']
			);

			$form_requestor_name 	= $this->model_user->getUserDetail($input['name_id'])['name'];
			
			$user_email = array();
			$user_email = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));
			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($user_email, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}
			
			$send_copy_form_email 	= (isset($input['send_email_checkbox']) && $input['send_email_checkbox'] == 'on')?$input['send_email_checkbox']:'off';	
			if($send_copy_form_email == 'on')
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['name_id']))[0];
				$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			}

			if($user_email)
			{
				$emailSubject 		= 'New Hotel Booking - '.$form_requestor_name.' ['.str_pad($newHotelBooking,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $form_requestor_name.' has request hotel booking on '.$input['datereq'].'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->model_approval->updateOrCreateNew('sv__hotel',$newHotelBooking,'Pending',0);

			$this->session->set_flashdata('success',"Successfully add new request for hotel booking. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new request for hotel booking.Please try again.");
		}

		redirect(base_url('hr/serviceform/hotel_form/'.$newHotelBooking.'/room_detail')); 
	}

	function hotel_edit()
	{
        $input 		= $this->input->post();
        $hotelID 	= $this->input->post('hotelID');
		$guest_id 	= (isset($input['guest_details']))?$input['guest_details']:((isset($input['guest_details_input']))?$input['guest_details_input']:$input['name_id']);

        // if(isset($input['guest_details']))
        // {
        // 	$guest_id 	= $input['guest_details'];
        // }else
        // {
        // 	$guest_id 	= $input['name_id'];
        // }

		$sets = array(
			'requestor_id'			=> $guest_id,
			'hotel_name'			=> $input['hotelname'],
			'location'				=> $input['location'],
			'checkin_date'			=> date('Y-m-d',strtotime($input['checkin_date'])),
			'checkin_time'			=> $input['checkin_time'],
			'checkout_date'			=> date('Y-m-d',strtotime($input['checkout_date'])),
			'checkout_time'			=> $input['checkout_time'],
			'updatedBY'     		=> $this->logged_user['id'],
			'updatedTS'     		=> date('Y-m-d H:i:s'),

		);

		$where = array 
		(
			'ID' => $hotelID,
		);

		$affected_rows = $this->model_hotel->update_hotel($sets,$where);
		//die(debug($affected_rows));
		
		if(!empty($affected_rows))
		{
			$this->session->set_flashdata('success',"Successfully update requested hotel booking. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update requested hotel booking.");
		}

		redirect(base_url('hr/serviceform/hotel_form/'.$hotelID.'/room_detail'));
	}

	function deleteHotelList()
	{
		$input    = $this->input->post();
		$hotelID  = $this->input->post('hotelID');


		$sets = array
		(
			'is_delete'   => 1,
			'updatedBY'   => $this->logged_user['id'],
			'updatedTS'   => date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $hotelID,
		);

		$affected_rows = $this->model_hotel->update_hotel($sets,$where);

		if($affected_rows)
		{
			$this->model_approval->update_sv_status('sv__hotel',$hotelID);

			print json_encode(array(
				"status" => "Success",
				"msg"  => "Successfully deleted booking ."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"  => "System failed to delete booking."
			));
		}
	}

	function hotel_save_room()
	{
		$input  		= $this->input->post();
		$currentPax 	= $this->model_hotel->getHotelListForm($input['hotel_ID'])[0]['pax'];
		$paxAdded		= count($input['staff_id']);

		$insertDataMain = array
		(
			'hotel_id'		=> $input['hotel_ID'],
			'room_type'		=> $input['typeroom'],
			'created_by'	=> $this->logged_user['id'],
		);

		$newMainDetails = $this->model_general->insert('sv__hotel_room_detail', $insertDataMain);

		if(!empty($newMainDetails))
		{
			$insert_guest = $this->model_hotel->updateOrCreateNew($newMainDetails,$input['staff_id']);

			if($insert_guest) $this->model_hotel->update_hotel(array('pax' => ($currentPax + $paxAdded)),array('ID' => $input['hotel_ID']));

			$this->session->set_flashdata('success',"Successfully add new room details for hotel booking. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new room details for hotel booking. Please try again.");
		}

		redirect(base_url('hr/serviceform/hotel_form/'.$input['hotel_ID'].'/room_detail'));
	}

	function hotel_edit_room()
	{
		$input 			= $this->input->post();

		$update = array
		(
			'room_type' 	=> $input['edit_typeroom'],
			'updated_ts'	=> date('Y-m-d H:i:s')
		);
		
		$updateRoomDetails = $this->model_general->update('sv__hotel_room_detail', $update, array('ID' => $input['room_ID']));

		if($updateRoomDetails)
		{
			$updateGuestID = $this->model_hotel->updateOrCreateNew($input['room_ID'],$input['edit_staff_id']);

			if($updateGuestID)
			{
				$pax 			= 0;
				$roomDetailList = $this->model_hotel->getHotelBookingRoomDetails($input['edit_hotel_ID']);
				if($roomDetailList) foreach($roomDetailList as $room_detail)
				{
					$guest_explode	= explode(',', $room_detail['guest_room_id']);
					foreach ($guest_explode as $value) 
					{
						$pax += count($value);
					}
				}
				
				$this->model_hotel->update_hotel(array('pax' => $pax),array('ID' => $input['edit_hotel_ID']));
			} 

			$this->session->set_flashdata('success',"Successfully update room details for hotel booking. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update room details for hotel booking. Please try again.");
		}

		redirect(base_url('hr/serviceform/hotel_form/'.$input['edit_hotel_ID'].'/room_detail'));
	}

	function hotel_delete_room()
	{
		$input 	= $this->input->post();
		$pax 	= 0;
		$update = array
		(
			'is_delete' 	=> 1, 
			'updated_by'	=> $this->logged_user['id'],
			'updated_ts'	=> date('Y-m-d H:i:s')
		);

		$updateRoomMain 	= $this->model_general->update('sv__hotel_room_detail', $update, array('ID' => $input['room_ID']));

		if($updateRoomMain)
		{
			$roomDetailList = $this->model_hotel->getHotelBookingRoomDetails($input['hotel_ID']);
			if($roomDetailList) foreach($roomDetailList as $room_detail)
			{
				$guest_explode	= explode(',', $room_detail['guest_room_id']);
				foreach ($guest_explode as $value) 
				{
					$pax += count($value);
				}

			}
			$this->model_hotel->update_hotel(array('pax' => $pax),array('ID' => $input['hotel_ID']));

			$this->model_general->update('sv__hotel_room_guest', $update, array('room_id' => $input['room_ID']));

			print json_encode(array(
				"status" 	=> "Success",
				"msg"	 	=> "Successfully deleted room details.",
				"redirect"	=> base_url('hr/serviceform/hotel_form/'.$input['hotel_ID']),
			)); 
		}
		else
		{
			print json_encode(array(
				"status" 	=> "Error",
				"msg"	 	=> "System failed to delete room details.",
				"redirect"	=> base_url('hr/serviceform/hotel_form/'.$input['hotel_ID']),
			));
		}
	}

	function flight_list($mode = '')
	{
		if($mode == 'submit') 
		{
			$this->session->set_flashdata('success',"Thank you for your requets.");
			redirect(base_url('hr/serviceform/flight_list'));
		}

		$this->load->model('hr/model_flight_booking');

		$flightDetail 	= $this->model_flight_booking->getListFlightBooking();
		$year	   		= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');

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

		if(!empty($flightDetail))
		{
			foreach ($flightDetail as $key => $detail) 
			{
				$createdTS   = date('Y-m-d',strtotime($detail['createdTS']));
				$start_date  = $detail['departure_date'];
				$end_date	 = $detail['return_date'];
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['dept_name'].'/'.$detail['branchName'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = $detail['requester_id'];
				$tmpEvent['start']          = $start_date;
				$tmpEvent['end']			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title']          = $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']    = $detail['requestor'].' request "'.$detail['flight_name'].'" booking.';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',0.5)';
				$tmpEvent['textColor']		= '#ffffff';

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

		$data = array
		(
            'department' 		=> $this->model_company->getDepartments(),
            'listName' 			=> $this->model_flight_booking->getlistName($this->logged_user['department_id']),
			'total_request'		=> $this->model_flight_booking->getRequestByCompany($year),
			'fc_res'            => json_encode($fc_res),
			'fc_event'          => json_encode($fc_event),
			'resource'          => json_encode($resource),
			'year'				=> date('Y')
		);


		if($this->logged_module['role'] == 'admin'){
            $data['listFlightBooking'] = $this->model_flight_booking->getListFlightBooking(null,null,$year);
		}else{	
            $data['listFlightBooking'] = $this->model_flight_booking->getListFlightBooking(null,$this->logged_user['id'],$year);
		}

		// die(debug($data['listFlightBooking']));

		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Flight List');
		$this->template->view('hr/policyprocedure/form/flight_list', $data);
	}

	function flight_form($ID = null, $mode = null)
	{
		$this->load->model('hr/model_flight_booking');
		$this->load->model('admin/model_user');
		
		$flightDetail 	= $this->model_flight_booking->getListFlightBooking();

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

		if(!empty($flightDetail))
		{
			foreach ($flightDetail as $key => $detail) 
			{
				$createdTS   = date('Y-m-d',strtotime($detail['createdTS']));
				$start_date  = $detail['departure_date'];
				$end_date	 = $detail['return_date'];
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['dept_name'].'/'.$detail['branchName'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = $detail['requester_id'];
				$tmpEvent['start']          = $start_date;
				$tmpEvent['end']			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title']          = $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']    = $detail['requestor'].' request "'.$detail['flight_name'].'" booking.';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',0.5)';
				$tmpEvent['textColor']		= '#ffffff';

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


		$data = array
		(
			'mode'						=> $mode,
			'listName'					=> $this->model_user->getUsers2(),
			'ID'	   					=> $ID,
			'upcoming_request'			=> $this->model_flight_booking->getBookingFlightByWeek(),
			'fc_res'            		=> json_encode($fc_res),
			'fc_event'          		=> json_encode($fc_event),
			'resource'          		=> json_encode($resource),
			'getListFlightBookingByID' 	=> $this->model_flight_booking->getListFlightBooking($ID),
		);

		if($this->logged_module['role'] == 'admin')
		{
	        if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__flight__booking';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'flight_list';
	            $data_approval['form_name'] = 'Flight Booking';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__flight__booking','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
	    }

		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Flight Form');
		$this->template->view('hr/policyprocedure/form/flight', $data);
	}

	function save_flight_form()
	{
		$input 			= $this->input->post();
		$requester_id 	= (isset($input['guest_details']))?$input['guest_details']:$input['name_id'];
		$baggage 		= (isset($input['other_baggage']))?$input['other_baggage']:$input['baggage'];

		$insert = array
		(
			'flight_name'		=> (!empty($input['other_flight_name']))?$input['other_flight_name']:$input['flightName'],
			'requester_id'		=> $requester_id,
			'departure_type'	=> $input['departure_type'],
			'ticket_type'		=> $input['ticket_type'],
			'origin'			=> $input['origin'],
            'destination'		=> $input['destination'],
            'departure_date' 	=> date('Y-m-d',strtotime($input['depart_date'])),
            'departure_time'	=> date('H:i:s',strtotime($input['depart_time'])),
            'return_date' 		=> ($input['ticket_type'] == 1)?'':date('Y-m-d',strtotime($input['return_date'])),
			'return_time'		=> ($input['ticket_type'] == 1)?'':date('H:i:s',strtotime($input['return_time'])),
			'flight_class'		=> $input['flightClass'],
			'baggage' 			=> $baggage,
			'createdBY'			=> $this->logged_user['id'],
		);

		$newFlightBooking = $this->model_general->insert('sv__flight__booking', $insert);

		if(!empty($newFlightBooking))
		{
			$form_detail = array 
			(
				'name' 				=> $input['name'],
				'email_address'		=> $input['email'],
				'department'		=> $input['department'],
				'date_request'		=> $input['datereq'],
				'type_of_departure'	=> ($input['departure_type'] == 0)?'International Departure':'Domestic Departure',
				'type_of_ticket'	=> ($input['ticket_type'] == 0)?'Two-Way Ticket':'One-Way Ticket',
				'origin'			=> $input['origin'],
	            'destination'		=> $input['destination'],
				'flight_name'		=> (!empty($input['other_flight_name']))?strtoupper($input['other_flight_name']):strtoupper($input['flightName']),
				'departure_date' 	=> $input['depart_date'].' '.$input['depart_time'],
				'baggage' 			=> $baggage,
				'meal'				=> $input['meal'],
				'flight_class'		=> $input['flightClass'],
			);

			if($input['ticket_type'] == 0) $form_detail['return_date'] = $input['return_date'].' '.$input['return_time'];

			$user_email = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));
			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($user_email, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			$send_copy_form_email 	= (isset($input['send_email_checkbox']) && $input['send_email_checkbox'] == 'on')?$input['send_email_checkbox']:'off';

			if($send_copy_form_email == 'on')
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['name_id']))[0];
				$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			}

			$form_requestor_name 	= $this->model_user->getUserDetail($input['name_id'])['name'];

			if($user_email)
			{
				$emailSubject 		= 'New Flight Booking - '.$form_requestor_name.' ['.str_pad($newFlightBooking,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $form_requestor_name.' has request flight booking on '.$input['datereq'].'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->model_approval->updateOrCreateNew('sv__flight__booking',$newFlightBooking,'Pending',0);
			
			$this->session->set_flashdata('success',"Successfully add new request for flight booking. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new request for flight booking.Please try again.");
		}

		redirect(base_url('hr/serviceform/flight_form/'.$newFlightBooking.'/guest_detail')); 
	}

	function edit_flight_form()
	{
		$this->load->model('hr/model_flight_booking');

		$input 			= $this->input->post();
		$flightID 		= $this->input->post('flightID');
		$baggage 		= (isset($input['other_baggage']))?$input['other_baggage']:$input['baggage'];
		$requester_id 	= (isset($input['guest_details']))?$input['guest_details']:((isset($input['guest_details_input']))?$input['guest_details_input']:$input['name_id']);

		$updateData = array
		(
			'flight_name'		=> (!empty($input['other_flight_name']))?$input['other_flight_name']:$input['flightName'],
			'requester_id'		=> $requester_id,
			'departure_type'	=> $input['departure_type'],
			'ticket_type'		=> $input['ticket_type'],
			'origin'			=> $input['origin'],
            'destination'		=> $input['destination'],
            'departure_date' 	=> date('Y-m-d',strtotime($input['depart_date'])),
            'departure_time'	=> date('H:i:s',strtotime($input['depart_time'])),
            'return_date' 		=> ($input['ticket_type'] == 1)?'':date('Y-m-d',strtotime($input['return_date'])),
			'return_time'		=> ($input['ticket_type'] == 1)?'':date('H:i:s',strtotime($input['return_time'])),
			'flight_class'		=> $input['flightClass'],
			'meal'				=> $input['meal'],
			'baggage' 			=> $baggage,
			'updatedBY' 		=> $this->logged_user['id'],
			'updatedTS'	 		=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $flightID,
		);

		$flightBooking = $this->model_flight_booking->update_flight($updateData,$where);

		if(!empty($flightBooking))
		{
			$this->session->set_flashdata('success',"Successfully update requested flight booking. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update requested flight booking.");
		}

		redirect(base_url('hr/serviceform/flight_form/'.$flightID.'/guest_detail'));
	}

	function deleteFlightList()
	{
		$this->load->model('hr/model_flight_booking');

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

		// debug($flightID);

		$sets = array
		(
			'is_delete'  	=> 1,
			'updatedBY'    	=> $this->logged_user['id'],
			'updatedTS'	 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $flightID,
		);

		$affected_rows = $this->model_flight_booking->update_flight($sets,$where);

		if($affected_rows)
		{
			$this->model_approval->update_sv_status('sv__flight__booking',$flightID);

			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted flight booking ."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete flight booking."
			));
		}
	}

	function flight_save_guest_detail()
	{
		$this->load->model('hr/model_flight_booking');

		$input 			= $this->input->post();
		$passport		= (isset($input['passport']))?$input['passport']:'';
		$flightPax 		= $this->model_flight_booking->getListFlightBooking($input['flight_ID'])[0]['no_of_passengers'];
		$guest 			= count($input['gID']);

		$insert = array
		(
			'flight_id'		=> $input['flight_ID'],
			'guest_id'		=> $input['gID'],
			'passport'		=> $passport,
			'createdBY'		=> $this->logged_user['id']
		);

		$newFlightGuest = $this->model_general->insert('sv__flight__booking_guest',$insert);

		if(!empty($newFlightGuest))
		{
			$this->model_general->update('sv__flight__booking',array('no_of_passengers'=>($flightPax + $guest)),array('ID'=>$input['flight_ID']));
			
			$this->session->set_flashdata('success',"Successfully add new flight guest detail. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new flight guest detail. Please try again.");
		}

		redirect(base_url('hr/serviceform/flight_form/'.$input['flight_ID'].'/guest_detail'));
	}

	function flight_edit_guest_detail()
	{
		$input = $this->input->post();
		$passport	= (isset($input['edit_passport']))?$input['edit_passport']:'';
		
		$updateData = array
		(
			'guest_id'		=> $input['edit_gID'],
			'passport'		=> $passport,
			'updatedBY' 	=> $this->logged_user['id'],
			'updatedTS'	 	=> date('Y-m-d H:i:s'),
		);

		$updateFlightGuest = $this->model_general->update('sv__flight__booking_guest',$updateData,array('ID' => $input['flight_detail_ID']));

		if(!empty($updateFlightGuest))
		{
			$this->session->set_flashdata('success',"Successfully update flight guest detail. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update flight guest detail. Please try again.");
		}

		redirect(base_url('hr/serviceform/flight_form/'.$input['flight_id'].'/guest_detail'));
	}

	function flight_delete_guest_detail()
	{
		$this->load->model('hr/model_flight_booking');
		$input 			= $this->input->post();
		$flightPax 		= $this->model_flight_booking->getListFlightBooking($input['flight_id'])[0]['no_of_passengers'];
		$guest 			= count($input['guest_id']);
		
		$updateData = array
		(
			'is_delete'		=> 1,
			'updatedBY' 	=> $this->logged_user['id'],
			'updatedTS'	 	=> date('Y-m-d H:i:s'),
		);

		$affected_rows = $this->model_general->update('sv__flight__booking_guest',$updateData,array('ID' => $input['detail_id']));

		if($affected_rows)
		{
			$this->model_general->update('sv__flight__booking',array('no_of_passengers'=>($flightPax - $guest)),array('ID'=>$input['flight_id']));
			
			print json_encode(array(
				"status" 	=> "Success",
				"msg"	 	=> "Successfully deleted flight guest detail.",
				"redirect"	=> base_url('hr/serviceform/flight_form/'.$input['flight_id'])
			)); 
		}
		else
		{
			print json_encode(array(
				"status" 	=> "Error",
				"msg"	 	=> "System failed to delete flight guest detail.",
				"redirect"	=> base_url('hr/serviceform/flight_form/'.$input['flight_id'])
			));
		}
	}

	function employee_form()
	{
		//$this->load->model('hr/model_stationery','model_stationery');

		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Employee Particulars Update for year 2020');
		$this->template->view('hr/policyprocedure/form/employee', $data);
	}

	function request_list()
	{
		$this->load->model('hr/model_training_request');
		
		$hod	= $this->model_company->getDepartmentHOD(array('a.hod_id' => $this->logged_user['id']));
		$year	= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');

		$trainingRequestDetails = $this->model_training_request->getListTrainingRequest();

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

		if(!empty($trainingRequestDetails))
		{
			foreach ($trainingRequestDetails as $key => $detail) 
			{
				$createdTS   = date('Y-m-d',strtotime($detail['createdTS']));
				$start_date  = $detail['proposed_date'];
				$end_date	 = $detail['proposed_date'];
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['dept_name'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = $detail['staff_id'];
				$tmpEvent['start']          = $start_date;
				$tmpEvent['end']			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title']          = $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']    = $detail['dept_name'].'/'.$detail['branchName'].' request training "'.$detail['topic'].'".';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',0.5)';
				$tmpEvent['textColor']      = '#ffffff';

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

		$data = array
		(
			'department' 			=> $this->model_company->getDepartments(),
			'total_request'			=> $this->model_training_request->getRequestByBusinessEntity($year),
			'business_entity'		=> $this->model_company->getBusinesses(1),
			'fc_res'            	=> json_encode($fc_res),
			'fc_event'          	=> json_encode($fc_event),
			'resource'          	=> json_encode($resource),
			'hod'					=> $hod,
		);
		
		if($this->logged_module['role'] == 'admin'){
			$data['listTrainingRequest'] = $this->model_training_request->getListTrainingRequest(null,null,null,$year);
		}else{
			if(!empty($hod))
			{	
				$data['listTrainingRequest'] = $this->model_training_request->getListTrainingRequest(null,null,$this->logged_user['department_id'],$year);
			}else{
				$data['listTrainingRequest'] = $this->model_training_request->getListTrainingRequest(null,$this->session->userdata('user')['id'],null,$year);
			}
		}
		
		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Training Request List');
		$this->template->view('hr/policyprocedure/form/request_list_new', $data);
	}

	function request_form($ID = null, $mode = null)
	{
		$this->load->model('admin/model_user');
		$this->load->model('hr/model_training_request');
		$trainingRequestDetails = $this->model_training_request->getListTrainingRequest();

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

		if(!empty($trainingRequestDetails))
		{
			foreach ($trainingRequestDetails as $key => $detail) 
			{
				$createdTS   = date('Y-m-d',strtotime($detail['createdTS']));
				$start_date  = $detail['proposed_date'];
				$end_date	 = $detail['proposed_date'];
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['dept_name'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = $detail['staff_id'];
				$tmpEvent['start']          = $start_date;
				$tmpEvent['end']			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title']          = $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']    = $detail['dept_name'].'/'.$detail['branchName'].' request training "'.$detail['topic'].'".';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',0.5)';
				$tmpEvent['textColor']      = '#ffffff';

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

		
		$data = array
		(
			'trainingRequestDetails'	=> $this->model_training_request->getListTrainingRequest($ID),
			'ID'         				=> $ID,
			'mode'         				=> $mode,
			'rsBusiness_entities'		=> $this->model_company->getBusinesses(1),
			'user_list'					=> $this->model_user->getUsers2(),
			'upcoming_request'			=> $this->model_training_request->getTrainingRequestByWeek(),
			'fc_res'            		=> json_encode($fc_res),
			'fc_event'          		=> json_encode($fc_event),
			'resource'          		=> json_encode($resource),
		);

		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Training Request Form');

		if($this->logged_module['role'] == 'admin')
		{
			if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__training_request';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'request_list';
	            $data_approval['form_name'] = 'Training Request';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__training_request','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
		}

		$this->template->view('hr/policyprocedure/form/request', $data);
	}

	function training_request_save()
	{
		$this->load->model('hr/model_training_request');
		$input = $this->input->post();
		
		$input['participant_email'] 		= array();
		$input['participant_department'] 	= array();
		$input['department_hod'] 			= array();

		$training_request = array
		(
			'user_id'				=> $input['reqNameID'],
			'department_id'			=> $input['department_id'],
			'business_entity_id'	=> $input['business_entity'],
			'topic'					=> $input['topic'],
			'venue'					=> $input['venue'],
			'organizer'				=> $input['organizer'],
			// 'time'					=> $input['time'],
			'cost'					=> $input['cost'],
            'date_from'				=> date('Y-m-d',strtotime($input['date_from'])),
            'date_to'				=> date('Y-m-d',strtotime($input['date_to'])),
            'proposed_date' 		=> date('Y-m-d',strtotime($input['proposed_date'])),
			'createdBY'				=> $this->logged_user['id']
		);

		if($input['participant']) foreach($input['participant'] as $part)
		{
			$user_dept_id 		= $this->model_training_request->getUserDepartment($part);
			$participant_email 	= $this->model_user->getUsersEmails(array('b.id = '.$part))[0];

			array_push($input['participant_department'],$user_dept_id['department_id']);
			array_push($input['participant_email'], ($participant_email['primary_email']) ? $participant_email['primary_email'] : (($participant_email['secondary_email']) ? $participant_email['secondary_email'] : $participant_email['email']));
		}

		$hods = $this->model_company->getDepartmentHOD(null,array('a.id' => $input['participant_department']));
		
		if($hods) foreach($hods as $hod)
		{
			array_push($input['department_hod'], ($hod['primary_email']) ? $hod['primary_email'] : (($hod['secondary_email']) ? $hod['secondary_email'] : $hod['email']));
		}

		$newTrainingRequest = $this->model_general->insert('sv__training_request', $training_request);
		
		$participantDetail 	= (!empty($input['participant']))?$input['participant']:array();
		$participanDeptID 	= (!empty($input['participant_department']))?$input['participant_department']:array();
		$participant_add 	= $this->model_training_request->updateOrCreateNew($newTrainingRequest,$participantDetail,$participanDeptID);
		
		$this->load->library('File_upload');

		$upload_directory = 'assets/upload/hr/Form/trainingRequest/';

		$upload_status = $this->file_upload
			->set_file_type(FILE_TYPE_UPLOAD)
			->set_directory_public()
			->set_upload_directory($upload_directory)
			->uploads('picture_upload');

		if(is_array($upload_status)) {
			$uploadFile = array
			(
				'photo_title'			=> (!empty($upload_status['file_name']))? $upload_status['file_name']:'',
				'sv_trainingRequest_id' => $newTrainingRequest,
				'file_location'			=> (!empty($upload_status['file_name']))?$upload_directory:'', 
				'is_delete'				=> 0,
			);
			// die(debug($uploadPhoto));

			$newTrainingRequestUpload = $this->model_general->insert('sv__training_request__upload',$uploadFile);

			// die(debug($newMaintenance2));
		} else {
			echo json_encode('Failed');
		}

		if(!empty($newTrainingRequest))
		{
			$form_detail = array 
			(
				'name' 				=> $input['reqName'],
				'email_address'		=> $input['email'],
				'department'		=> $input['department'],
				'date_request'		=> $input['datereq'],
				'topic'				=> $input['topic'],
	            'venue'				=> $input['venue'],
				'date' 				=> $input['date_from'].' '.$input['date_to'],
				'cost' 				=> ($input['cost'])?('RM'.number_format($input['cost'],2)):'RM0.00',
				'sharing_date'		=> $input['proposed_date'],
			);

			$user_email = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));
			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($user_email, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			/* participant email */
			if($input['participant_email']) foreach($input['participant_email'] as $participant_email)
			{
				array_push($user_email, $participant_email);
			}

			/* hod email */
			if($input['department_hod']) foreach($input['department_hod'] as $hod_email)
			{
				array_push($user_email, $hod_email);
			}

			$send_copy_form_email 	= (isset($input['send_email_checkbox']) && $input['send_email_checkbox'] == 'on')?$input['send_email_checkbox']:'off';

			if($send_copy_form_email == 'on')
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['reqNameID']))[0];
				$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			}

			$form_requestor_name 	= $input['reqName'];

			if($user_email)
			{
				$emailSubject 		= 'New Training Request - '.$form_requestor_name.' ['.str_pad($newTrainingRequest,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $form_requestor_name.' has request training on '.$input['datereq'].'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->model_approval->updateOrCreateNew('sv__training_request',$newTrainingRequest,'Pending',0);

			$this->session->set_flashdata('success',"Successfully add new request for training. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new request for training.Please try again.");
		}

		redirect(base_url('hr/serviceform/request_list')); 
	}

	function training_request_edit()
	{
		$this->load->model('hr/model_training_request');

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

		$trainingRequestID 	= $this->input->post('trainingRequestID');
		$uploadID 			= $this->input->post('upload_id');

		// die(debug($input));
		
		$updateData = array(
			'user_id'				=> $input['reqNameID'],
			'department_id'			=> $input['department_id'],
			'business_entity_id'	=> $input['business_entity'],
			'topic'					=> $input['topic'],
			'venue'					=> $input['venue'],
			'organizer'				=> $input['organizer'],
			'time'					=> $input['time'],
			'cost'					=> $input['cost'],
			// 'participant'			=> $input['participant'],
            'proposed_date' 		=> date('Y-m-d',strtotime($input['proposed_date'])),
			'updatedBY' 			=> $this->logged_user['id'],
			'updatedTS'	 			=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $trainingRequestID,
		);

		$affected_rows = $this->model_training_request->update_training_request($updateData,$where);

		$participantDetail 	= (!empty($input['participant']))?$input['participant']:array();
		$participant_add 	= $this->model_training_request->updateOrCreateNew($trainingRequestID,$participantDetail);

		if(!empty($_FILES['picture_upload']['name']))
		{
			$this->load->library('File_upload');

			$upload_directory = 'assets/upload/hr/Form/trainingRequest/';

			$upload_status = $this->file_upload
				->set_file_type(FILE_TYPE_UPLOAD)
				->set_directory_public()
				->set_upload_directory($upload_directory)
				->uploads('picture_upload');

				// die(debug($upload_status));

			if(is_array($upload_status)) 
			{
				$uploadFile = array
				(
					'photo_title'         	=> (($upload_status['file_name']))?$upload_status['file_name']:$input['picture_upload'],
					// 'filename'       		=> (!empty($upload_status['file_location']))?$upload_status['file_location']:''
					'file_location'     	=> (!empty($upload_status['file_name']))?$upload_directory:'', 
					'is_delete'         	=> 0,
					'updatedBY' 			=> $this->logged_user['id'],
					'updatedTS'	 			=> date('Y-m-d H:i:s'),
				); 

				// die(debug($uploadFile));

				if(empty($uploadID))
				{
					$uploadFile['sv_trainingRequest_id'] = $trainingRequestID;
				}

				$where = array
				(
					'ID' => $uploadID,
				);
				// die(debug($where));

				//$affected_rows2 = $this->model_training_request->update_training_request_upload($uploadFile, $where);

				if(!empty($uploadID)){
					$affected_rows2 = $this->model_training_request->update_training_request_upload($uploadFile, $where);
				} else {	
					$affected_rows2 = $this->model_general->insert('sv__training_request__upload',$uploadFile);
				}

			// die(debug($affected_rows));
			
			} else {
				'Failed';
			}
		}

		if(!empty($affected_rows))
		{
			$this->session->set_flashdata('success',"Successfully update requested training. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update requested training.");
		}

		redirect(base_url('hr/serviceform/request_list'));
	}

	function deleteTrainingRequestList()
	{
		$this->load->model('hr/model_training_request');

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

		$sets = array
		(
			'is_delete'  	=> 1,
			'updatedBY'    	=> $this->logged_user['id'],
			'updatedTS'	 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $trainingRequestID,
		);

		$affected_rows = $this->model_training_request->update_training_request($sets,$where);

		if($affected_rows)
		{
			$this->model_general->update('sv__training_request_participant',$sets,array('sv_trainingRequest_id' => $trainingRequestID));
			$this->model_general->update('sv__training_request__upload',$sets,array('sv_trainingRequest_id' => $trainingRequestID));

			$this->model_approval->update_sv_status('sv__training_request',$trainingRequestID);

			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted training request."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete training request."
			));
		}
	}

	function hodApprovalTrainingRequest()
	{
		$this->load->model('hr/model_training_request');

		$input 					= $this->input->post();
		$participant_id 		= $this->input->post('participant_id');
		$participant_user_id 	= $this->input->post('participant_user_id');
		$approval_status 		= $this->input->post('approval_status');
		$approved_mode			= ($approval_status == 1)?'approv':'reject'; 		

		$sets = array
		(
			'hod_status'  	=> $approval_status,
			'approvedBY'   	=> $this->logged_user['id'],
			'approvedTS' 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' 		=> $participant_id,
			'user_id' 	=> $participant_user_id,
		);

		$affected_rows = $this->model_general->update('sv__training_request_participant',$sets,$where);

		if($affected_rows)
		{
			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully ".$approved_mode."ed training request."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to ".$approved_mode." training request."
			));
		}
	}

	function evaluation_list()
	{
		$this->load->model('hr/model_training_evaluation');

		if($_SESSION['module_data']['role']=='admin'){
			$data['listTrainingEvaluation'] = $this->model_training_evaluation->getListTrainingEvaluation();
		}else{
			$data['listTrainingEvaluation'] = $this->model_training_evaluation->getListTrainingEvaluation($this->session->userdata('user')['id']);
		}
		//die(debug($data['listTrainingEvaluation']));
		$data['department'] = $this->model_company->getDepartments();
		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Training Evaluation List');
		$this->template->view('hr/policyprocedure/form/evaluation_list', $data);
	}

	function evaluation_form($ID=0)
	{
		$this->load->model('hr/model_training_evaluation');

		$data = array
		(
			'rsEvaluationQuestion' 		=> $this->model_training_evaluation->getEvaluationQuestionDetails($ID),
			'rsDepartments' 			=> $this->model_training_evaluation->name_with_branch(),
			'evaluation_detail' 		=> $this->model_training_evaluation->getAllEvaluationDetails_new($ID),
			'ID' 						=> $ID,
			'page_setup' 				=> $this->template->pageSetup('Online Form', '', 'Training Evaluation Form')
		);

		if(!empty($ID))
		{
			foreach ($data['evaluation_detail'] as $key => $value) 
			{
				if(!empty($value['questionID']))
				{
					$data['evaluation_detail'][$key]['qtn_id'] = explode("==>", $value['questionID']);
				}else{
					$data['evaluation_detail'][$key]['qtn_id'] = '';
				}

				if(!empty($value['question']))
				{
					$data['evaluation_detail'][$key]['qtn'] = explode("==>", $value['question']);
				}else{
					$data['evaluation_detail'][$key]['qtn'] = '';
				}

				if(!empty($value['answer_radio']))
				{
					$data['evaluation_detail'][$key]['radio'] = explode("==>", $value['answer_radio']);
				}else{
					$data['evaluation_detail'][$key]['radio'] = '';
				}

				if(!empty($value['answer_text']))
				{
					$data['evaluation_detail'][$key]['txt'] = explode("==>", $value['answer_text']);
				}else{
					$data['evaluation_detail'][$key]['txt'] = '';
				}
			}
		}
		// if($ID >0) 	$data['rsEvaluationDetails'] = $this->model_training_evaluation->getAllEvaluationDetails($ID);
		// 			$data['rsUserEvaluationDetails'] = $this->model_training_evaluation->getUserEvaluationDetails($ID);
		// 			$data['rsEvaluationAnswer'] = $this->model_training_evaluation->getEvaluationAnswerDetails($ID);
		//die(debug($data['detailsTrainingEvaluation']));

		$this->template->view('hr/policyprocedure/form/evaluation', $data);
	}

	function evaluation_form_save()
	{
		$input = $this->input->post();


		// $evaluationID = $this->input->post('evaluation_id');

		//debug($input);

		$userData = array
		(
			'user_id'				=> $input['user_id'],
			'department_id'			=> $input['department_id'],
			'createdBY'				=> $this->logged_user['id']
		);

		$newUser = $this->model_general->insert('sv__evaluation', $userData);

		if(!empty($newUser)){
			$evaluationData = array
			(
				'training_title'		=> $input['title'],
				'packages'				=> $input['packages'],
				'venue'					=> $input['venue'],
				'training_date'			=> $input['date_training'],
				'time'					=> $input['time'],
				'respective_dept'		=> $input['respective_dept'],
				'cpd_hours'				=> $input['hour'],
				'trainer_name'			=> $input['trainer_name'],
				'createdBY'				=> $this->logged_user['id']
			);
		}

		$newTrainingEvaluation = $this->model_general->insert('sv__evaluation_training', $evaluationData);

		//die($newTrainingEvaluation);
		if($newUser && $newTrainingEvaluation)
		{
			foreach($input['question_id'] as $question_id){
				//echo '<br>no soalan',$question_id; 
				//echo '<br>jawapan'.(!empty($input['answerRadio'][$question_id]))?$input['answerRadio'][$question_id] :null;
				//echo '<br>type'.$input['question_type'][$question_id];
	
				$answerData = array 
				(
					'sv_evaluation_id'			=> $newUser,
					'sv_evaluation_training_id'	=> $newTrainingEvaluation,
					'sv_evaluation_question_id'	=> $question_id,
					// 'answer_radio'				=> (!empty($input['answerRadio'][$question_id]))?$input['answerRadio'][$question_id] :'',
					// 'answer_text'				=> (!empty($input['answerText'][$question_id]))?$input['answerText'][$question_id] :'',
					'createdBY'					=> $this->logged_user['id']
				);
	
				if($input['question_type'][$question_id] == 0){
					$answerData['answer_radio'] = (!empty($input['answerRadio'][$question_id]))?$input['answerRadio'][$question_id] :'';
				}
				elseif($input['question_type'][$question_id] == 1){
					$answerData['answer_text'] = (!empty($input['answerText'][$question_id]))?$input['answerText'][$question_id] :'';
				}else{
					return false;
				}
	
				$newAnswer = $this->model_general->insert('sv__evaluation__answer', $answerData);
			}
		}

		if(!empty($newAnswer))
		{

			$this->session->set_flashdata('success',"Successfully add new training evaluation. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new training evaluation.Please try again.");
		}

		redirect(base_url('hr/serviceform/evaluation_list')); 
	}

	function delete_evaluation_form()
	{
		$this->load->model('hr/model_training_evaluation');

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

		$sets = array
		(
			'is_delete'  	=> 1,
			'updatedBY'    	=> $this->logged_user['id'],
			'updatedTS'	 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $evaluation_id,
		);

		$affected_rows = $this->model_training_evaluation->update_training_evaluation($sets,$where);

		if($affected_rows)
		{
			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted training evaluation."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete training evaluation"
			));
		}
	}

	function it_equipment_list()
	{
		$this->load->model('hr/model_av_it');

		$equipment_list = $this->model_av_it->getEquipmentList();
        $year	   		= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');

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

		if(!empty($equipment_list))
		{
			foreach ($equipment_list as $key => $details) 
			{
				$createdTS  = date('Y-m-d',strtotime($details['createdTS']));
				$startDate  = $details['check_in'];
				$endDate    = $details['check_out'];
				
				$tmpRes 					= array(); $tmpEvent = array();
				$tmpRes['id']  				= $details['ID'];
				$tmpRes['title'] 			= $details['dept_name'];

				$tmpEvent['id'] 			= $key;
				$tmpEvent['resourceId'] 	= $details['staff_id'];
				$tmpEvent['start'] 			= $startDate;
				$tmpEvent['end'] 			= date('Y-m-d',strtotime($endDate."+1 days"));
				$tmpEvent['title'] 			= $details['dept_name'].'/'.$details['branchName'];
				$tmpEvent['description']	= $details['dept_name'].' request "'.$details['hardware'].'" and "'.$details['software'].'".';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',0.5)';
				$tmpEvent['textColor']		= '#ffffff';

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

		$data = array
		(
			'page_setup' 		=> $this->template->pageSetup('Online Form', '', 'AV/IT Equipment Request List'),
			'department' 		=> $this->model_company->getDepartments(),
			'count_request'		=> $this->model_av_it->getRequestByCompany($year),
			// 'request_monthly' 	=> $this->model_av_it->getEquipmentRequestRoomByMonth(),
			'fc_res'			=> json_encode($fc_res),
			'fc_event'			=> json_encode($fc_event),
			'resource'			=> json_encode($resource),
		);

		if($this->logged_user['division_id'] == 19){
			$data['equipment_list'] = $this->model_av_it->getEquipmentList(null,null,$year);
		}else{
			$data['equipment_list'] = $this->model_av_it->getEquipmentList(null,$this->session->userdata('user')['id'],$year);
		}

		$this->template->view('hr/policyprocedure/form/it_equipment_list', $data);
	}

	function it_equipment_form($ID = null)
	{
		$this->load->model('hr/model_av_it');

		$equipment_list = $this->model_av_it->getEquipmentList();

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

		if(!empty($equipment_list))
		{
			foreach ($equipment_list as $key => $details) 
			{
				$createdTS  = date('Y-m-d',strtotime($details['createdTS']));
				$startDate  = $details['check_in'];
				$endDate    = $details['check_out'];
				
				$tmpRes 					= array(); $tmpEvent = array();
				$tmpRes['id']  				= $details['ID'];
				$tmpRes['title'] 			= $details['dept_name'];

				$tmpEvent['id'] 			= $key;
				$tmpEvent['resourceId'] 	= $details['staff_id'];
				$tmpEvent['start'] 			= $startDate;
				$tmpEvent['end'] 			= date('Y-m-d',strtotime($endDate."+1 days"));
				$tmpEvent['title'] 			= $details['dept_name'].'/'.$details['branchName'];
				$tmpEvent['description']	= $details['dept_name'].' request "'.$details['hardware'].'" and "'.$details['software'].'".';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',0.5)';
				$tmpEvent['textColor']		= '#ffffff';

				array_push($fc_res, $tmpRes);
				array_push($fc_event, $tmpEvent);
				array_push($resource, $details);
			}
		// debug($details);
		}

		$data = array
		(
			'page_setup' 		=> $this->template->pageSetup('Online Form', '', 'AV/IT Equipment Request Form'),
			'equipment_detail' 	=> $this->model_av_it->getEquipmentList($ID),
			'upcoming_request' 	=> $this->model_av_it->getEquipmentRequestByWeek(),
			'ID'				=> $ID,
			'fc_res'			=> json_encode($fc_res),
			'fc_event'			=> json_encode($fc_event),
			'resource'			=> json_encode($resource),
		);

		if($this->logged_user['division_id'] == 19)
		{
			if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__it__equipment';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'it_equipment_list';
	            $data_approval['form_name'] = 'AV/IT Equipment Request';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__it__equipment','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
		}

		$this->template->view('hr/policyprocedure/form/it_equipment', $data);
	}

	function it_equipment_calendar()
	{
		$this->load->model('hr/model_av_it');

		$equipment_list = $this->model_av_it->getEquipmentList();

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

		if(!empty($equipment_list))
		{
			foreach ($equipment_list as $key => $details) 
			{
				$createdTS  = date('Y-m-d',strtotime($details['createdTS']));
				$startDate  = $details['check_in'];
				$endDate    = $details['check_out'];
				
				$tmpRes 					= array(); $tmpEvent = array();
				$tmpRes['id']  				= $details['ID'];
				$tmpRes['title'] 			= $details['dept_name'];

				$tmpEvent['id'] 			= $key;
				$tmpEvent['resourceId'] 	= $details['staff_id'];
				$tmpEvent['start'] 			= $startDate;
				$tmpEvent['end'] 			= date('Y-m-d',strtotime($endDate."+1 days"));
				$tmpEvent['title'] 			= $details['dept_name'].'/'.$details['branchName'];
				$tmpEvent['description']	= $details['dept_name'].' request "'.$details['hardware'].'" and "'.$details['software'].'".';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',0.5)';
				$tmpEvent['textColor']		= '#ffffff';

				array_push($fc_res, $tmpRes);
				array_push($fc_event, $tmpEvent);
				array_push($resource, $details);
			}
		// debug($details);
		}

		$data = array
		(
			'page_setup' 		=> $this->template->pageSetup('Online Form', '', 'AV/IT Equipment Request Calendar'),
			'equipment_list' 	=> $this->model_av_it->getEquipmentList(),
			'fc_res'			=> json_encode($fc_res),
			'fc_event'			=> json_encode($fc_event),
			'resource'			=> json_encode($resource),
		);
		
		$this->template->view('hr/policyprocedure/calendar/it_equipment_calendar', $data);
	}

	function it_equipment_form_save()
	{
		$input = $this->input->post();

		$insert = array
		(
			'borrower_id' 		=> $input['borrower_id'],
			'department_id' 	=> $input['department_id'],
			'hardware' 			=> $input['hardware'],
			'hw_reason' 		=> $input['hw_reason'],
			'software' 			=> $input['software'],
			'sw_reason' 		=> $input['sw_reason'],
			'check_in' 			=> date('Y-m-d',strtotime($input['check_in'])),
			'check_out'			=> date('Y-m-d',strtotime($input['check_out'])),
			'createdBY'			=> $this->logged_user['id'],
			'createdTS'			=> date('Y-m-d',strtotime($input['date_request']))
		);

		$new_equipment = $this->model_general->insert('sv__it__equipment',$insert);

		if(!empty($new_equipment))
		{
			$form_detail = array 
			(
				'name' 				=> $input['borrower_name'],
				'email_address'		=> $input['email'],
				'department'		=> $input['department_name'],
				'date_request'		=> $input['date_request'],
				'hardware'			=> $input['hardware'],
				'hw_reason'			=> $input['hw_reason'],
				'software'			=> $input['software'],
				'sw_reason'			=> $input['sw_reason'],
				'check_in_date'		=> $input['check_in'],
				'check_out_date'	=> $input['check_out']
			);

			$user_email 	= array();
			$admin_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 19'));
			if($admin_detail) foreach($admin_detail as $admin_email) 
			{
				array_push($user_email, ($admin_email['primary_email']) ? $admin_email['primary_email'] : (($admin_email['secondary_email']) ? $admin_email['secondary_email'] : $admin_email['email']));
			}

			$send_copy_form_email 	= (isset($input['send_email_checkbox']) && $input['send_email_checkbox'] == 'on')?$input['send_email_checkbox']:'off';

			if($send_copy_form_email == 'on')
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['borrower_id']))[0];
				$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			}

			$form_requestor_name 	= $this->model_user->getUserDetail($input['borrower_id'])['name'];
			
			if($user_email)
			{
				$emailSubject 		= 'New AV/IT Equipment Request - '.$form_requestor_name.' ['.str_pad($new_equipment,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $form_requestor_name.' has request AV/IT Equipment on '.$input['date_request'].'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->model_approval->updateOrCreateNew('sv__it__equipment',$new_equipment,'Pending',0);

			$this->session->set_flashdata('success',"Successfully add new request for av/it equipment. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new request for av/it equipment.Please try again.");
		}

		redirect(base_url('hr/serviceform/it_equipment_list')); 
	}

	function it_equipment_form_edit()
	{
		$this->load->model('hr/model_av_it');

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

		$sets = array
		(
			'borrower_id' 		=> $input['borrower_id'],
			'department_id' 	=> $input['department_id'],
			'hardware' 			=> $input['hardware'],
			'hw_reason' 		=> $input['hw_reason'],
			'software' 			=> $input['software'],
			'sw_reason' 		=> $input['sw_reason'],
			'check_in' 			=> date('Y-m-d',strtotime($input['check_out'])),
			'check_out'			=> date('Y-m-d',strtotime($input['check_in'])),
			'createdBY'			=> $this->logged_user['id'],
		);

		$where = array('ID' => $input['equipmentID']);

		$edit_equipment = $this->model_av_it->update_av_it($sets,$where);

		if(!empty($edit_equipment))
		{
			$this->session->set_flashdata('success',"Successfully update requested av/it equipment. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update requested av/it equipment.");
		}

		redirect(base_url('hr/serviceform/it_equipment_list/'));
	}

	function it_equipment_form_delete()
	{
		$this->load->model('hr/model_av_it');

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

		$sets = array
		(
			'is_delete' 		=> 1,
			'createdBY'			=> $this->logged_user['id'],
		);

		$where = array('ID' => $input['equipment_id']);

		$delete_equipment = $this->model_av_it->update_av_it($sets,$where);

		if($delete_equipment)
		{
			$this->model_approval->update_sv_status('sv__it__equipment',$input['equipment_id']);

			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully delete AV/IT equipment request."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete AV/IT equipment request."
			));
		}

		// redirect(base_url('hr/serviceform/it_equipment_list'));
	}

	function it_service_list()
	{
		$this->load->model('hr/model_it_service');

		$data['department'] = $this->model_company->getDepartments();
        $year	   		= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');
		
		if($this->logged_user['division_id'] == 19){
			$data['rsServiceList'] = $this->model_it_service->getServiceList(null,null,$year);
		}else{
			$data['rsServiceList'] = $this->model_it_service->getServiceList(null,$this->session->userdata('user')['id'],$year);
		}
	
		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'AV/IT Service Request List');
		$this->template->view('hr/policyprocedure/form/it_service_list', $data);
	}
	
	function it_service_form($ID = null)
	{
        $this->load->model('hr/model_it_service');
        $data['ID'] = $ID;
        
		if($ID > 0) {
			$data['rsServiceList'] = $this->model_it_service->getServiceListForm($ID);
			$data['row'] = (sizeof($data['rsServiceList'])>0)?$data['rsServiceList'][0]:null; 
		}
		
		if($this->logged_user['division_id'] == 19)
		{
			if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__it_service';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'it_service_list';
	            $data_approval['form_name'] = 'AV/IT Service Request';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__it_service','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
		}
		
		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'AV/IT Service Request List');
		$this->template->view('hr/policyprocedure/form/it_service', $data);
	}

	function it_service_save()
	{
		$input = $this->input->post();
		//die(debug($input));

		$insertData = array(
			'user_id'    		=> $this->input->post('name_id'),
			'department_id' 	=> $this->input->post('department_id'),
			'dateRequest'       => $this->input->post('datereq'),
			'location'    		=> $this->input->post('location'),
			'request'       	=> $this->input->post('request'),
			'problem'     		=> $this->input->post('problem'),
			'complaint'     	=> $this->input->post('complaint'),
			'hardware'     		=> $this->input->post('hardware'),
			'createdBY'     	=> $this->logged_user['id']
		);
		$newServiceRequest = $this->model_general->insert('sv__it_service', $insertData);
		
		if(!empty($newServiceRequest))
		{
			$form_detail = array 
			(
				'name' 				=> $this->input->post('name'),
				'email_address'		=> $this->input->post('email'),
				'department'		=> $this->input->post('department'),
				'date_request'		=> $this->input->post('datereq'),
				'location'			=> $this->input->post('location'),
				'request'			=> $this->input->post('request'),
				'hardware'			=> $this->input->post('hardware'),
				'problem'			=> $this->input->post('problem'),
				'complaint'			=> $this->input->post('complaint'),
			);

			$user_email 	= array();
			$admin_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 19'));
			if($admin_detail) foreach($admin_detail as $admin_email) 
			{
				array_push($user_email, ($admin_email['primary_email']) ? $admin_email['primary_email'] : (($admin_email['secondary_email']) ? $admin_email['secondary_email'] : $admin_email['email']));
			}

			$email_checkbox = $this->input->post('send_email_checkbox');

			$send_copy_form_email = (isset($email_checkbox) && $email_checkbox == 'on')?$email_checkbox:'off';

			if($send_copy_form_email == 'on')
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$this->input->post('name_id')))[0];
				$form_requestor_email 	= array($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			}

			$form_requestor_name 	= $this->model_user->getUserDetail($this->input->post('name_id'))['name'];
			
			if($user_email)
			{
				$emailSubject 		= 'New AV/IT Service Request - '.$form_requestor_name.' ['.str_pad($newServiceRequest,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $form_requestor_name.' has request AV/IT Service on '.$this->input->post('datereq').'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->model_approval->updateOrCreateNew('sv__it_service',$newServiceRequest,'Pending',0);

			$this->session->set_flashdata('success',"Successfully add new request for av/it service. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new request for av/it service. Please try again.");
		}

		redirect(base_url('hr/serviceform/it_service_list'));
	}

	function it_service_edit()
	{
		$this->load->model('hr/model_it_service');
	
		$itServiceID = $this->input->post('itServiceID');
	
		// die(debug($itServiceID));
	
		$sets = array
		(
			'user_id'    		=> $this->input->post('name_id'),
			'department_id' 	=> $this->input->post('department_id'),
			'dateRequest'       => $this->input->post('datereq'),
			'location'    		=> $this->input->post('location'),
			'request'       	=> $this->input->post('request'),
			'problem'     		=> $this->input->post('problem'),
			'complaint'     	=> $this->input->post('complaint'),
			'hardware'     		=> $this->input->post('hardware'),
			'updatedBY'     => $this->logged_user['id'],
			'updatedTS'     => date('Y-m-d H:i:s'),
		);
	
		$where = array 
		(
			'ID' => $itServiceID,
		);    
		$affected_rows = $this->model_it_service->update_service($sets,$where);
		
		if(!empty($affected_rows))
		{
			$this->session->set_flashdata('success',"Successfully update requested av/it service. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update requested av/it service.");
		}

		redirect(base_url('hr/serviceform/it_service_list'));
	}

	function deleteServiceList()
	{
		$this->load->model('hr/model_it_service');

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

		$sets = array
		(
			'is_delete'   => 1,
			'updatedBY'   => $this->logged_user['id'],
			'updatedTS'   => date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $itServiceID,
		);

		$affected_rows = $this->model_it_service->update_service($sets,$where);

		if($affected_rows)
		{
			$this->model_approval->update_sv_status('sv__it_service',$itServiceID);

			print json_encode(array(
				"status" => "Success",
				"msg"  => "Successfully deleted request ."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"  => "System failed to delete request."
			));
		}
	}

	function policereport_list()
	{
		$this->load->model('hr/model_police_report');

		$data['department'] = $this->model_company->getDepartments();

		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl']=='admin' || $this->logged_user['division_id'] == 4){
			$data['listPoliceReport'] = $this->model_police_report->getListPoliceReport();
		}else{
			$data['listPoliceReport'] = $this->model_police_report->getListPoliceReport(null,$this->session->userdata('user')['id']);
		}

		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Police Report List');
		$this->template->view('hr/policyprocedure/form/policereport_list', $data);
	}

	function police_report_form($ID=null)
	{
		$this->load->model('hr/model_police_report');
		$this->load->model('admin/model_user');

		$data['ID']			= $ID;
		$data['user_phone'] = $this->model_user->getUsers2($this->logged_user['id'])['phone'];
		if($ID >0) 	$data['policeReportDetails'] 	= $this->model_police_report->getPoliceReportDetails($ID);

		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Police Report Form');
		$this->template->view('hr/policyprocedure/form/police_report', $data);
	}

	function police_report_save()
	{
		$input = $this->input->post();

		//die(debug($input));
		$police_report = array
		(
			'user_id'				=> $input['reqName_id'],
			'department_id'			=> $input['department_id'],
			'position'				=> $input['position'],
			'phone'					=> $input['phone'],
            'location'				=> $input['location'],
            'incident_date' 		=> date('Y-m-d',strtotime($input['incident_date'])),
            'incident_time'			=> $input['incident_time'],
            'reported_date' 		=> date('Y-m-d',strtotime($input['reported_date'])),
			'time_reported'			=> $input['time_reported'],
			'supervisor'			=> $input['supervisor'],
			'equipment_damaged'		=> $input['equipment_damaged'],
			'equipment_number'		=> $input['equipment_number'],
			'equipment_location'	=> $input['equipment_location'],
			'reason_damage'			=> $input['reason_damage'],
			'description_damage'	=> $input['description_damage'],
			'repair_cost'			=> $input['repair_cost'],
			'responsible_person'	=> $input['responsible_person'],
			'police_report'			=> $input['police_report'],
			'police_file'			=> $input['police_file'],
			'officer_incharge'		=> $input['officer_incharge'],
			'station'			    => $input['station'],
			'contact_no'			=> $input['contact_no'],
			'createdBY'				=> $this->logged_user['id']
						
		);

		$newPoliceReport = $this->model_general->insert('sv__police_report', $police_report);

		$this->load->library('File_upload');

		$upload_directory = 'assets/upload/hr/Form/policeReport/';

		$upload_status = $this->file_upload
			->set_file_type(FILE_TYPE_UPLOAD)
			->set_directory_public()
			->set_upload_directory($upload_directory)
			->uploads('file_upload');

			// die(debug($upload_status));

		if(is_array($upload_status)) {
			$uploadFile = array
			(
				'file_title'			=> (!empty($upload_status['file_name']))? $upload_status['file_name']:'',
				'sv_policeReport_id' 	=> $newPoliceReport,
				'file_location'			=> (!empty($upload_status['file_name']))?$upload_directory:'', 
				'is_delete'				=> 0,
			);
			// die(debug($uploadPhoto));

			$newTrainingRequestUpload = $this->model_general->insert('sv__police_report__upload',$uploadFile);

			// die(debug($newMaintenance2));
		} else {
			'tidak berjaya';
		}

		if(!empty($newPoliceReport))
		{
			$this->session->set_flashdata('success',"Successfully add new police report. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new police report. Please try again.");
		}

		redirect(base_url('hr/serviceform/policereport_list'));
	}

	function police_report_edit()
	{
		$this->load->model('hr/model_police_report');

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

		$policeReportID 	= $this->input->post('policeReportID');
		$uploadID 			= $this->input->post('upload_id');
		
		$updateData = array
		(
			'user_id'				=> $input['reqName_id'],
			'department_id'			=> $input['department_id'],
			'position'				=> $input['position'],
			'phone'					=> $input['phone'],
			'location'				=> $input['location'],
            'incident_date' 		=> date('Y-m-d',strtotime($input['incident_date'])),
			'incident_time'			=> $input['incident_time'],
            'reported_date' 		=> date('Y-m-d',strtotime($input['reported_date'])),
			'time_reported'			=> $input['time_reported'],
			'supervisor'			=> $input['supervisor'],
			'equipment_damaged'		=> $input['equipment_damaged'],
			'equipment_number'		=> $input['equipment_number'],
			'equipment_location'	=> $input['equipment_location'],
			'reason_damage'			=> $input['reason_damage'],
			'description_damage'	=> $input['description_damage'],
			'repair_cost'			=> $input['repair_cost'],
			'responsible_person'	=> $input['responsible_person'],
			'police_report'			=> $input['police_report'],
			'police_file'			=> $input['police_file'],
			'officer_incharge'		=> $input['officer_incharge'],
			'station'				=> $input['station'],
			'contact_no'			=> $input['contact_no'],
			'updatedBY' 			=> $this->logged_user['id'],
			'updatedTS'	 			=> date('Y-m-d H:i:s'),
		);
		
		$where = array
		(
			'ID' => $policeReportID,
		);

		$affected_rows = $this->model_police_report->update_police_report($updateData,$where);
		//die(debug($affected_rows));

		if(!empty($_FILES['file_upload']['name']))
		{
			$this->load->library('File_upload');

			$upload_directory = 'assets/upload/hr/Form/policeReport/';

			$upload_status = $this->file_upload
				->set_file_type(FILE_TYPE_UPLOAD)
				->set_directory_public()
				->set_upload_directory($upload_directory)
				->uploads('file_upload');

				// die(debug($upload_status));

			if(is_array($upload_status)) 
			{
				$uploadFile = array
				(
					'file_title'         	=> (($upload_status['file_name']))?$upload_status['file_name']:$input['file_upload'],
					// 'filename'       		=> (!empty($upload_status['file_location']))?$upload_status['file_location']:''
					'file_location'     	=> (!empty($upload_status['file_name']))?$upload_directory:'', 
					'is_delete'         	=> 0,
					// 'updatedBY' 			=> $this->logged_user['id'],
					// 'updatedTS'	 			=> date('Y-m-d H:i:s'),
				); 

				// die(debug($uploadPhoto));

				if(empty($uploadID))
				{
					$uploadFile['sv_policeReport_id'] = $policeReportID;
				}

				$where = array
				(
					'ID' => $uploadID,
				);
				// die(debug($where));

				if(!empty($uploadID)){
					$affected_rows2 = $this->model_police_report->update_police_report_upload($uploadFile, $where);
				} else {
					$affected_rows2 = $this->model_general->insert('sv__police_report__upload', $uploadFile);
				}

			// die(debug($affected_rows));
			
			} else {
				'tidak berjaya';
			}
		}

		if(!empty($affected_rows) || !empty($affected_rows2))
		{
			$this->session->set_flashdata('success',"Successfully update police report. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update police report.");
		}

		redirect(base_url('hr/serviceform/policereport_list'));
	}

	function deletePoliceReportList()
	{
		$this->load->model('hr/model_police_report');

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

		$sets = array
		(
			'is_delete'		=> 1,
			'updatedBY'		=> $this->logged_user['id'],
			'updatedTS'	 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $policeReportID,
		);

		$affected_rows = $this->model_police_report->update_police_report($sets,$where);

		if($affected_rows)
		{
			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted police report list."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete police report list."
			));
		}
	}

	function approval_save()
	{
		$input 			= $this->input->post();
		$form_detail 	= $this->model_approval->get_form_detail($input['table_name'],$input['table_id']);
		$form_createdTS	= (isset($form_detail['created_ts']))?$form_detail['created_ts']:$form_detail['createdTS'];
		$form_creator 	= (isset($form_detail['created_by']))?$form_detail['created_by']:$form_detail['createdBY'];
		$form_requestor = (isset($form_detail['requester_id']))?$form_detail['requester_id']:(isset($form_detail['user_id'])?$form_detail['user_id']:(isset($form_detail['requestor_id'])?$form_detail['requestor_id']:$form_detail['borrower_id']));

		$form_detail = array();
		if(!empty($input['reason']))
		{
			$form_detail = array 
			(
				'status' 			=> $input['status'],
				'reason'			=> $input['reason'],
			);
		}else{
			$form_detail = array(); 
		}

		$user_email = array();
		// $user_email = array('hr@salihin.com.my');
		// $hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));
		// if($hr_detail) foreach($hr_detail as $hr_email) 
		// {
		// 	array_push($user_email, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
		// }

		if($form_creator == $form_requestor)
		{
			$form_creator_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$form_creator))[0];
			$form_creator_email 	= array_push($user_email, ($form_creator_detail['primary_email']) ? $form_creator_detail['primary_email'] : (($form_creator_detail['secondary_email']) ? $form_creator_detail['secondary_email'] : $form_creator_detail['email']));
		}else{
			// creator
			$form_creator_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$form_creator))[0];
			$form_creator_email 	= array_push($user_email, ($form_creator_detail['primary_email']) ? $form_creator_detail['primary_email'] : (($form_creator_detail['secondary_email']) ? $form_creator_detail['secondary_email'] : $form_creator_detail['email']));

			// requestor
			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$form_requestor))[0];
			$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
		}

		if($user_email)
		{
			$status 			= ($input['status'] == 'In_progress')?'In Progress':$input['status'];
			$emailSubject 		= $input['form_name'].' - ['.str_pad($input['table_id'],5,0,STR_PAD_LEFT).'] '.ucwords($status);
			$emailMessage 		= 'Your '.$input['form_name'].' [#'.str_pad($input['table_id'],5,0,STR_PAD_LEFT).'] created at <b>'.date('d-m-Y h:i:sA',strtotime($form_createdTS)).'</b> have been '.ucwords($status);
			$emailDetailForm	= $form_detail;

			$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
		}

		$addNew = $this->model_approval->updateOrCreateNew($input['table_name'],$input['table_id'],$input['status'],$this->session->userdata('user')['id'], $input['reason']);

		if($addNew)
		{
			if($input['table_name'] == 'sv__job_request')
			{
				$this->load->model('hr/model_job_request');
				$job_request_list = $this->model_job_request->getJobRequestList($input['table_id'])[0];

				$insert_mgs = array
				(
					'departmentID'	=> $job_request_list['department_id'],
					'customerID'	=> $job_request_list['client_id'],
					'yearEndDate'	=> $job_request_list['yearEndDate'],
					'description'	=> $job_request_list['description'],
					'remarks'		=> ($job_request_list['remarks'])?$job_request_list['remarks']:'',
					'deadline'		=> (strtotime($job_request_list['deadline']) > 0)?$job_request_list['deadline']:((isset($input['input_value']['deadline']))?$input['input_value']['deadline']:'0000-00-00'),
					'createdBY'		=> $this->logged_user['id'],
				);

				if($input['status'] == 'Approved') 
				{	
					$createJobMGS = $this->model_job_request->insertJobToMGS($insert_mgs);
					
					if(strtotime($job_request_list['deadline']) <= 0) 
					{
						$update_deadline = array
						(
							'deadline'		=> (isset($input['input_value']['deadline']))?$input['input_value']['deadline']:'0000-00-00',
							'updatedBY'		=> $this->logged_user['id'],
							'updatedTS'		=> date('Y-m-d H:i:s'),
						);

						$this->model_general->update('sv__job_request',$update_deadline,array('ID'=>$input['table_id']));
					}
				}
			}

			if($input['table_name'] == 'sv__client_new_resignation')
			{
				$this->load->model('hr/model_client_new_resignation');
				$request_list = $this->model_client_new_resignation->getClientNewResignationList($input['table_id'])[0];


				if($input['status'] == 'Approved') 
				{
					if($request_list['type'] == 1)
					{
						$insert_client = array
						(
							'type'			=> 1,
							'name'			=> $request_list['client_name'],
							'profile'		=> $request_list['nature_business'],
							'created_by'	=> $request_list['requester_id'],
						);

						$insertCustomer = $this->model_client_new_resignation->insertCustomerCRM('customer', $insert_client);

						$insert_client_director = array
						(
							'customer_id'	=> $insertCustomer,
							'name'			=> $request_list['director_name'],
							'director'		=> 1,
							'created_by'	=> $request_list['requester_id'],
						);

						$insertCustomer = $this->model_client_new_resignation->insertCustomerCRM('customer__contact', $insert_client_director);
					}
					if($request_list['type'] == 2)
					{
						$update_service = array
						(
							'service_status' 	=> 3,
							'updatedBY'			=> $request_list['requester_id'],
							'updatedTS'			=> date('Y-m-d H:i:s'),
						);

						$updateServiceStatus = $this->model_client_new_resignation->updateServiceStatus($update_service, $request_list['department_id'], $request_list['client_id']);
					}
				}
			}

			print json_encode(array(
				"status" 	=> "Success",
				"msg"	 	=> "Successfully update status request.",
				"redirect"	=> base_url('hr/serviceform/'.$input['link'])
				// "redirect"	=> base_url('hr/serviceform/'.$input['link'].'/'.$input['table_id'])
			)); 
		}
		else
		{
			print json_encode(array(
				"status" 	=> "Error",
				"msg"	 	=> "System failed to update status request.",
				"redirect"	=> base_url('hr/serviceform/'.$input['link'])
			));
		}
	}

	function approval_edit()
	{
		$input = $this->input->post();

		$set = array
		(
			'status' 		=> $input['status'],
			'reason' 		=> (!empty($input['reason']))?$input['reason']:'',
			'updated_by' 	=> $this->logged_user['id'],
		);

		$edit_status = $this->model_approval->update_sv_status($input['table_name'],$input['table_id'],$set,$input['status_id']);

		if($edit_status)
		{
			print json_encode(array(
				"status" 	=> "Success",
				"msg"	 	=> "Successfully edit status.",
				"redirect"	=> base_url('hr/serviceform/'.$input['link'])
				// "redirect"	=> base_url('hr/serviceform/'.$input['link'].'/'.$input['table_id'])
			)); 
		}
		else
		{
			print json_encode(array(
				"status" 	=> "Error",
				"msg"	 	=> "System failed to edit status.",
				"redirect"	=> base_url('hr/serviceform/'.$input['link'])
			));
		}
	}

	function it_system_list()
	{
		//$data['department'] = $this->model_company->getDepartments();
		//$data['customer']	= $this->model_crm->getCustomerActiveDormantOnly();

		$data = array
		(
			'cust'		 	=> $this->model_crm->getCustomerActiveDormantOnly(),
			'department'	=> $this->model_company->getDepartments(),
		);

		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl']=='admin' || $this->logged_user['division_id'] == 4){
			$data['rsSystem'] = $this->model_service_form->getSystemList();
		}else{
			$data['rsSystem'] = $this->model_service_form->getSystemList(null,$this->session->userdata('user')['id']);
		}
	
		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'IT System Support Request List');
		$this->template->view('hr/policyprocedure/form/it_system_list', $data);

		//$data['rsSystem'] = $this->model_service_form->getSystemSupport(); 
	}

	function it_system_form($ID=null)
	{
		//$data['ID'] = $ID;

		$data = array 
		(
			'ID'			=> $ID,
			'customer' 		=> $this->model_crm->getCustomerActiveDormantOnly(),
			'rsSystem' 		=> $this->model_service_form->getSystemListForm($ID), 
			'rsSystemList' 	=> $this->db->order_by('seq_no')->where('is_delete',0)->get('_ref__system_name')->result_array(),
			'systemDetails' => $this->model_service_form->getSystemDetails($ID),
			'discussions'	=> $this->model_service_form->getDiscussion($ID),
			'page_setup' 	=> $this->template->pageSetup('Online Form', '', 'IT System Support Request Form'),
		);

		if(!empty($ID)){	
			//$data['rsSystem'] = $this->model_service_form->getSystemListForm($ID);
			$data['row'] = (sizeof($data['rsSystem'])>0)?$data['rsSystem'][0]:null;
		}

		if(!empty($ID)){
            $data_approval['tblname'] = 'sv__system';
            $data_approval['ID'] = $ID;
            $data_approval['link'] = 'it_system_list';
            $data_approval['form_name'] = 'IT System Support Request';
            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__system','a.id_table'=>$ID));

            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
        }

		$this->template->view('hr/policyprocedure/form/it_system', $data);
	}

	function it_system_save()
	{
		$input = $this->input->post();
		//die(debug($input));

		$insertData = array(
			'user_id'    		=> $this->input->post('name_id'),
			'department_id' 	=> $this->input->post('department_id'),
			'cust_id'       	=> ($input['internal'] == 2)?$this->input->post('external_crm'):0,
			'location'    		=> $this->input->post('location'),
			'problem'     		=> $this->input->post('problem'),
			'complaint'     	=> $this->input->post('complaint'),
			'systemID'			=> $this->input->post('systemname'),
			'createdBY'     	=> $this->logged_user['id']
		);
		$newSystemRequest = $this->model_general->insert('sv__system', $insertData);

		//die(debug($insertData));

		$this->load->library('File_upload');

		$upload_directory = 'assets/upload/hr/Form/systemsupportform/';

		$upload_status = $this->file_upload
			->set_file_type(FILE_TYPE_UPLOAD)
			->set_directory_public()
			->set_upload_directory($upload_directory)
			->uploads('file_upload');

			// die(debug($upload_status));

		if(is_array($upload_status)) {
		$uploadPhoto = array
		(
			//'filename'         		=> (!empty($upload_status['file_name']))? $upload_status['file_name']:'',
			'filename'         		=> (($upload_status['file_name']))?$upload_status['file_name']:$input['file_upload'],
			'svID'     				=> $newSystemRequest, 
			// 'filename'       		=> (!empty($upload_status['file_location']))?$upload_status['file_location']:'',
			'file_location'     	=> (!empty($upload_status['file_name']))?$upload_directory:'', 
			'is_delete'         	=> 0,
		);
		//die(debug($uploadPhoto));

		$newSystemRequest2 = $this->model_general->insert('sv__system_attachment',$uploadPhoto);

		//die(debug($newSystemRequest2));
		
		} else {
			'Upload Failed. Please Try Again.';
		}

		if(!empty($newSystemRequest) || !empty($newSystemRequest2))
		{
			$this->model_approval->updateOrCreateNew('sv__system',$newSystemRequest,'Pending',0);

			$this->session->set_flashdata('success',"Successfully add new request for IT System Support. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new request for IT System Support. Please try again.");
		}

		redirect(base_url('hr/serviceform/it_system_list'));
	}

	function it_system_edit()
	{
		$input = $this->input->post();
	
		$itSystemID = $this->input->post('itSystemID');
		$fileID 	= $this->input->post('file_id');
	
		// die(debug($itServiceID));
	
		$sets = array
		(
			'user_id'    		=> $this->input->post('name_id'),
			'department_id' 	=> $this->input->post('department_id'),
			'cust_id'       	=> ($input['internal'] == 2)?$this->input->post('external_crm'):0,
			'location'    		=> $this->input->post('location'),
			'problem'     		=> $this->input->post('problem'),
			'complaint'     	=> $this->input->post('complaint'),
			'systemID'			=> $this->input->post('systemname'),
			'updatedBY'     	=> $this->logged_user['id'],
			'updatedTS'     	=> date('Y-m-d H:i:s'),
		);
	
		$where = array 
		(
			'ID' => $itSystemID,
		);  
		  
		$affected_rows = $this->model_service_form->update_system($sets,$where);

		if(!empty($_FILES['file_upload']['name']))
		{
			$this->load->library('File_upload');

			$upload_directory = 'assets/upload/hr/Form/systemsupportform/';
			

			$upload_status = $this->file_upload
				->set_file_type(FILE_TYPE_UPLOAD)
				->set_directory_public()
				->set_upload_directory($upload_directory)
				->uploads('file_upload');

				// die(debug($upload_status));

			if(is_array($upload_status)) {
				$uploadPhoto = array
				(
					//'filename'         		=> (!empty($upload_status['file_name']))? $upload_status['file_name']:'',
					'filename'         		=> (($upload_status['file_name']))?$upload_status['file_name']:$input['file_upload'],
					//'svID'     				=> $newSystemRequest, 
					// 'filename'       		=> (!empty($upload_status['file_location']))?$upload_status['file_location']:'',
					'file_location'     	=> (!empty($upload_status['file_name']))?$upload_directory:'', 
					'is_delete'         	=> 0,
				);

				if(empty($fileID))
				{
					$uploadPhoto['svID'] = $fileID;
				}

				$where = array
				(
					'ID' => $fileID,
				);

				// $affected_rows = $this->model_maintenance->update_picture($uploadPhoto, $where);

				// die(debug($where));
				if(!empty($fileID)){
					$affected_rows2 = $this->model_service_form->update_system($uploadPhoto, $where);
				} else {	
					$affected_rows2 = $this->model_general->insert('sv__system_attachment',$uploadPhoto);
				}
			// die(debug($affected_rows));
			
			} else {
				'Upload Error';
			}
		}

		if(!empty($affected_rows) || !empty($affected_rows2))
		{
			$this->session->set_flashdata('success',"Successfully update requested it system. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update requested it system.");
		}

		redirect(base_url('hr/serviceform/it_system_list'));
	}

	function it_system_save_attachment()
	{
		$ID = $this->input->post('form_id');


		if(!empty($_FILES['file_upload']['name']))
		{
			$this->load->library('File_upload');

			$upload_directory = 'assets/upload/hr/Form/systemsupportform/';
			

			$upload_status = $this->file_upload
				->set_file_type(FILE_TYPE_UPLOAD)
				->set_directory_public()
				->set_upload_directory($upload_directory)
				->uploads('file_upload');

				// die(debug($upload_status));

			if(is_array($upload_status)) {
				$uploadPhoto = array
				(
					//'filename'         		=> (!empty($upload_status['file_name']))? $upload_status['file_name']:'',
					'filename'         		=> (($upload_status['file_name']))?$upload_status['file_name']:'',
					'svID'     				=> $this->input->post('form_id'), 
					// 'filename'       		=> (!empty($upload_status['file_location']))?$upload_status['file_location']:'',
					'file_location'     	=> (!empty($upload_status['file_name']))?$upload_directory:'', 
					'is_delete'         	=> 0,
					'createdBy'				=> $this->logged_user['id']
				);

				$affected_rows2 = $this->model_general->insert('sv__system_attachment',$uploadPhoto);
				
			
			} else {
				'Upload Error';
			}
		}

		redirect(base_url('hr/serviceform/it_system/'.$ID));
	}

	function it_system_save_discussion()
	{
		$ID = $this->input->post('ID');

		//debug($ID);

		$insertData = array(
			'userID'				=> $this->session->userdata('user')['id'],
			'svID'     				=> $this->input->post('ID'), 
			'text'     				=> $this->input->post('message'), 
			'createdTS'   			=> date('Y-m-d H:i:s'),		
		);

		//$data['userID']		= $this->model_service_form->getSystemList(null,$this->session->userdata('user')['id']);
		//die(debug($insertData));
		
		$newDiscussion = $this->model_general->insert('sv__system_discussion', $insertData);
				
		if(!empty($newDiscussion))
		{
			$this->session->set_flashdata('success',"Successfully add new message.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new message.");
		}

		redirect(base_url('hr/serviceform/it_system/'.$ID));
	}

	function deleteSystemList()
	{
		$input    = $this->input->post();
		$itSystemID  = $this->input->post('itSystemID');

		$sets = array
		(
			'is_delete'   => 1,
			'updatedBY'   => $this->logged_user['id'],
			'updatedTS'   => date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $itSystemID,
		);

		$affected_rows = $this->model_service_form->update_system($sets,$where);

		if($affected_rows)
		{
			$this->model_approval->update_sv_status('sv__system',$itSystemID);

			print json_encode(array(
				"status" => "Success",
				"msg"  => "Successfully deleted request ."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"  => "System failed to delete request."
			));
		}
	}

	function deleteAttachments()
	{
		$input    = $this->input->post();
		$attachment  = $this->input->post('ID');

		$sets = array
		(
			'is_delete'   => 1,
			'createdBY'   => $this->logged_user['id'],
			'createdTS'   => date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $attachment,
		);

		$affected_rows = $this->model_service_form->update_attachment($sets,$where);

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

	function updateSystemList($mode = null)
	{
		$input 	= $this->input->post();

		if($mode == 'delete')
		{
			$system_id 		= $input['system_id'];
			$system_name	= $input['system_name'];

			$where = array('ID' => $system_id);

			$updateData = array('is_delete' => 1);

			$affected_rows = $this->model_general->update('_ref__system_name', $updateData, $where);

			if($affected_rows)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Successfully deleted ".$system_name." from system list."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to delete ".$system_name." from system list."
				));
			}
		}
		elseif($mode == 'add')
		{
		    $system_name 		= $input['system_name'];
		    $system_sequence 	= $input['system_sequence'];

		    $inserData = array
		    (
		    	'systemName'	=> $system_name,
		    	'seq_no'		=> $system_sequence,
		    );
			
			$affected_rows = $this->model_general->insert('_ref__system_name',$inserData);

			if($affected_rows)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Successfully added ".$system_name." to system list."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to added ".$system_name." to system list."
				));
			}
		}else{
			$system_id 			= $input['system_id'];
		    $system_name 		= $input['system_name'];
		    $system_sequence 	= $input['system_sequence'];

			$where = array('ID' => $system_id);

			$updateData = array
			(
				'systemName'	=> $system_name,
				'seq_no'		=> $system_sequence,
			);

			$affected_rows = $this->model_general->update('_ref__system_name', $updateData, $where);

			if($affected_rows)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Successfully update ".$system_name."."
				)); 
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to update ".$system_name."."
				));
			}
		}
	}

	function delivery_list()
	{
		$this->load->model('hr/model_delivery');

		$deliveryDetail	= $this->model_delivery->getDeliveryList();
        $year			= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');

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

		if(!empty($deliveryDetail))
		{
			foreach ($deliveryDetail as $key => $detail) 
			{
				$createdTS   				= date('Y-m-d',strtotime($detail['created_ts']));
				$start_date  				= $detail['date'];
				$end_date	 				= $detail['date'];
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['requester_dept'].'/'.$detail['requester_branch'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = 0;
				$tmpEvent['start']          = $start_date;
				$tmpEvent['end']			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title']          = $detail['requester_dept'].'/'.$detail['requester_branch'];
				$tmpEvent['description']    = $detail['requester_dept'].'/'.$detail['requester_branch'].' made a delivery request for "'.$detail['task'].'" purpose.';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',0.5)';
				$tmpEvent['textColor']		= '#ffffff';

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

		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		$data = array
		(
			'page_setup'  		=> $this->template->pageSetup('Online Form', '', 'Daily Delivery Request List'),
			'department'		=> $this->model_company->getDepartments(),
			'delivery_list' 	=> ($module_access['access_lvl'] == 'admin' || $this->logged_user['division_id'] == 4)?$this->model_delivery->getDeliveryList(null,null,$year):$this->model_delivery->getDeliveryList(null,$this->logged_user['id'],$year),
			'total_request'		=> $this->model_delivery->getRequestByCompany($year),
			'fc_res'            => json_encode($fc_res),
			'fc_event'          => json_encode($fc_event),
			'resource'          => json_encode($resource),
		);

		$this->template->view('hr/policyprocedure/form/delivery_list', $data);
	}

	function delivery_form($ID=null, $mode=null)
	{
		$this->load->model('hr/model_delivery');

		$deliveryDetail 	= $this->model_delivery->getDeliveryList();
		// debug($deliveryDetail);

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

		if(!empty($deliveryDetail))
		{
			foreach ($deliveryDetail as $key => $detail) 
			{
				$createdTS   				= date('Y-m-d',strtotime($detail['created_ts']));
				$start_date  				= $detail['date'];
				$end_date	 				= $detail['date'];
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['requester_dept'].'/'.$detail['requester_branch'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = $detail['requester_id'];
				$tmpEvent['start']          = $start_date;
				$tmpEvent['end']			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title']          = $detail['requester_dept'].'/'.$detail['requester_branch'];
				$tmpEvent['description']    = $detail['requester_dept'].'/'.$detail['requester_branch'].' made a delivery request for "'.$detail['task'].'" purpose.';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',0.5)';
				$tmpEvent['textColor']		= '#ffffff';

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

		$data = array
		(
			'page_setup'  		=> $this->template->pageSetup('Online Form', '', 'Daily Delivery Request Form'),
			'department'		=> $this->model_company->getDepartments(),
			'ID'				=> $ID,
			'mode'				=> $mode,
			'listName'			=> $this->model_user->getUsers2(),
			'delivery_detail'	=> $this->model_delivery->getDeliveryList($ID),
			'upcoming_request'	=> $this->model_delivery->getDeliveryByWeek(),
			'fc_res'            => json_encode($fc_res),
			'fc_event'          => json_encode($fc_event),
			'resource'          => json_encode($resource),
		);

		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl'] == 'admin' || $this->logged_user['division_id'] == 4){
			if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__delivery';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'delivery_list';
	            $data_approval['form_name'] = 'Delivery Request Form';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__delivery','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
	    }
		// debug($data['upcoming_request']);
		// die();

		$this->template->view('hr/policyprocedure/form/delivery', $data);	
	}

	function save_delivery_form()
	{
		$input 				= $this->input->post();
		// $requester_id 	= (isset($input['other_person_details']))?$input['other_person_details']:$input['reqNameID'];
		$requester_dept_id 	= (isset($input['other_person_details']))?$input['other_person_details']:$input['department_id'];
		$task 				= '';
		$detail_name 		= '';
		$detail_address 	= '';
		$detail_item 		= '';
		$detail_remark 		= '';
		$delivery_fee		= 0;

		if(isset($input['payment']) && $input['payment'] == 'on')
		{
			$task 			= 'payment';
		}elseif(isset($input['banking']) && $input['banking'] == 'on')
		{
			$task = 'banking';
			if(!empty($input['bank_pbb'])){ 
				$detail_name = 'pbb';
				$detail_remark = $input['bank_pbb']; 
			}elseif(!empty($input['bank_amislam'])){
				$detail_name = 'amislamic';
				$detail_remark = $input['bank_amislam'];
			}elseif(!empty($input['bank_bmbb'])){
				$detail_name = 'bmbb';
				$detail_remark = $input['bank_bmbb'];
			}elseif(!empty($input['bank_mbb'])){
				$detail_name = 'mbb';
				$detail_remark = $input['bank_mbb'];
			}elseif(!empty($input['bank_bimb'])){
				$detail_name = 'bimb';
				$detail_remark = $input['bank_bimb'];
			}else {
				$detail_name = ''; 
				$detail_remark = '';
			}

		}elseif(isset($input['delivery']) && $input['delivery'] == 'on')
		{
			$task 			= 'delivery';
			$detail_name 	= (!empty($input['delivery_name']))?$input['delivery_name']:''; 
			$detail_address = (!empty($input['delivery_address']))?$input['delivery_address']:'';
			$detail_item 	= (!empty($input['delivery_item']))?$input['delivery_item']:'';
			$detail_remark 	= (!empty($input['delivery_remarks']))?$input['delivery_remarks']:'';

		}elseif(isset($input['collection']) && $input['collection'] == 'on')
		{
			$task 			= 'collection';
			$detail_name 	= (!empty($input['collection_name']))?$input['collection_name']:''; 
			$detail_address = (!empty($input['collection_address']))?$input['collection_address']:'';
			$detail_item 	= (!empty($input['collection_item']))?$input['collection_item']:'';
			$detail_remark 	= (!empty($input['collection_remarks']))?$input['collection_remarks']:'';

		}elseif(isset($input['return']) && $input['return'] == 'on')
		{
			$task 			= 'return';
			$detail_name 	= (!empty($input['return_name']))?$input['return_name']:''; 
			$detail_address = (!empty($input['return_address']))?$input['return_address']:'';
			$detail_item 	= (!empty($input['return_item']))?$input['return_item']:'';
			$detail_remark 	= (!empty($input['return_remarks']))?$input['return_remarks']:'';

		}else 
		{
			$task = '';
			$detail_name = '';
			$detail_address = '';
			$detail_item = '';
			$detail_remark = '';
		}

		if(strtolower($task) == 'delivery')
		{
			if((preg_match('/\blhdn\b/', strtolower($detail_name)) || (preg_match('/\bssm\b/', strtolower($detail_name)))) == 1)
			{
				$delivery_fee += 30;
			}else{
				$delivery_fee += 5;
			}
		}else{
			$delivery_fee += 5;
		}

		$insert = array
		(
			'requester_id'	=> 0,
			'department_id'	=> $requester_dept_id,
			'date'			=> date('Y-m-d',strtotime($input['date'])),
			'task'			=> $task,
			'created_by'	=> $this->logged_user['id']
		);

		$newDelivery = $this->model_general->insert('sv__delivery', $insert);

		if(!empty($newDelivery))
		{
			$user_email 			= array();
			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$this->input->post('reqNameID')))[0];
			$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));

			$form_detail = array
			(
				'name' 					=> $this->input->post('reqName'),
				'email_address'			=> ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']),
				'department'			=> $this->input->post('department'),
				'date_request'  		=> $this->input->post('datereq'),
				'task_request' 			=> ucwords($task),
			);

			$admin_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 4'));
			if($admin_detail) foreach($admin_detail as $admin_email) 
			{
				// array_push($user_email, ($admin_email['primary_email']) ? $admin_email['primary_email'] : (($admin_email['secondary_email']) ? $admin_email['secondary_email'] : $admin_email['email']));
			}
			
			$form_requestor_name 	= $this->model_user->getUserDetail($this->input->post('reqNameID'))['name'];

			if($user_email)
			{
				$emailSubject 		= 'New Delivery Request - '.$form_requestor_name.' ['.str_pad($newDelivery,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $form_requestor_name.' has request delivery on '.$this->input->post('datereq').'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				// $emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$insert_detail = array
			(
				'delivery_id'		=> $newDelivery,
				'detail_name'		=> $detail_name,
				'detail_address'	=> $detail_address,
				'detail_item'		=> $detail_item,
				'detail_remark'		=> $detail_remark,
				'price'				=> $delivery_fee,
				'created_by'		=> $this->logged_user['id']
			);

			$newDeliveryDetail = $this->model_general->insert('sv__delivery_detail', $insert_detail);

			$this->model_approval->updateOrCreateNew('sv__delivery',$newDelivery,'Pending',0);
			
			$this->session->set_flashdata('success',"Successfully add new delivery request. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new delivery request. Please try again.");
		}

		redirect(base_url('hr/serviceform/delivery_list'));
	}

	function edit_delivery_form()
	{
		$input 				= $this->input->post();
		$delivery_id		= $input['delivery_id'];
		// $requester_id 	= (isset($input['other_person_details']))?$input['other_person_details']:((isset($input['other_person_details_input']))?$input['other_person_details_input']:$input['reqNameID']);
		$requester_dept_id 	= (isset($input['other_person_details']))?$input['other_person_details']:((isset($input['other_person_details_input']))?$input['other_person_details_input']:$input['department_id']);
		$task 				= '';
		$detail_name 		= '';
		$detail_address 	= '';
		$detail_item 		= '';
		$detail_remark 		= '';
		$delivery_fee		= 0;

		if(isset($input['payment']) && $input['payment'] == 'on')
		{
			$task = 'payment';
		}elseif(isset($input['banking']) && $input['banking'] == 'on')
		{
			$task = 'banking';
			if(!empty($input['bank_pbb'])){ 
				$detail_name = 'pbb';
				$detail_remark = $input['bank_pbb']; 
			}elseif(!empty($input['bank_amislam'])){
				$detail_name = 'amislamic';
				$detail_remark = $input['bank_amislam'];
			}elseif(!empty($input['bank_bmbb'])){
				$detail_name = 'bmbb';
				$detail_remark = $input['bank_bmbb'];
			}elseif(!empty($input['bank_mbb'])){
				$detail_name = 'mbb';
				$detail_remark = $input['bank_mbb'];
			}elseif(!empty($input['bank_bimb'])){
				$detail_name = 'bimb';
				$detail_remark = $input['bank_bimb'];
			}else {
				$detail_name = ''; 
				$detail_remark = '';
			}

		}elseif(isset($input['delivery']) && $input['delivery'] == 'on')
		{
			$task 			= 'delivery';
			$detail_name 	= (!empty($input['delivery_name']))?$input['delivery_name']:''; 
			$detail_address = (!empty($input['delivery_address']))?$input['delivery_address']:'';
			$detail_item 	= (!empty($input['delivery_item']))?$input['delivery_item']:'';
			$detail_remark 	= (!empty($input['delivery_remarks']))?$input['delivery_remarks']:'';

		}elseif(isset($input['collection']) && $input['collection'] == 'on')
		{
			$task 			= 'collection';
			$detail_name 	= (!empty($input['collection_name']))?$input['collection_name']:''; 
			$detail_address = (!empty($input['collection_address']))?$input['collection_address']:'';
			$detail_item 	= (!empty($input['collection_item']))?$input['collection_item']:'';
			$detail_remark 	= (!empty($input['collection_remarks']))?$input['collection_remarks']:'';

		}elseif(isset($input['return']) && $input['return'] == 'on')
		{
			$task 			= 'return';
			$detail_name 	= (!empty($input['return_name']))?$input['return_name']:''; 
			$detail_address = (!empty($input['return_address']))?$input['return_address']:'';
			$detail_item 	= (!empty($input['return_item']))?$input['return_item']:'';
			$detail_remark 	= (!empty($input['return_remarks']))?$input['return_remarks']:'';

		}else 
		{
			$task = '';
			$detail_name = '';
			$detail_address = '';
			$detail_item = '';
			$detail_remark = '';
		}

		if(strtolower($task) == 'delivery')
		{
			if((preg_match('/\blhdn\b/', strtolower($detail_name)) || (preg_match('/\bssm\b/', strtolower($detail_name)))) == 1)
			{
				$delivery_fee += 30;
			}else{
				$delivery_fee += 5;
			}
		}else{
			$delivery_fee += 5;
		}

		$update = array
		(
			'requester_id'	=> 0,
			'department_id'	=> $requester_dept_id,
			'date'			=> date('Y-m-d',strtotime($input['date'])),
			'task'			=> $task,
			'updated_by'	=> $this->logged_user['id'],
			'updated_ts'	=> date('Y-m-d H:i:s')
		);

		$updateDelivery = $this->model_general->update('sv__delivery', $update, array('ID' => $delivery_id));

		if(!empty($updateDelivery))
		{
			$update_detail = array
			(
				'detail_name'		=> $detail_name,
				'detail_address'	=> $detail_address,
				'detail_item'		=> $detail_item,
				'detail_remark'		=> $detail_remark,
				'price'				=> $delivery_fee,
				'updated_by'		=> $this->logged_user['id'],
				'updated_ts'		=> date('Y-m-d H:i:s')
			);

			$newDeliveryDetail = $this->model_general->update('sv__delivery_detail', $update_detail, array('delivery_id' => $delivery_id));
			
			$this->session->set_flashdata('success',"Successfully update delivery request. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update delivery request. Please try again.");
		}

		redirect(base_url('hr/serviceform/delivery_list'));
	}

	function deleteDeliveryList()
	{
		$input 		= $this->input->post();
		$deliveryID = $input['deliveryID'];

		$sets = array
		(
			'is_delete'  	=> 1,
			'updated_by'   	=> $this->logged_user['id'],
			'updated_ts' 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $deliveryID,
		);

		$affected_rows = $this->model_general->update('sv__delivery',$sets,$where);

		if($affected_rows)
		{
			$this->model_general->update('sv__delivery_detail',$sets,array('delivery_id' => $deliveryID));
			$this->model_approval->update_sv_status('sv__delivery',$deliveryID);

			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted delivery request."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete delivery request."
			));
		}
	}

	function qr_code_list()
	{
		$this->load->model('hr/model_qr_code');

		$qrCodeRequestDetail 	= $this->model_qr_code->getQRCodeList();
        $year	   	= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');

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

		if(!empty($qrCodeRequestDetail))
		{
			foreach ($qrCodeRequestDetail as $key => $detail) 
			{
				$createdTS   				= date('Y-m-d',strtotime($detail['created_ts']));
				$start_date  				= $detail['date'];
				$end_date	 				= $detail['date'];
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['dept_name'].'/'.$detail['branchName'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = $detail['requester_id'];
				$tmpEvent['start']          = $start_date;
				$tmpEvent['end']			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title']          = $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']    = $detail['requestor'].' request QR Code for "'.$detail['title'].'".';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',0.5)';
				$tmpEvent['textColor']		= '#ffffff';

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

		$data = array
		(
			'page_setup'  		=> $this->template->pageSetup('Online Form', '', 'QR Code CPD Request List'),
			'department'		=> $this->model_company->getDepartments(),
			'qr_code_list' 		=> ($_SESSION['module_data']['role']=='admin')?$this->model_qr_code->getQRCodeList(null,null,$year):$this->model_qr_code->getQRCodeList(null,$this->logged_user['id'],$year),
			'total_request'		=> $this->model_qr_code->getRequestByDepartment($year),
			'fc_res'            => json_encode($fc_res),
			'fc_event'          => json_encode($fc_event),
			'resource'          => json_encode($resource),
		);

		$this->template->view('hr/policyprocedure/form/qr_code_list', $data);
	}

	function qr_code_form($ID=null, $mode=null)
	{
		$this->load->model('hr/model_qr_code');
		$this->load->model('training/model_category');
		$this->load->model('training/model_organizer');

		$qrCodeRequestDetail 	= $this->model_qr_code->getQRCodeList();

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

		if(!empty($qrCodeRequestDetail))
		{
			foreach ($qrCodeRequestDetail as $key => $detail) 
			{
				$createdTS   				= date('Y-m-d',strtotime($detail['created_ts']));
				$start_date  				= $detail['date'];
				$end_date	 				= $detail['date'];
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['dept_name'].'/'.$detail['branchName'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = $detail['requester_id'];
				$tmpEvent['start']          = $start_date;
				$tmpEvent['end']			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title']          = $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']    = $detail['requestor'].' request QR Code for "'.$detail['title'].'".';
				$tmpEvent['color']			= 'rgba('.rand(0,255).','.rand(0,255).','.rand(100,255).',0.5)';
				$tmpEvent['textColor']		= '#ffffff';

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

		$data = array
		(
			'page_setup'  		=> $this->template->pageSetup('Online Form', '', 'QR Code CPD Request Form'),
			'department'		=> $this->model_company->getDepartments(),
			'ID'				=> $ID,
			'mode'				=> $mode,
			// 'listName'			=> $this->model_user->getUsers2(),
			'qr_code_detail'	=> $this->model_qr_code->getQRCodeList($ID),
			'upcoming_request'	=> $this->model_qr_code->getQRCodeByWeek(),
			'category'			=> $this->model_category->getCategories(),
			'organizer'			=> $this->model_organizer->getOrganizer(),
			'fc_res'            => json_encode($fc_res),
			'fc_event'          => json_encode($fc_event),
			'resource'          => json_encode($resource),
		);

		// debug($data['qr_code_detail']);
		// die();

		if($this->logged_module['role'] == 'admin')
		{
			if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__qr_code';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'qr_code_list';
	            $data_approval['form_name'] = 'QR Code CPD Form';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__qr_code','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
		}
		// debug($data['upcoming_request']);
		// die();

		$this->template->view('hr/policyprocedure/form/qr_code', $data);	
	}

	function save_qr_code_form()
	{
		$this->load->model('hr/model_qr_code');

		$input 			= $this->input->post();
		$category 		= $input['category'];

		$internal 		= (isset($input['internal']))?$input['internal']:$input['external'];
		$structured 	= (isset($input['structured']))?$input['structured']:$input['unstructured'];
		$technical 		= (isset($input['technical']))?$input['technical']:$input['nontechnical'];
		$cpd_type_id	= $internal.''.$structured.''.$technical;

		$insert = array
		(
			'requester_id' 	=> $input['reqNameID'],
			'department_id' => $input['department_id'],
			'date' 			=> date('Y-m-d',strtotime($input['date'])),
			'start_time' 	=> date('H:i:s',strtotime($input['start_time'])),
			'end_time' 		=> date('H:i:s',strtotime($input['end_time'])),
			'cpd_type_id' 	=> $cpd_type_id,
			'organizer_id' 	=> $input['organizer'],
			'title' 		=> $input['title'],
			'topic' 		=> $input['topic'],
			'pax' 			=> $input['pax'],
			'cpd_hour' 		=> $input['hour'],
			'cost' 			=> $input['cost'],
			'created_by' 	=> $this->logged_user['id'],
		);

		$newQRCode = $this->model_general->insert('sv__qr_code', $insert);

		if(!empty($newQRCode))
		{
			$addCategoryid = $this->model_qr_code->updateOrCreateNew($newQRCode,$category);

			$form_detail = array 
			(
				'name' 				=> $input['reqName'],
				'email_address'		=> $input['email'],
				'department'		=> $input['department'],
				'date_request'		=> $input['datereq'],
				'event_date'		=> $input['date'],
				'event_time'		=> $input['start_time'].' - '.$input['end_time'],
				'event_title'		=> $input['title'],
				'cpd_hour'			=> $input['hour'],
			);
			
			$user_email = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));
			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($user_email, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}
			
			$send_copy_form_email 	= (isset($input['send_email_checkbox']) && $input['send_email_checkbox'] == 'on')?$input['send_email_checkbox']:'off';	
			if($send_copy_form_email == 'on')
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['reqNameID']))[0];
				$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			}

			if($user_email)
			{
				$emailSubject 		= 'New QR Code CPD Request - '.$input['reqName'].' ['.str_pad($newQRCode,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $input['reqName'].' has request QR Code CPD on '.$input['datereq'].'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->model_approval->updateOrCreateNew('sv__qr_code',$newQRCode,'Pending',0);

			$this->session->set_flashdata('success',"Successfully add new request for qr code cpd. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new request for qr code cpd. Please try again.");
		}

		redirect(base_url('hr/serviceform/qr_code_list'));
	}

	function edit_qr_code_form()
	{
		$this->load->model('hr/model_qr_code');

		$input 			= $this->input->post();
		$category 		= $input['category'];

		$internal 		= (isset($input['internal']))?$input['internal']:$input['external'];
		$structured 	= (isset($input['structured']))?$input['structured']:$input['unstructured'];
		$technical 		= (isset($input['technical']))?$input['technical']:$input['nontechnical'];
		$cpd_type_id	= $internal.''.$structured.''.$technical;

		$update = array
		(
			'date' 			=> date('Y-m-d',strtotime($input['date'])),
			'start_time' 	=> date('H:i:s',strtotime($input['start_time'])),
			'end_time' 		=> date('H:i:s',strtotime($input['end_time'])),
			'cpd_type_id' 	=> $cpd_type_id,
			'organizer_id' 	=> $input['organizer'],
			'title' 		=> $input['title'],
			'topic' 		=> $input['topic'],
			'pax' 			=> $input['pax'],
			'cpd_hour' 		=> $input['hour'],
			'cost' 			=> $input['cost'],
			'updated_by' 	=> $this->logged_user['id'],
			'updated_ts' 	=> date('Y-m-d H:i:s'),
		);

		$where = array('ID' => $input['qr_code_id']);

		$updateQRCode = $this->model_qr_code->update_qr_code($update, $where);

		if(!empty($updateQRCode))
		{
			$addCategoryid = $this->model_qr_code->updateOrCreateNew($input['qr_code_id'],$category);

			$this->session->set_flashdata('success',"Successfully update qr code cpd request. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update qr code cpd request. Please try again.");
		}

		redirect(base_url('hr/serviceform/qr_code_list'));
	}

	function deleteQRCodeList()
	{
		$input 		= $this->input->post();
		$qr_codeID 	= $input['qr_codeID'];

		$sets = array
		(
			'is_delete'  	=> 1,
			'updated_by'   	=> $this->logged_user['id'],
			'updated_ts' 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $qr_codeID,
		);

		$affected_rows = $this->model_general->update('sv__qr_code',$sets,$where);

		if($affected_rows)
		{
			$this->model_general->update('sv__qr_code_organizer',$sets,array('qr_code_id' => $qr_codeID));
			$this->model_approval->update_sv_status('sv__qr_code',$qr_codeID);

			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted qr code cpd request list."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete qr code cpd request list."
			));
		}
	}

	function change_date_format()
	{
		$input 	= $this->input->post();
		$date 	= (isset($input['checkin_date']))?date('Y-m-d',strtotime($input['checkin_date'])):date('Y-m-d');
		$time 	= (isset($input['checkin_time']))?date('H:i:s',strtotime($input['checkin_time'])):date('H:i:s');

		if($date)
        {
          	print json_encode(array(
                "status" 		=> "success",
                "date_time"		=> $date.' '.$time,
            ));

        }
        else
        {
        	print json_encode(array(
                "status"		=> "failed",
                "date_time"		=> $date.' '.$time,
            ));
        }
	}

	function invoice_list()
	{
		$this->load->model('hr/model_invoice');

		$finance_staff 	= $this->model_user->getUsersByFilter(array('d.id'=>$this->logged_user['id'],'d.division_id'=>8));
		$entity_filter 	= array('a.id' => array('11','6'));
		$year 			= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');
		
		$data = array
		(
			'page_setup'  		=> $this->template->pageSetup('Online Form', '', 'Invoice Request List'),
			'finance_staff'		=> $finance_staff,
			'invoice_list'		=> ($this->logged_user['division_id'] == 8)?$this->model_invoice->getInvoiceList(null,null,null,null,$year):(($this->logged_user['grade'] >= 31)?$this->model_invoice->getInvoiceList(null,null,$this->logged_user['department_id'],$this->logged_user['id'],$year):$this->model_invoice->getInvoiceList(null,$this->logged_user['id'],null,null,$year)),
			'business_entity'	=> $this->model_company->getBusinesses(null,null,$entity_filter),
			'department'		=> $this->model_company->getDepartments(),
			'branch'			=> $this->model_company->getBranches(),
			'requester'			=> ($finance_staff)?$this->model_invoice->getInvoicePerson('requester'):$this->model_invoice->getInvoicePerson('requester',$this->logged_user['department_id']),
			'approver'			=> ($finance_staff)?$this->model_invoice->getInvoicePerson('approver'):$this->model_invoice->getInvoicePerson('approver',$this->logged_user['department_id']),
			'preparer'			=> ($finance_staff)?$this->model_invoice->getInvoicePerson('preparer'):$this->model_invoice->getInvoicePerson('preparer',$this->logged_user['department_id']),
		);

		if($data['business_entity']) foreach($data['business_entity'] as $key => $be)
		{
			if($be['id'] == 3) $data['business_entity'][$key]['name'] = 'Al Jafree Salihin Kuzaimi PLT';
			if($be['id'] == 7) $data['business_entity'][$key]['name'] = 'MYSA Business Management Sdn Bhd';
			if($be['id'] == 2) $data['business_entity'][$key]['name'] = 'Salihin';
			if($be['id'] == 13) $data['business_entity'][$key]['name'] = 'SALIHIN IT Curation Sdn Bhd';
		}

		$this->template->view('hr/policyprocedure/form/invoice_list', $data);
	}

	function invoice_form($entity_id, $ID=null, $mode=null)
	{
		$this->load->model('staff_directory/model_user_list');
		$this->load->model('hr/model_invoice');
		$business_entity_detail = $this->model_company->getBusinesses('',$entity_id);

		if($business_entity_detail['id'] == 3) $business_entity_detail['name'] = 'Al Jafree Salihin Kuzaimi PLT';
		if($business_entity_detail['id'] == 7) $business_entity_detail['name'] = 'MYSA Business Management Sdn Bhd';
		if($business_entity_detail['id'] == 2) $business_entity_detail['name'] = 'Salihin';
		if($business_entity_detail['id'] == 13) $business_entity_detail['name'] = 'SALIHIN IT Curation Sdn Bhd';

		$data = array
		(
			'page_setup'  				=> $this->template->pageSetup('Online Form', '', 'Invoice Request Form - '.$business_entity_detail['name'].' ('.$business_entity_detail['roc_no'].')'),
			'form_title'				=> $business_entity_detail['name'].' ('.$business_entity_detail['roc_no'].')',
			'business_entity_detail'	=> $business_entity_detail,
			'department'				=> $this->model_company->getDepartments(),
			'ID'						=> $ID,
			'mode'						=> $mode,
			'invoice_list'				=> $this->model_invoice->getInvoiceList($ID)[0],
			'client'					=> $this->model_crm->getCustomerDetail(),
			'country'					=> $this->model_crm->getCountry(),
			'state'						=> $this->model_general->fetchAll('_ref__state'),
			'entity_id'					=> $entity_id,
			'branch'					=> $this->model_company->getBranches(),
			'partner'					=> $this->model_user_list->getUsers(null,null,null,null,array(6,7,8)),
			'description'				=> $this->model_invoice->getInvoiceDescription($entity_id),
			'finance_division'			=> $this->model_user->getUsersByFilter(array('a.id' => $this->logged_user['id'],'d.division_id' => 8))[0],
			'mgs_job'					=> $this->model_invoice->getMgsJobByPIC($this->logged_user['id']),
			'count_description'			=> $this->model_invoice->countDescriptionDetail($entity_id, $ID),
		);

		$data['approver']		= ($data['invoice_list']['department_id'] > 0)?$this->model_invoice->getInvoicePerson('approver',$data['invoice_list']['department_id']):$this->model_invoice->getInvoicePerson('approver',$this->logged_user['department_id']);
		
		$data['dept_manager'] 	= $this->model_user->getUsersByFilter(array('d.id'=>$this->logged_user['id'],'d.department_id'=>$data['invoice_list']['department_id'],'d.employee_grade >='=>31));
		// debug($data['description']);
		// debug($data['forms']);
		// die();

		$this->template->view('hr/policyprocedure/form/invoice', $data);
	}

	function create_invoice()
	{
		$input = $this->input->post();
		
		$insert = array
		(
			'requester_id'			=> $this->logged_user['id'],
			'department_id'			=> $this->logged_user['department_id'],
			'business_entity_id'	=> $input['entity_id'],
			'createdBY'				=> $this->logged_user['id'],
		);

		$newInvoice = $this->model_general->insert('sv__invoice',$insert);

		if($newInvoice)
        {
          	print json_encode(array(
                "status" 	=> "success",
                "msg"		=> "Success.",
                "redirect"	=> base_url("hr/serviceform/invoice_form/".$input['entity_id'].'/'.$newInvoice),
            ));

        }
        else
        {
        	print json_encode(array(
                "status"	=> "failed",
                "msg"		=> "Please select business entity. Thank you.",
                "redirect"	=> base_url("hr/serviceform/invoice_list"),
            ));
        }
	}

	function invoice_save()
	{
		$this->load->model('hr/model_invoice');

		$input 				= $this->input->post();
		$description_id 	= array();
		$description_detail = array();
		$description_amount = array();

		$insert = array
		(
			'requester_id'			=> $input['request_name_id'],
			'department_id'			=> $input['request_dept_id'],
			'business_entity_id'	=> $input['entityID'],
			'job_id'				=> ($input['job_id'] > 0)?$input['job_id']:0,
			'po_no'					=> $input['client_po_no'],
			'client_id'				=> $input['client_id'],
			'client_contact'		=> $input['client_tel_no'],
			'client_fax'			=> $input['client_fax_no'],
			'client_email'			=> $input['client_email'],
			'client_address'		=> $input['client_address'],
			'attention_to'			=> $input['client_attention_to'],
			'branch_id'				=> (isset($input['branch_id']))?$input['branch_id']:'',
			'sign_partner_id'		=> (isset($input['signing_partner']))?$input['signing_partner']:'',
			'total'					=> str_replace(',','',$input['total_invoice']),
			'createdBY'				=> $this->logged_user['id'],
		);

		$newInvoice = $this->model_general->insert('sv__invoice',$insert);

		foreach($input as $key => $row)
		{
			$input_explode = explode("__",$key);
			
			if($input_explode[0] == 'desc_detail')
			{
				array_push($description_id,array($input_explode[1])[0]);
				array_push($description_detail,array($input['desc_detail__'.$input_explode[1]])[0]);
				array_push($description_amount,array(str_replace(',', '', $input['desc_amount__'.$input_explode[1]]))[0]);
			}
		}

		$this->model_invoice->updateOrCreateNew($newInvoice, $description_id, $description_detail, $description_amount);
		
		if(isset($input['desc_check_sst']) && strtolower($input['desc_check_sst']) == 'on')
		{
			$insert_sst = array
			(
				'invoice_id'		=> $newInvoice,
				'description_id'	=> 111,
				'remark'			=> 'sst',
				'amount'			=> $input['desc_amount__sst'],
				'createdBY'			=> $this->logged_user['id'],
			);
			
			$newInvoiceSst = $this->model_general->insert('sv__invoice_description',$insert_sst);
		}


		if(!empty($newInvoice))
		{
			$client	= $this->model_crm->getCustomerDetail(array('a.id' => $input['client_id']))[0];
			$invoice_item_detail = array();
			foreach($description_detail as $key => $val)
			{
				array_push($invoice_item_detail, $val.' - <b>RM'.number_format($description_amount[$key],2).'</b>');
			}

			$form_detail = array 
			(
				'name' 				=> $input['request_name'],
				'email_address'		=> $input['request_email'],
				'department'		=> $input['request_dept'],
				'date_request'		=> $input['datereq'],
				'client'			=> $client->name,
				'detail'			=> $invoice_item_detail,
			);

			$user_email = array();
			$send_copy_form_email 	= (isset($input['send_email_checkbox']) && $input['send_email_checkbox'] == 'on')?$input['send_email_checkbox']:'off';	
			if($send_copy_form_email == 'on')
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['request_name_id']))[0];
				$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			}
			
			if($user_email)
			{
				$emailSubject 		= 'New Invoice Request - '.$input['request_name'].' ['.str_pad($newInvoice,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $input['request_name'].' has request invoice on '.$input['datereq'].'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;
				
				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->session->set_flashdata('success',"Successfully add new request for invoice. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new request for invoice. Please try again.");
		}

		redirect(base_url('hr/serviceform/invoice_list'));
	}

	function invoice_edit_bak($mode = null)
	{
		$this->load->model('hr/model_invoice');

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

		if($mode == null)
		{
			$description_id 	= array();
			$description_detail = array();
			$description_amount = array();

			$update = array
			(
				'job_id'				=> ($input['job_id'] > 0)?$input['job_id']:0,
				'po_no'					=> $input['client_po_no'],
				'client_id'				=> $input['client_id'],
				'client_contact'		=> $input['client_tel_no'],
				'client_fax'			=> $input['client_fax_no'],
				'client_email'			=> $input['client_email'],
				'client_address'		=> $input['client_address'],
				'attention_to'			=> $input['client_attention_to'],
				'branch_id'				=> (isset($input['branch_id']))?$input['branch_id']:'',
				'sign_partner_id'		=> (isset($input['signing_partner']))?$input['signing_partner']:'',
				'total'					=> str_replace(',','',$input['total_invoice']),
				'updatedBY'				=> $this->logged_user['id'],
				'updatedTS'    			=> date('Y-m-d H:i:s'),
			);

			$where = array
			(
				'ID' => $input['invoiceID']
			);

			$updateInvoice = $this->model_general->update('sv__invoice',$update, $where);

			foreach($input as $key => $row)
			{
				$input_explode = explode("__",$key);
				
				if($input_explode[0] == 'desc_detail')
				{
					array_push($description_id,array($input_explode[1])[0]);
					array_push($description_detail,array($input['desc_detail__'.$input_explode[1]])[0]);
					array_push($description_amount,array(str_replace(',', '', $input['desc_amount__'.$input_explode[1]]))[0]);
				}
			}

			$this->model_invoice->updateOrCreateNew($input['invoiceID'], $description_id, $description_detail, $description_amount);
			
			if(isset($input['desc_check_sst']) && strtolower($input['desc_check_sst']) == 'on')
			{
				$update_sst = array
				(
					'is_delete'			=> 0,
					'amount'			=> $input['desc_amount__sst'],
					'updatedBY'			=> $this->logged_user['id'],
					'updatedTS'    		=> date('Y-m-d H:i:s'),
				);
				
				$where_sst = array
				(
					'invoice_id'		=> $input['invoiceID'],
					'description_id'	=> '"'.'sst'.'"',
				);
				
				$newInvoiceSst = $this->model_general->update('sv__invoice_description',$update_sst,$where_sst);
			}
		}else{
			$update = array
			(
				'job_id'				=> ($input['job_id'] > 0)?$input['job_id']:0,
				'updatedBY'				=> $this->logged_user['id'],
				'updatedTS'    			=> date('Y-m-d H:i:s'),
			);

			$where = array
			(
				'ID' => $input['invoiceID']
			);
			
			$updateInvoice = $this->model_general->update('sv__invoice',$update, $where);
		}

		if(!empty($updateInvoice))
		{
			$this->session->set_flashdata('success',"Successfully update request for invoice. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update request for invoice. Please try again.");
		}

		redirect(base_url('hr/serviceform/invoice_list'));
	}

	function invoice_edit($mode = null)
	{
		$this->load->model('hr/model_invoice');
		$input = $this->input->post();

		if($mode == null)
		{
			$update = array
			(
				'job_id'				=> ($input['job_id'] > 0)?$input['job_id']:0,
				'po_no'					=> $input['client_po_no'],
				'client_id'				=> $input['client_id'],
				'client_contact'		=> $input['client_tel_no'],
				'client_fax'			=> $input['client_fax_no'],
				'client_email'			=> $input['client_email'],
				'client_address'		=> $input['client_address'],
				'attention_to'			=> $input['client_attention_to'],
				'branch_id'				=> (isset($input['branch_id']))?$input['branch_id']:'',
				'sign_partner_id'		=> (isset($input['signing_partner']))?$input['signing_partner']:'',
				'total'					=> str_replace(',','',$input['total_invoice']),
				'updatedBY'				=> $this->logged_user['id'],
				'updatedTS'    			=> date('Y-m-d H:i:s'),
			);

			$where = array
			(
				'ID' => $input['invoiceID']
			);

			$updateInvoice = $this->model_general->update('sv__invoice',$update, $where);
			
			$check_existing_sst = $this->model_general->fetchSingle('sv__invoice_description', array('*'), array('description_id' => 111, 'is_delete' => 0, 'invoice_id' => $input['invoiceID']));
			if($check_existing_sst)
			{
				$update_sst = array
				(
					'updatedBY'			=> $this->logged_user['id'],
					'updatedTS'    		=> date('Y-m-d H:i:s'),
				);

				$where_sst = array
				(
					'invoice_id'		=> $input['invoiceID'],
					'description_id'	=> 111,
				);
				
				if(isset($input['sst_amount']) && ($input['sst_amount']) > 0 && ($input['sst_amount'] != 'N/A'))
				{
					$update_sst['is_delete'] = 0;
					$update_sst['amount'] = $input['sst_amount'];
				}else{
					$update_sst['is_delete'] = 1;
				}

				$updateInvoiceSst = $this->model_general->update('sv__invoice_description',$update_sst,$where_sst);
			}else{
				if(isset($input['sst_amount']) && ($input['sst_amount']) > 0 && ($input['sst_amount'] != 'N/A'))
				{
					$insert_sst = array
					(
						'invoice_id'		=> $input['invoiceID'],
						'description_id'	=> 111,
						'remark'			=> 'sst',
						'is_delete'			=> 0,
						'amount'			=> $input['sst_amount'],
						'createdBY'			=> $this->logged_user['id'],
						'createdTS'    		=> date('Y-m-d H:i:s'),
					);

					$newInvoiceSst = $this->model_general->insert('sv__invoice_description',$insert_sst);
				}
			}

			$manager_email = $this->model_form->sv__filter('user a',array('a.id, a.name, a.email, b.employee_grade'),array(),array(array('user__employment_detail b','b.id = a.id','')),array('b.employee_grade' => 'desc'),array(),array(),array(),array(),array('a.id' => $input['mgr_approval']));

			$insertManagerApproval = $this->model_invoice->updateOrCreateNewMgrApproved($input['invoiceID'], $input['mgr_approval']);
		}

		if(!empty($updateInvoice))
		{
			$client	= $this->model_crm->getCustomerDetail(array('a.id' => $input['client_id']))[0];
			$description_detail = $this->model_general->fetchAll('sv__invoice_description a', array('ifnull(b.description, a.description_id) as description, a.amount, a.year_end, a.remark'), array('a.is_delete' => 0, 'a.invoice_id' => $input['invoiceID']), array(array('sv__ref_invoice_description b','b.id = a.description_id','left')));
			
			$invoice_item_detail = array();

			foreach($description_detail as $key => $val)
			{
				array_push($invoice_item_detail, $val['description'].' - <b>RM'.number_format($val['amount'],2).'</b>');
			}

			$form_detail = array 
			(
				'name' 				=> $input['request_name'],
				'email_address'		=> $input['request_email'],
				'department'		=> $input['request_dept'],
				'date_request'		=> $input['datereq'],
				'client'			=> $client->name,
				'detail'			=> $invoice_item_detail,
			);

			$user_email = array();
			
			// if($manager_email) foreach($manager_email as $mgr_email) array_push($user_email, $mgr_email['email']);

			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['request_name_id']))[0];
			$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			
			if($user_email)
			{
				$emailSubject 		= 'New Invoice Request - '.$input['request_name'].' ['.str_pad($newInvoice,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $input['request_name'].' has request invoice on '.$input['datereq'].'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;
				
				if($mode == 'first') $emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->session->set_flashdata('success',"Successfully update request for invoice. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update request for invoice. Please try again.");
		}

		redirect(base_url('hr/serviceform/invoice_list'));
	}

	function invoice_get_client_detail()
	{
		$this->load->model('hr/model_invoice');
		$job_id 			= ($this->input->post('job_id'))?$this->input->post('job_id'):0;
		$client_id 			= ($this->input->post('client_id'))?$this->input->post('client_id'):0;
		$client_contact 	= ($this->input->post('client_contact'))?$this->input->post('client_contact'):0;

		$job_detail 		= $this->model_invoice->getJobDetail($job_id);
		$client_detail 		= $this->model_crm->getCustomerDetailByID(($client_id > 0)?$client_id:$job_detail[0]['customerID']);
		$client_contact_no 	= $this->model_invoice->getClientContact(($client_detail['id'])?$client_detail['id']:$job_detail[0]['customerID'], $client_contact);
		$client_address		= $this->model_invoice->getClientAddress(($client_detail['id'])?$client_detail['id']:$job_detail[0]['customerID'], $client_contact);
		$query 				= $this->db->last_query();
		
		if($client_detail)
        {
          	print json_encode(array(
                "status" 			=> "success",
                "job_detail"		=> $job_detail,
                "client_detail"		=> $client_detail,
                "client_contact_no"	=> $client_contact_no,
                // "query"				=> $query,
                "job_id"			=> $job_id,
                "client_id"			=> $client_id,
                "client_contact"	=> $client_contact,
                "client_address"	=> $client_address,
            ));

        }
        else
        {
        	print json_encode(array(
                "status"			=> "failed",
                "job_detail"		=> $job_detail,
                "client_detail"		=> $client_detail,
                "client_contact_no"	=> $client_contact_no,
                "client_address"	=> $client_address,
            ));
        }
	}

	function invoice_save_client_phone()
	{
		$this->load->model('hr/model_invoice');
		$input = $this->input->post();

		$insert = array(
			'customer_id'	=> $input['client_id'],
			'name'			=> $input['rep_name'],
			'phone_mobile'	=> $input['phone_mobile'],
			'fax'			=> $input['fax'],
			'email'			=> $input['email'],
			'created_by'	=> $this->logged_user['id']
		);

		$new_client_phone = $this->model_general->insert('customer__contact', $insert);
		
		$client_contact_no 	= $this->model_invoice->getClientContact($input['client_id']);

		if($new_client_phone)
        {
			$client	= $this->model_crm->getCustomerDetail(array('a.id' => $input['client_id']))[0];
			
			$change_detail = array();

			array_push($change_detail, 'Name - <b>'.$input['rep_name'].'</b>');
			array_push($change_detail, 'Contact Number - <b>'.$input['phone_mobile'].'</b>');
			array_push($change_detail, ($input['fax'])?'Fax - <b>'.$fax.'</b>':'Fax - <b>N/A</b>');
			array_push($change_detail, 'Email - <b>'.$input['email'].'</b>');

			$form_detail = array 
			(
				'name' 				=> $this->logged_user['name'],
				'email_address'		=> $this->logged_user['email'],
				'department'		=> $this->logged_user['department_name'].' ['.$this->logged_user['branch_name'].']',
				'date_change'		=> date('d-m-Y H:i:s'),
				'item_change'		=> "Client Contact Information",
				'client'			=> $client->name,
				'detail'			=> $change_detail,
			);

			$user_email = array(); // to notify crm
			// $user_email = array('hazwani@salihin.com.my'); // to notify crm

			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$this->logged_user['id']))[0];
			$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			
			if($user_email)
			{
				$emailSubject 		= 'New Client Contact Information - '.strtoupper($client->name);
				$emailMessage 		= $this->logged_user['name'].' has add new client contact information on '.date('d-m-Y').'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;
				
				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->session->set_flashdata('success',"Successfully update request for invoice. Thank you.");

          	print json_encode(array(
                "status" 			=> "success",
                "msg"				=> "Successfully add client phone number.",
                "client_contact_no"	=> $client_contact_no,
            ));

        }
        else
        {
        	print json_encode(array(
                "status"			=> "failed",
                "msg"				=> "Failed to add client phone number. Please try again.",
                "client_contact_no"	=> $client_contact_no,
            ));
        }
	}

	function invoice_approved($mode)
	{
		$input 		= $this->input->post();
		$update 	= array();
		$user_email = array();

		if($mode == 'manager')
		{
			$temp = array
			(
				'approval_status'	=> $input['approveBtn'],
				'approval_remark'	=> $input['approval_remark'],
				'approvedBY'		=> $input['approve_name_id'],
				'approvedTS'		=> date('Y-m-d H:i:s',strtotime($input['dateapprv']))
			);

			array_push($update, $temp);

			if($input['approveBtn'] == 1) $status = 'Approved';
			elseif($input['approveBtn'] == 2) $status = 'Rejected';
			else $status = '';

			if($input['approveBtn'] == 1)
			{
				array_push($user_email,'finance@salihin.com.my');
				$finance_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 8'));
				if($finance_detail) foreach($finance_detail as $finance_email) 
				{
					array_push($user_email, ($finance_email['primary_email']) ? $finance_email['primary_email'] : (($finance_email['secondary_email']) ? $finance_email['secondary_email'] : $finance_email['email']));
				}
			}
		}else{
			$temp = array
			(
				'prepared_status'	=> $input['financeCompleteBtn'],
				'preparedBY'		=> $input['finance_name_id'],
				'inv_form_no'		=> $input['finance_inv_no'],
				'preparedTS'		=> date('Y-m-d H:i:s',strtotime($input['finance_date']))
			);

			array_push($update, $temp);

			if($input['financeCompleteBtn'] == 1) $status = 'Completed';
			elseif($input['financeCompleteBtn'] == 2) $status = 'Duplicate';
			else $status = '';
		}

		$where['ID'] = $input['invoiceID'];

		$update_status 			= $this->model_general->update('sv__invoice',$update[0],$where);

		// for manager_approval
		$update_manager_status 	= $this->model_general->update('sv__invoice_manager_approval',$update[0],array('is_delete'=>0,'invoice_id'=>$input['invoiceID'], 'manager_id'=>$input['approve_name_id']));

		if($update_status)
		{
			$form 			= $this->model_approval->get_form_detail('sv__invoice',$input['invoiceID']);
			$form_createdTS	= (isset($form['createdTS']))?$form['createdTS']:0;
			$form_creator 	= (isset($form['createdBY']))?$form['createdBY']:0;
			$form_requestor = (isset($form['requester_id']))?$form['requester_id']:0;
			$form_requestor_name = (isset($form['requester_id']))?$this->db->select('name')->where('id',$form['requester_id'])->get('user')->result_array()[0]['name']:'';

			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$form_creator))[0];
			$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));

			if($user_email)
			{
				$emailSubject 		= 'Invoice Request - ['.str_pad($input['invoiceID'],5,0,STR_PAD_LEFT).'] '.ucwords($status);
				$emailMessage 		= 'Invoice request [#'.str_pad($input['invoiceID'],5,0,STR_PAD_LEFT).'] created by <b>'.ucfirst($form_requestor_name).'</b> at <b>'.date('d-m-Y h:i:sA',strtotime($form_createdTS)).'</b> have been '.ucwords($status).'.';
				$emailDetailForm	= array();

				// $emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->session->set_flashdata('success',"Successfully update status invoice. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update status invoice. Please try again.");
		}

		redirect('hr/serviceform/invoice_list');
	}

	function deleteInvoiceList()
	{
		$input 		= $this->input->post();
		$invoiceID 	= $input['invoiceID'];

		$sets = array
		(
			'is_delete'  	=> 1,
			'updatedBY'   	=> $this->logged_user['id'],
			'updatedTS' 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $invoiceID,
		);

		$affected_rows = $this->model_general->update('sv__invoice',$sets,$where);

		if($affected_rows)
		{
			$this->model_general->update('sv__invoice_description',$sets,array('invoice_id' => $invoiceID));

			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted invoice from list."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete invoice from list."
			));
		}
	}

	function invoice_description($entity_id = null)
	{
		$this->load->model('hr/model_invoice');
		if($entity_id)
		{
			$business_entity_detail = $this->model_company->getBusinesses('',$entity_id);
			$data = array
			(
				'page_setup'  	=> $this->template->pageSetup('Online Form', '', 'Invoice Description - '.$business_entity_detail['name'].' ('.$business_entity_detail['roc_no'].')'),
				'description'	=> $this->model_invoice->getInvoiceDescription($entity_id),
				'entity'		=> $this->model_company->getBusinesses(),
				'entity_id'		=> $entity_id,
			);
		}else{
			$data = array
			(
				'page_setup'  	=> $this->template->pageSetup('Online Form', '', 'Invoice Description'),
				'entity'		=> $this->model_company->getBusinesses(),
				'entity_id'		=> $entity_id,
			);
		}

		$this->template->view('hr/policyprocedure/form/invoice_description', $data);
	}

	function saveDescription($mode)
	{
		$input = $this->input->post();

		if(strtolower($mode) == 'add')
		{
			unset($input['id']);
			$input['createdBY'] = $this->logged_user['id'];
			
			$query = $this->model_general->insert('sv__ref_invoice_description', $input);
		}else{
			$input['updatedBY'] = $this->logged_user['id'];
			$input['updatedTS'] = date('Y-m-d H:i:s');
			
			$where = array
			(
				'ID' 		=> $input['id'],
				'entity_id' => $input['entity_id'],
			);
			unset($input['id']);
			unset($input['entity_id']);

			$query = $this->model_general->update('sv__ref_invoice_description', $input, $where);
		}

		if($query)
        {
          	print json_encode(array(
                "status" 		=> "success",
                "msg"			=> "Successfully ".$mode." description.",
            ));

        }
        else
        {
        	print json_encode(array(
                "status"		=> "failed",
                "msg"			=> "Failed to ".$mode." description.",
            ));
        }
	}

	function deleteDescriptionList()
	{
		$input 		= $this->input->post();
		$descriptionID 	= $input['descriptionID'];

		$sets = array
		(
			'is_delete'  	=> 1,
			'updatedBY'   	=> $this->logged_user['id'],
			'updatedTS' 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $descriptionID,
		);

		$affected_rows = $this->model_general->update('sv__ref_invoice_description',$sets,$where);

		if($affected_rows)
		{
			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted description from list."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete description from list."
			));
		}
	}
	
	function invoice_save_client_info($entity_id = 0, $invoiceID = 0, $save_mode = null)
	{
		$input 			= $this->input->post();
		$mode 			= ucwords(implode(" ", explode('_',$input['mode'])));
		$result 		= '';
		$result2 		= '';

		if($save_mode)
		{
			if($save_mode == 'update') // edit & delete
			{
				$where = array
				(
					'ID' 		=> $input['input_value']['ID'],
				);
				
				if(($input['mode'] == 'update_invoice_detail') || ($input['mode'] == 'update_invoice_disbursement') || ($input['mode'] == 'delete_invoice_detail') || ($input['mode'] == 'delete_invoice_disbursement'))
				{
					$result .= $this->model_general->fetchAll('sv__invoice_description', null, $where)[0]['amount'];
				}
				
				unset($input['input_value']['ID']);

				$query = $this->model_general->update($input['table_name'], $input['input_value'], $where);
			}
		}else{ // insert
			$query = $this->model_general->insert($input['table_name'],$input['input_value']);
		}

		if($input['mode'] == 'client_address') 
		{
			$getData = $this->model_crm->getAddressByID($query);
			$result .= $getData['address1']." ".$getData['address2']."\n, ".$getData['postcode']." ".$getData['city']."\n, ".$getData['state'].", ".$getData['country'];

			$client	= $this->model_crm->getCustomerDetail(array('a.id' => $input['input_value']['customer_id']))[0];

			$form_detail = array 
			(
				'name' 				=> $this->logged_user['name'],
				'email_address'		=> $this->logged_user['email'],
				'department'		=> $this->logged_user['department_name'].' ['.$this->logged_user['branch_name'].']',
				'date_change'		=> date('d-m-Y H:i:s'),
				'item_change'		=> "Client Address Information",
				'client'			=> $client->name,
				'detail'			=> 'Address - <b>'.ucwords($result).'</b>',
			);

			$user_email = array(); // to notify crm
			// $user_email = array('hazwani@salihin.com.my'); // to notify crm

			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$this->logged_user['id']))[0];
			$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			
			if($user_email)
			{
				$emailSubject 		= 'New Client Address Information - '.strtoupper($client->name);
				$emailMessage 		= $this->logged_user['name'].' has add new client address information on '.date('d-m-Y').'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;
				
				if($query) $emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}
		}

		if($input['mode'] == 'new_invoice_detail' || $input['mode'] == 'new_invoice_disbursement' || $input['mode'] == 'update_invoice_detail' || $input['mode'] == 'update_invoice_disbursement' || $input['mode'] == 'delete_invoice_detail' || $input['mode'] == 'delete_invoice_disbursement'){
			$this->load->model('model_invoice');
			$result2 .= json_encode($this->model_invoice->countDescriptionDetail($entity_id, $invoiceID));
		}

		if($query)
        {
          	print json_encode(array(
                "status" 	=> "success",
                "msg"		=> ((explode('_',$input['mode'])[0]) == 'new')?"Successfully insert ".$mode.".":"Successfully ".$mode.".",
                "result"	=> $result,
                "result2"	=> $result2,
                "data"		=> $query,
            ));

        }
        else
        {
        	print json_encode(array(
                "status"	=> "failed",
                "msg"		=> ((explode('_',$input['mode'])[0]) == 'new')?"Failed to insert ".$mode.".":"Failed to ".$mode.".",
                "result"	=> $result,
                "result2"	=> $result2,
                "data"		=> $query,
            ));
        }
	}

	function credit_note_list()
	{
		$this->load->model('hr/model_credit_note');

		$finance_staff  = $this->model_user->getUsersByFilter(array('d.id'=>$this->logged_user['id'],'d.division_id'=>8));
		$year			= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');
		
		$data = array
		(
			'page_setup'  		=> $this->template->pageSetup('Online Form', '', 'Credit Note Request List'),
			'finance_staff'		=> $finance_staff,
			'business_entity'	=> $this->model_company->getBusinesses(),
			'department'		=> $this->model_company->getDepartments(),
			'branch'			=> $this->model_company->getBranches(),
			'requester'			=> ($finance_staff)?$this->model_credit_note->getCreditNotePerson('requester'):$this->model_credit_note->getCreditNotePerson('requester',$this->logged_user['department_id']),
			'approver'			=> ($finance_staff)?$this->model_credit_note->getCreditNotePerson('approver'):$this->model_credit_note->getCreditNotePerson('approver',$this->logged_user['department_id']),
			'preparer'			=> ($finance_staff)?$this->model_credit_note->getCreditNotePerson('preparer'):$this->model_credit_note->getCreditNotePerson('preparer',$this->logged_user['department_id']),
			'credit_note_list'	=> ($finance_staff || $this->logged_user['department_id'] == 1)?$this->model_credit_note->getCreditNoteList(null,null,null,$year):(($this->logged_user['grade'] >= 31)?$this->model_credit_note->getCreditNoteList(null,null,$this->logged_user['department_id'],$year):$this->model_credit_note->getCreditNoteList(null,$this->logged_user['id'],null,$year)),
		);

		$this->template->view('hr/policyprocedure/form/credit_note_list', $data);
	}

	function credit_note_form($entity_id, $ID=null, $mode=null)
	{
		$this->load->model('hr/model_credit_note');
		$business_entity_detail = $this->model_company->getBusinesses('',$entity_id);

		$data = array
		(
			'page_setup'  				=> $this->template->pageSetup('Online Form', '', 'Credit Note Request Form - '.$business_entity_detail['name'].' ('.$business_entity_detail['roc_no'].')'),
			'form_title'				=> $business_entity_detail['name'].' ('.$business_entity_detail['roc_no'].')',
			'business_entity_detail'	=> $business_entity_detail,
			'department'				=> $this->model_company->getDepartments(),
			'ID'						=> $ID,
			'mode'						=> $mode,
			'credit_note_list'			=> $this->model_credit_note->getCreditNoteList($ID)[0],
			'client'					=> $this->model_crm->getCustomerDetail(),
			'entity_id'					=> $entity_id,
			'branch'					=> $this->model_company->getBranches(),
			'description'				=> $this->model_credit_note->getCreditNoteDescription($entity_id),
			'finance_division'			=> $this->model_user->getUsersByFilter(array('a.id' => $this->logged_user['id'],'d.division_id' => 8))[0],
			'mgs_job'					=> $this->model_credit_note->getMgsJobByPIC($this->logged_user['id']),
		);

		$this->template->view('hr/policyprocedure/form/credit_note', $data);
	}

	function credit_note_get_invoice()
	{
		$this->load->model('hr/model_credit_note');
		$input = $this->input->post();

		$invoice_list 	= $this->model_credit_note->getInvoiceDetail($input['job_id'],$input['entity_id']);
		$client_detail 		= $this->model_crm->getCustomerDetailByID(($invoice_list)?$invoice_list[0]['client_id']:0);
		if($invoice_list)
        {
          	print json_encode(array(
                "status" 			=> "success",
                "invoice_list"		=> $invoice_list,
                "client_detail"		=> $client_detail,
            ));

        }
        else
        {
        	print json_encode(array(
                "status"			=> "failed",
                "invoice_list"		=> $invoice_list,
                "client_detail"		=> $client_detail,
            ));
        }
	}

	function credit_note_save()
	{
		$this->load->model('hr/model_credit_note');

		$input 				= $this->input->post();
		$description_id 	= array();
		$description_detail = array();
		$description_amount = array();

		$insert = array
		(
			'requester_id'			=> $input['request_name_id'],
			'department_id'			=> $input['request_dept_id'],
			'business_entity_id'	=> $input['entityID'],
			'job_id'				=> ($input['job_id'] > 0)?$input['job_id']:0,
			'invoice_id'			=> $input['inv_form_no'],
			'client_id'				=> $input['client_id'],
			'client_contact'		=> $input['client_tel_no'],
			'client_pic'			=> $input['client_pic'],
			'client_email'			=> $input['client_email'],
			'branch_id'				=> (isset($input['branch_id']) && $input['branch_id'] > 0)?$input['branch_id']:'',
			'total'					=> str_replace(',','',$input['total_credit_note']),
			'createdBY'				=> $this->logged_user['id'],
		);

		$newCreditNote = $this->model_general->insert('sv__credit_note',$insert);
		// $newCreditNote = 1;

		foreach($input as $key => $row)
		{
			$input_explode = explode("__",$key);
			
			if($input_explode[0] == 'desc_detail')
			{
				array_push($description_id,array($input_explode[1])[0]);
				array_push($description_detail,array($input['desc_detail__'.$input_explode[1]])[0]);
				array_push($description_amount,array(str_replace(',','',$input['desc_amount__'.$input_explode[1]]))[0]);
			}
		}

		$this->model_credit_note->updateOrCreateNew($newCreditNote, $description_id, $description_detail, $description_amount);
		
		if(isset($input['desc_check_sst']) && strtolower($input['desc_check_sst']) == 'on')
		{
			$insert_sst = array
			(
				'credit_note_id'	=> $newCreditNote,
				'description_id'	=> 'sst',
				'amount'			=> $input['desc_amount__sst'],
				'createdBY'			=> $this->logged_user['id'],
			);
			
			$newCreditNoteSst = $this->model_general->insert('sv__credit_note_description',$insert_sst);
		}


		if(!empty($newCreditNote))
		{
			$invoice_list 	= $this->model_credit_note->getInvoiceDetail(null, null, $input['inv_form_no'])[0];
			$client			= $this->model_crm->getCustomerDetail(array('a.id' => $input['client_id']))[0];
			$cn_item_detail = array();
			if($invoice_list) array_push($cn_item_detail, 'Invoice Number - <b>'.$invoice_list['inv_form_no'].'</b>');
			foreach($description_detail as $key => $val)
			{
				array_push($cn_item_detail, $val.' - <b>RM'.$description_amount[$key].'</b>');
			}

			$form_detail = array 
			(
				'name' 				=> $input['request_name'],
				'email_address'		=> $input['request_email'],
				'department'		=> $input['request_dept'],
				'date_request'		=> $input['datereq'],
				'client'			=> $client->name,
				'detail'			=> $cn_item_detail,
			);
			
			$user_email = array();
			$send_copy_form_email 	= (isset($input['send_email_checkbox']) && $input['send_email_checkbox'] == 'on')?$input['send_email_checkbox']:'off';	
			if($send_copy_form_email == 'on')
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['request_name_id']))[0];
				$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			}
			
			if($user_email)
			{
				$emailSubject 		= 'New Credit Note Request - '.$input['request_name'].' ['.str_pad($newCreditNote,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $input['request_name'].' has request credit note on '.$input['datereq'].'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;
				
				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->session->set_flashdata('success',"Successfully add new request for credit note. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new request for credit note. Please try again.");
		}

		redirect(base_url('hr/serviceform/credit_note_list'));
	}

	function credit_note_edit()
	{
		$this->load->model('hr/model_credit_note');

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

		$description_id 	= array();
		$description_detail = array();
		$description_amount = array();

		$update = array
		(
			'job_id'				=> ($input['job_id'] > 0)?$input['job_id']:0,
			'invoice_id'			=> $input['inv_form_no'],
			'client_id'				=> $input['client_id'],
			'client_contact'		=> $input['client_tel_no'],
			'client_email'			=> $input['client_email'],
			'client_pic'			=> $input['client_pic'],
			'branch_id'				=> (isset($input['branch_id']))?$input['branch_id']:'',
			'total'					=> str_replace(',','',$input['total_credit_note']),
			'updatedBY'				=> $this->logged_user['id'],
			'updatedTS'    			=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $input['creditNoteID']
		);

		$updateInvoice = $this->model_general->update('sv__credit_note',$update, $where);

		foreach($input as $key => $row)
		{
			$input_explode = explode("__",$key);
			
			if($input_explode[0] == 'desc_detail')
			{
				array_push($description_id,array($input_explode[1])[0]);
				array_push($description_detail,array($input['desc_detail__'.$input_explode[1]])[0]);
				array_push($description_amount,array(str_replace(',','',$input['desc_amount__'.$input_explode[1]]))[0]);
			}
		}

		$this->model_credit_note->updateOrCreateNew($input['creditNoteID'], $description_id, $description_detail, $description_amount);
		
		if(isset($input['desc_check_sst']) && strtolower($input['desc_check_sst']) == 'on')
		{
			$update_sst = array
			(
				'is_delete'			=> 0,
				'amount'			=> $input['desc_amount__sst'],
				'updatedBY'			=> $this->logged_user['id'],
				'updatedTS'    		=> date('Y-m-d H:i:s'),
			);
			
			$where_sst = array
			(
				'credit_note_id'	=> $input['creditNoteID'],
				'description_id'	=> '"'.'sst'.'"',
			);
			
			$newInvoiceSst = $this->model_general->update('sv__credit_note_description',$update_sst,$where_sst);
		}

		if(!empty($updateInvoice))
		{
			$this->session->set_flashdata('success',"Successfully update request for credit note. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update request for credit note. Please try again.");
		}

		redirect(base_url('hr/serviceform/credit_note_list'));
	}

	function credit_note_approved($mode)
	{
		$input = $this->input->post();
		$update = array();
		$user_email = array();

		if($mode == 'manager')
		{
			$temp = array
			(
				'approval_status'	=> $input['approveBtn'],
				'approvedBY'		=> $input['approve_name_id'],
				'approvedTS'		=> date('Y-m-d H:i:s',strtotime($input['dateapprv']))
			);

			array_push($update, $temp);


			if($input['approveBtn'] == 1) $status = 'Approved';
			elseif($input['approveBtn'] == 2) $status = 'Rejected';
			else $status = '';

			array_push($user_email,'finance@salihin.com.my');
			$finance_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 8'));
			if($finance_detail) foreach($finance_detail as $finance_email) 
			{
				array_push($user_email, ($finance_email['primary_email']) ? $finance_email['primary_email'] : (($finance_email['secondary_email']) ? $finance_email['secondary_email'] : $finance_email['email']));
			}

		}else{
			$temp = array
			(
				'prepared_status'	=> $input['financeCompleteBtn'],
				'preparedBY'		=> $input['finance_name_id'],
				'cn_form_no'		=> $input['finance_inv_no'],
				'preparedTS'		=> date('Y-m-d H:i:s',strtotime($input['finance_date']))
			);

			array_push($update, $temp);

			if($input['financeCompleteBtn'] == 1) $status = 'Completed';
			elseif($input['financeCompleteBtn'] == 2) $status = 'Duplicate';
			else $status = '';
		}

		$where = array('ID' => $input['creditNoteID']);

		$update_status = $this->model_general->update('sv__credit_note',$update[0],$where);
		
		if($update_status)
		{
			$form 			= $this->model_approval->get_form_detail('sv__credit_note',$input['creditNoteID']);
			$form_createdTS	= (isset($form['createdTS']))?$form['createdTS']:0;
			$form_creator 	= (isset($form['createdBY']))?$form['createdBY']:0;
			$form_requestor = (isset($form['requester_id']))?$form['requester_id']:0;
			$form_requestor_name = (isset($form['requester_id']))?$this->db->select('name')->where('id',$form['requester_id'])->get('user')->result_array()[0]['name']:'';

			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$form_creator))[0];
			$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));

			if($user_email)
			{
				$emailSubject 		= 'Credit Note Request - ['.str_pad($input['creditNoteID'],5,0,STR_PAD_LEFT).'] '.ucwords($status);
				// $emailMessage 		= 'Your Credit Note request [#'.str_pad($input['creditNoteID'],5,0,STR_PAD_LEFT).'] created at <b>'.date('d-m-Y h:i:sA',strtotime($form_createdTS)).'</b> have been '.ucwords($status).'.';
				$emailMessage 		= 'Credit Note request [#'.str_pad($input['creditNoteID'],5,0,STR_PAD_LEFT).'] created by <b>'.ucfirst($form_requestor_name).'</b> at <b>'.date('d-m-Y h:i:sA',strtotime($form_createdTS)).'</b> have been '.ucwords($status).'.';
				$emailDetailForm	= array();

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->session->set_flashdata('success',"Successfully update status credit note. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update status credit note. Please try again.");
		}

		redirect('hr/serviceform/credit_note_list');
	}

	function deleteCreditNoteList()
	{
		$input 			= $this->input->post();
		$creditNoteID 	= $input['creditNoteID'];

		$sets = array
		(
			'is_delete'  	=> 1,
			'updatedBY'   	=> $this->logged_user['id'],
			'updatedTS' 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $creditNoteID,
		);

		$affected_rows = $this->model_general->update('sv__credit_note',$sets,$where);

		if($affected_rows)
		{
			$this->model_general->update('sv__credit_note_description',$sets,array('credit_note_id' => $creditNoteID));

			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted credit note from list."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete credit note from list."
			));
		}
	}

	function credit_note_description($entity_id = null)
	{
		$this->load->model('hr/model_credit_note');
		if($entity_id)
		{
			$business_entity_detail = $this->model_company->getBusinesses('',$entity_id);
			$data = array
			(
				'page_setup'  	=> $this->template->pageSetup('Online Form', '', 'Credit Note Description - '.$business_entity_detail['name'].' ('.$business_entity_detail['roc_no'].')'),
				'description'	=> $this->model_credit_note->getCreditNoteDescription($entity_id),
				'entity'		=> $this->model_company->getBusinesses(),
				'entity_id'		=> $entity_id,
			);
		}else{
			$data = array
			(
				'page_setup'  	=> $this->template->pageSetup('Online Form', '', 'Credit Note Description'),
				'entity'		=> $this->model_company->getBusinesses(),
				'entity_id'		=> $entity_id,
			);
		}

		$this->template->view('hr/policyprocedure/form/credit_note_description', $data);
	}

	function saveCreditNoteDescription($mode)
	{
		$input = $this->input->post();

		if(strtolower($mode) == 'add')
		{
			unset($input['id']);
			$input['createdBY'] = $this->logged_user['id'];
			
			$query = $this->model_general->insert('sv__ref_credit_note_description', $input);
		}else{
			$input['updatedBY'] = $this->logged_user['id'];
			$input['updatedTS'] = date('Y-m-d H:i:s');
			
			$where = array
			(
				'ID' 		=> $input['id'],
				'entity_id' => $input['entity_id'],
			);
			unset($input['id']);
			unset($input['entity_id']);

			$query = $this->model_general->update('sv__ref_credit_note_description', $input, $where);
		}

		if($query)
        {
          	print json_encode(array(
                "status" 		=> "success",
                "msg"			=> "Successfully ".$mode." description.",
            ));

        }
        else
        {
        	print json_encode(array(
                "status"		=> "failed",
                "msg"			=> "Failed to ".$mode." description.",
            ));
        }
	}

	function deleteCreditNoteDescriptionList()
	{
		$input 			= $this->input->post();
		$descriptionID 	= $input['descriptionID'];

		$sets = array
		(
			'is_delete'  	=> 1,
			'updatedBY'   	=> $this->logged_user['id'],
			'updatedTS' 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $descriptionID,
		);

		$affected_rows = $this->model_general->update('sv__ref_credit_note_description',$sets,$where);

		if($affected_rows)
		{
			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted description from list."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete description from list."
			));
		}
	}

	function petty_cash_advance_list()
	{
		$this->load->model('hr/model_petty_cash_advance');

		$finance_staff = $this->model_user->getUsersByFilter(array('d.id'=>$this->logged_user['id'],'d.division_id'=>8));
		$year			= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');
		
		$data = array
		(
			'page_setup'  			=> $this->template->pageSetup('Online Form', '', 'Petty Cash / Advance Request List'),
			'finance_staff'			=> $finance_staff,
			'petty_advance_list'	=> ($finance_staff || $this->logged_user['division_id'] == 10)?$this->model_petty_cash_advance->getPettyCashAdvanceList(null,null,null,$year):(($this->logged_user['grade'] >= 31)?$this->model_petty_cash_advance->getPettyCashAdvanceList(null,null,$this->logged_user['department_id'],$year):$this->model_petty_cash_advance->getPettyCashAdvanceList(null,$this->logged_user['id'],null,$year)),
			'business_entity'		=> $this->model_company->getBusinesses(),
			'department'			=> $this->model_company->getDepartments(),
			'branch'				=> $this->model_company->getBranches(),
			'requester'				=> ($finance_staff)?$this->model_petty_cash_advance->getPettyCashAdvancePerson('requester'):$this->model_petty_cash_advance->getPettyCashAdvancePerson('requester',$this->logged_user['department_id']),
			'approver'				=> ($finance_staff)?$this->model_petty_cash_advance->getPettyCashAdvancePerson('approver'):$this->model_petty_cash_advance->getPettyCashAdvancePerson('approver',$this->logged_user['department_id']),
			'preparer'				=> ($finance_staff)?$this->model_petty_cash_advance->getPettyCashAdvancePerson('preparer'):$this->model_petty_cash_advance->getPettyCashAdvancePerson('preparer',$this->logged_user['department_id']),
		);

		$this->template->view('hr/policyprocedure/form/petty_cash_advance_list', $data);
	}

	function petty_cash_advance_form($ID=null, $mode=null)
	{
		$this->load->model('admin/model_user');
		$this->load->model('hr/model_petty_cash_advance');

		$data = array
		(
			'page_setup'  				=> $this->template->pageSetup('Online Form', '', 'Petty Cash / Advance Request Form'),
			'listName'					=> $this->model_user->getUsers2(),
			'business_entity'			=> $this->model_company->getBusinesses(),
			'department'				=> $this->model_company->getDepartments(),
			'ID'						=> $ID,
			'mode'						=> $mode,
			'petty_advance_list'		=> $this->model_petty_cash_advance->getPettyCashAdvanceList($ID)[0],
			'client'					=> $this->model_crm->getCustomerDetail(),
			'branch'					=> $this->model_company->getBranches(),
			'description'				=> $this->model_petty_cash_advance->getPettyCashAdvanceDescription(),
			'finance_division'			=> $this->model_user->getUsersByFilter(array('a.id' => $this->logged_user['id'],'d.division_id' => 8))[0],
			'mgs_job'					=> $this->model_petty_cash_advance->getMgsJobByPIC($this->logged_user['id']),
		);


		if($mode == 'cash_advance_listing')
		{
			$data['page_setup']			= $this->template->pageSetup('Online Form', '', 'Cash Advance Listing Form');
			$data['petty_advance_list'] = $this->model_petty_cash_advance->getCashAdvanceListing($ID)[0];

			$this->template->view('hr/policyprocedure/form/petty_cash_advance_listing', $data);
		}else{
			$this->template->view('hr/policyprocedure/form/petty_cash_advance', $data);
		}
	}

	function petty_cash_advance_get_client()
	{
		$this->load->model('hr/model_petty_cash_advance');
		$input = $this->input->post();

		$job_detail 	= $this->model_petty_cash_advance->getJobDetail($input['job_id']);
		
		if($job_detail)
        {
          	print json_encode(array(
                "status" 			=> "success",
                "job_detail"		=> $job_detail,
            ));

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

	function petty_cash_advance_save()
	{
		$this->load->model('hr/model_petty_cash_advance');

		$input 						= $this->input->post();
		$input['member_email'] 		= array();
		$input['department_hod'] 	= array();

		$member_dept_id		= (isset($input['member_id']))?$this->model_petty_cash_advance->getMemberDeptID($input['member_id']):'';
		if($input['request_type'] == 0) $request_mode = 'Petty Cash';
        elseif($input['request_type'] == 1) $request_mode = 'Cash Advance';
        elseif($input['request_type'] == 2) $request_mode = 'Reimbursement';
        elseif($input['request_type'] == 3) $request_mode = 'Perks';
        else $request_mode = '';

		$description_id 	= array();
		$description_detail = array();
		$description_amount = array();

		$insert = array
		(
			'requester_id'			=> $input['request_name_id'],
			'department_id'			=> $input['request_dept_id'],
			'business_entity_id'	=> $input['entity_id'],
			'job_id'				=> ($input['job_id'] > 0)?$input['job_id']:0,
			'request_type'			=> $input['request_type'],
			'client_id'				=> $input['client_id'],
			'travel_date_from'		=> date('Y-m-d',strtotime($input['date_from'])),
			'travel_date_to'		=> date('Y-m-d',strtotime($input['date_to'])),
			'total'					=> str_replace(',','',$input['total_petty_cash_advance']),
			'createdBY'				=> $this->logged_user['id'],
		);

		$hods = $this->model_company->getDepartmentHOD(null,array('a.id' => $input['request_dept_id']));	

		if($hods) foreach($hods as $hod)
		{
			array_push($input['department_hod'], ($hod['primary_email']) ? $hod['primary_email'] : (($hod['secondary_email']) ? $hod['secondary_email'] : $hod['email']));
		}

		if($member_dept_id) foreach($member_dept_id as $member)
		{
			$member_email 	= $this->model_user->getUsersEmails(array('b.id = '.$member['id']))[0];

			array_push($input['member_email'], ($member_email['primary_email']) ? $member_email['primary_email'] : (($member_email['secondary_email']) ? $member_email['secondary_email'] : $member_email['email']));
			
			// $hods = $this->model_company->getDepartmentHOD(null,array('a.id' => $member['department_id']));	

			// if($hods) foreach($hods as $hod)
			// {
			// 	array_push($input['department_hod'], ($hod['primary_email']) ? $hod['primary_email'] : (($hod['secondary_email']) ? $hod['secondary_email'] : $hod['email']));
			// }
		}
		
		$newPettyAdvance = $this->model_general->insert('sv__petty_cash_advance',$insert);
		// $newPettyAdvance = 1;

		$this->load->library('File_upload');

		$upload_directory = 'assets/upload/hr/Form/pettyCashAdvanceForm/2/'.$this->logged_user['id'];

		$upload_status = $this->file_upload
			->set_file_type(FILE_TYPE_UPLOAD)
			->set_directory_public()
			->set_upload_directory($upload_directory)
			->uploads('picture_upload');

		if(is_array($upload_status)) 
		{
			$uploadPhoto = array
			(
				'photo_title'         	=> (!empty($upload_status['file_name']))? $upload_status['file_name']:'',
				'petty_cash_advance_id' => $newPettyAdvance,
				'file_location'     	=> (!empty($upload_status['file_name']))?$upload_directory:'', 
				'is_delete'         	=> 0,
			);

			$newMaintenance2 = $this->model_general->insert('sv__petty_cash_advance_upload',$uploadPhoto);
		} else {
			echo 'Upload Failed. Please Try Again.';
		}

		foreach($input as $key => $row)
		{
			$input_explode = explode("__",$key);
			
			if($input_explode[0] == 'desc_detail')
			{
				array_push($description_id,array($input_explode[1])[0]);
				array_push($description_detail,array($input['desc_detail__'.$input_explode[1]])[0]);
				array_push($description_amount,array(str_replace(',','',$input['desc_amount__'.$input_explode[1]]))[0]);
			}
		}

		$this->model_petty_cash_advance->updateOrCreateNewDescription($newPettyAdvance, $description_id, $description_detail, $description_amount);

		if($member_dept_id)
		{ 
			$input['member_id'] = '';
			foreach($member_dept_id as $key => $dept_id)
			{
				$input['member_id'][] = $dept_id['id'];
				$input['member_dept_id'][] = $dept_id['department_id'];
			}

			$this->model_petty_cash_advance->updateOrCreateNewMember($newPettyAdvance, $input['member_id'], $input['member_dept_id']);
		}

		if(!empty($newPettyAdvance))
		{
			$petty_cash_item_detail = array();
			$client					= (isset($input['client_id']))?$this->model_crm->getCustomerDetail(array('a.id' => $input['client_id']))[0]:'';

			foreach($description_detail as $key => $val)
			{
				array_push($petty_cash_item_detail, $val.' - <b>RM'.$description_amount[$key].'</b>');
			}

			$form_detail = array 
			(
				'name' 				=> $input['request_name'],
				'email_address'		=> $input['request_email'],
				'department'		=> $input['request_dept'],
				'request_type'		=> $request_mode,
				'date_request'		=> $input['datereq'],
			);

			if(strtotime($input['date_from']) > 0) $form_detail['date_from'] = $input['date_from'].' - '.$input['date_to'];
			if($client) $form_detail['client'] = $client->name;
			$form_detail['detail'] = $petty_cash_item_detail;

			
			$user_email = array();			
			// if(sizeof($input['department_hod']) > 0) foreach($input['department_hod'] as $hod) array_push($user_email, $hod);
			
			$send_copy_form_email 	= (isset($input['send_email_checkbox']) && $input['send_email_checkbox'] == 'on')?$input['send_email_checkbox']:'off';	
			if($send_copy_form_email == 'on')
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['request_name_id']))[0];
				$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			}

			if($user_email)
			{
				$emailSubject 		= 'New '.$request_mode.' Request - '.$input['request_name'].' ['.str_pad($newPettyAdvance,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $input['request_name'].' has request '.strtolower($request_mode).' on '.$input['datereq'].'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->session->set_flashdata('success',"Successfully add new request for ".$request_mode.". Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new request for ".$request_mode.". Please try again.");
		}

		redirect(base_url('hr/serviceform/petty_cash_advance_list'));
	}

	function petty_cash_advance_edit()
	{
		$this->load->model('hr/model_petty_cash_advance');

		$input 				= $this->input->post();
		$member_dept_id		= (isset($input['member_id']))?$this->model_petty_cash_advance->getMemberDeptID($input['member_id']):'';
		if($input['request_type'] == 0) $request_mode = 'Petty Cash';
        elseif($input['request_type'] == 1) $request_mode = 'Cash Advance';
        elseif($input['request_type'] == 2) $request_mode = 'Reimbursement';
        elseif($input['request_type'] == 3) $request_mode = 'Perks';
        else $request_mode = '';

		$description_id 	= array();
		$description_detail = array();
		$description_amount = array();

		$update = array
		(
			'business_entity_id'	=> $input['entity_id'],
			'job_id'				=> ($input['job_id'] > 0)?$input['job_id']:0,
			'request_type'			=> $input['request_type'],
			'client_id'				=> $input['client_id'],
			'travel_date_from'		=> date('Y-m-d',strtotime($input['date_from'])),
			'travel_date_to'		=> date('Y-m-d',strtotime($input['date_to'])),
			'total'					=> str_replace(',', '', $input['total_petty_cash_advance']),
			'updatedBY'				=> $this->logged_user['id'],
			'updatedTS'				=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID'	=> $input['pettyCashAdvanceID'],
		);

		$updatePettyAdvance = $this->model_general->update('sv__petty_cash_advance',$update, $where);

		$this->load->library('File_upload');

		$upload_directory = 'assets/upload/hr/Form/pettyCashAdvanceForm/2/'.$this->logged_user['id'];

		$upload_status = $this->file_upload
			->set_file_type(FILE_TYPE_UPLOAD)
			->set_directory_public()
			->set_upload_directory($upload_directory)
			->uploads('picture_upload');

		if(is_array($upload_status)) 
		{
			$uploadPhoto = array
			(
				'photo_title'         	=> (!empty($upload_status['file_name']))? $upload_status['file_name']:'',
				'petty_cash_advance_id' => $input['pettyCashAdvanceID'],
				'file_location'     	=> (!empty($upload_status['file_name']))?$upload_directory:'', 
				'is_delete'         	=> 0,
			);

			$newMaintenance2 = $this->model_general->insert('sv__petty_cash_advance_upload',$uploadPhoto);
		} else {
			echo 'Upload Failed. Please Try Again.';
		}

		foreach($input as $key => $row)
		{
			$input_explode = explode("__",$key);
			
			if($input_explode[0] == 'desc_detail')
			{
				array_push($description_id,array($input_explode[1])[0]);
				array_push($description_detail,array($input['desc_detail__'.$input_explode[1]])[0]);
				array_push($description_amount,array(str_replace(',', '', $input['desc_amount__'.$input_explode[1]]))[0]);
			}
		}

		$this->model_petty_cash_advance->updateOrCreateNewDescription($input['pettyCashAdvanceID'], $description_id, $description_detail, $description_amount);

		if($member_dept_id) 
		{
			$input['member_id'] = '';
			foreach($member_dept_id as $key => $dept_id)
			{
				$input['member_id'][] = $dept_id['id'];
				$input['member_dept_id'][] = $dept_id['department_id'];
			}

			$this->model_petty_cash_advance->updateOrCreateNewMember($input['pettyCashAdvanceID'], $input['member_id'], $input['member_dept_id']);
		}

		if(!empty($updatePettyAdvance))
		{
			$this->session->set_flashdata('success',"Successfully update request for ".$request_mode.". Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update request for ".$request_mode.". Please try again.");
		}

		redirect(base_url('hr/serviceform/petty_cash_advance_list'));
	}

	function petty_cash_advance_approved($mode)
	{
		$input 	= $this->input->post();
		$input['finance_total_approved'] = str_replace(',', '', $input['finance_total_approved']);
		$user_email = array();
		$update = array();

		if($mode == 'manager')
		{
			$temp = array
			(
				'approval_status'	=> $input['approveBtn'],
				'approvedBY'		=> $input['approve_name_id'],
				'approvedTS'		=> date('Y-m-d H:i:s')
			);

			array_push($update, $temp);

			if($input['approveBtn'] == 1) $status = 'Approved';
			elseif($input['approveBtn'] == 2) $status = 'Rejected';
			else $status = '';

			array_push($user_email,'finance@salihin.com.my');
			$finance_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 8'));
			if($finance_detail) foreach($finance_detail as $finance_email) 
			{
				array_push($user_email, ($finance_email['primary_email']) ? $finance_email['primary_email'] : (($finance_email['secondary_email']) ? $finance_email['secondary_email'] : $finance_email['email']));
			}
		}else{
			$temp = array
			(
				'prepared_status'	=> $input['financeCompleteBtn'],
				'advice_no'			=> $input['advice_no'],
				'total_approved'	=> $input['finance_total_approved'],
				'preparedBY'		=> $input['finance_name_id'],
				'preparedTS'		=> date('Y-m-d H:i:s')
			);

			array_push($update, $temp);

			if($input['financeCompleteBtn'] == 1) $status = 'Completed';
			elseif($input['financeCompleteBtn'] == 2) $status = 'Duplicate';
			else $status = '';
		}

		$where = array('ID' => $input['pettyCashAdvanceID']);

		$update_status = $this->model_general->update('sv__petty_cash_advance',$update[0],$where);
		
		if($update_status)
		{
			$form 			= $this->model_approval->get_form_detail('sv__petty_cash_advance',$input['pettyCashAdvanceID']);
			$form_createdTS	= (isset($form['createdTS']))?$form['createdTS']:$form['createdTS'];
			$form_creator 	= (isset($form['createdBY']))?$form['createdBY']:$form['createdBY'];
			$form_requestor = (isset($form['requester_id']))?$form['requester_id']:0;
			$form_requestor_name = (isset($form['requester_id']))?$this->db->select('name')->where('id',$form['requester_id'])->get('user')->result_array()[0]['name']:'';

			if($form['request_type'] == 0) $request_mode = 'Petty Cash';
	        elseif($form['request_type'] == 1) $request_mode = 'Cash Advance';
	        elseif($form['request_type'] == 2) $request_mode = 'Reimbursement';
	        elseif($form['request_type'] == 3) $request_mode = 'Perks';
	        else $request_mode = '';

			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$form_creator))[0];
			$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));

			if($user_email)
			{
				$emailSubject 		= $request_mode.' - ['.str_pad($input['pettyCashAdvanceID'],5,0,STR_PAD_LEFT).'] '.ucwords($status);
				$emailMessage 		= $request_mode.' request [#'.str_pad($input['pettyCashAdvanceID'],5,0,STR_PAD_LEFT).'] created by <b>'.ucfirst($form_requestor_name).'</b> at <b>'.date('d-m-Y h:i:sA',strtotime($form_createdTS)).'</b> have been '.ucwords($status).'.';
				// $emailMessage 		= 'Your '.$request_mode.' [#'.str_pad($input['pettyCashAdvanceID'],5,0,STR_PAD_LEFT).'] created at <b>'.date('d-m-Y h:i:sA',strtotime($form_createdTS)).'</b> have been '.ucwords($status).'.';
				$emailDetailForm	= array();

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}
			$this->session->set_flashdata('success',"Successfully update ".$request_mode.". Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update ".$request_mode.". Please try again.");
		}

		redirect('hr/serviceform/petty_cash_advance_list');
	}

	function deletePettyCashAdvanceList()
	{
		$input 					= $this->input->post();
		$pettyCashAdvanceID 	= $input['petty_cash_advanceID'];

		$sets = array
		(
			'is_delete'  	=> 1,
			'updatedBY'   	=> $this->logged_user['id'],
			'updatedTS' 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $pettyCashAdvanceID,
		);

		$affected_rows = $this->model_general->update('sv__petty_cash_advance',$sets,$where);

		if($affected_rows)
		{
			$this->model_general->update('sv__petty_cash_advance_description',$sets,array('petty_cash_advance_id' => $pettyCashAdvanceID));
			$this->model_general->update('sv__petty_cash_advance_member',$sets,array('petty_cash_advance_id' => $pettyCashAdvanceID));
			$this->model_general->update('sv__petty_cash_advance_listing',$sets,array('petty_cash_advance_id' => $pettyCashAdvanceID));

			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted Petty Cash / Advance from list."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete Petty Cash / Advance from list."
			));
		}
	}

	function petty_cash_advance_description()
	{
		$this->load->model('hr/model_petty_cash_advance');
		
		$data = array
		(
			'page_setup'  	=> $this->template->pageSetup('Online Form', '', 'Petty Cash / Advance Description'),
			'description'	=> $this->model_petty_cash_advance->getPettyCashAdvanceDescription(),
		);

		$this->template->view('hr/policyprocedure/form/petty_cash_advance_description', $data);
	}

	function savePettyCashAdvanceDescription($mode)
	{
		$input = $this->input->post();

		if(strtolower($mode) == 'add')
		{
			unset($input['id']);
			$input['createdBY'] = $this->logged_user['id'];
			
			$query = $this->model_general->insert('sv__ref_petty_cash_advance_description', $input);
		}else{
			$input['updatedBY'] = $this->logged_user['id'];
			$input['updatedTS'] = date('Y-m-d H:i:s');
			
			$where = array
			(
				'ID' 		=> $input['id'],
			);
			unset($input['id']);

			$query = $this->model_general->update('sv__ref_petty_cash_advance_description', $input, $where);
		}

		if($query)
        {
          	print json_encode(array(
                "status" 		=> "success",
                "msg"			=> "Successfully ".$mode." description.",
            ));

        }
        else
        {
        	print json_encode(array(
                "status"		=> "failed",
                "msg"			=> "Failed to ".$mode." description.",
            ));
        }
	}

	function deletePettyCashAdvanceDescriptionList()
	{
		$input 			= $this->input->post();
		$descriptionID 	= $input['descriptionID'];

		$sets = array
		(
			'is_delete'  	=> 1,
			'updatedBY'   	=> $this->logged_user['id'],
			'updatedTS' 	=> date('Y-m-d H:i:s'),
		);

		$where = array
		(
			'ID' => $descriptionID,
		);

		$affected_rows = $this->model_general->update('	sv__ref_petty_cash_advance_description',$sets,$where);

		if($affected_rows)
		{
			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully deleted description from list."
			)); 
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete description from list."
			));
		}
	}

	function save_cash_desc_list()
	{
		$this->load->model('hr/model_petty_cash_advance');

		$input 				= $this->input->post();
		$pettyCashAdvanceID = $input['pettyCashAdvanceID'];

		$description_id 	= array();
		$description_detail = array();
		$description_amount = array();
		$description_sst 	= array();
		$description_total 	= array();

		foreach($input as $key => $row)
		{
			$input_explode = explode("__",$key);
			
			if($input_explode[0] == 'desc_base')
			{
				array_push($description_id,array($input_explode[1])[0]);
				array_push($description_detail,array($input['desc_remark__'.$input_explode[1]])[0]);
				array_push($description_amount,array($input['desc_base__'.$input_explode[1]])[0]);
				array_push($description_sst,array($input['desc_sst__'.$input_explode[1]])[0]);
				array_push($description_total,array($input['desc_total__'.$input_explode[1]])[0]);
			}
		}

		$newCashAdvanceListing = $this->model_petty_cash_advance->updateOrCreateNewListing($pettyCashAdvanceID, $description_id, $description_detail, $description_amount, $description_sst, $description_total);

		if(!empty($newCashAdvanceListing))
		{
			$update_main = array
			(
				'cash_balance' 			=> ($input['desc_total__received'] - array_sum($description_total)),
				'listing_createdBY'		=> $this->logged_user['id'],
				'listing_createdTS'		=> date('Y-m-d H:i:s'),
			);
			$updateCashAdvance = $this->model_general->update('sv__petty_cash_advance', $update_main, array('ID' => $pettyCashAdvanceID));
			$client	= $this->model_crm->getCustomerDetail(array('a.id' => $input['client_id']))[0];
			// $form_detail = array 
			// (
			// 	'name' 				=> $input['request_name'],
			// 	'email_address'		=> $input['request_email'],
			// 	'department'		=> $input['request_dept'],
			// 	'date_request'		=> $input['datereq'],
			// 	'client'			=> $client->name,
			// );
			
			// $user_email = array();
			
			// $send_copy_form_email 	= (isset($input['send_email_checkbox']) && $input['send_email_checkbox'] == 'on')?$input['send_email_checkbox']:'off';	
			// if($send_copy_form_email == 'on')
			// {
			// 	$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['request_name_id']))[0];
			// 	$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			// }

			// if($user_email)
			// {
			// 	$emailSubject 		= 'New Invoice Request - '.$input['request_name'].' ['.str_pad($newInvoice,5,0,STR_PAD_LEFT).']';
			// 	$emailMessage 		= $input['request_name'].' has request invoice on '.$input['datereq'].'. Below is the detail:- ';
			// 	$emailDetailForm	= $form_detail;

			// 	$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			// }

			$this->session->set_flashdata('success',"Successfully create cash advance listing. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to create cash advance listing. Please try again.");
		}

		redirect(base_url('hr/serviceform/petty_cash_advance_list'));
	}

	function petty_cash_listing_approved($mode)
	{
		$input = $this->input->post();
		$update = array();

		if($mode == 'manager')
		{
			$temp = array
			(
				'listing_approval_status'	=> $input['approveBtn'],
				'listing_approvedBY'		=> $input['approve_name_id'],
				'listing_approvedTS'		=> date('Y-m-d H:i:s',strtotime($input['dateapprv']))
			);

			array_push($update, $temp);
		}else{
			$temp = array
			(
				'listing_received_status'	=> $input['financeCompleteBtn'],
				'listing_receivedBY'		=> $input['finance_name_id'],
				'balance_received'			=> $input['finance_total_received'],
				'listing_receivedTS'		=> date('Y-m-d H:i:s',strtotime($input['finance_date']))
			);

			array_push($update, $temp);
		}

		$where = array('ID' => $input['pettyCashAdvanceID']);

		$update_status = $this->model_general->update('sv__petty_cash_advance',$update[0],$where);
		
		if($update_status)
		{
			$this->session->set_flashdata('success',"Successfully update status cash advance listing. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update status cash advance listing. Please try again.");
		}

		redirect('hr/serviceform/petty_cash_advance_list');
	}

	function petty_cash_advance_get_description()
	{
		$this->load->model('hr/model_petty_cash_advance');
		$input = $this->input->post();
		$type = $input['type'];
		$description = $this->model_petty_cash_advance->getPettyCashAdvanceDescription($type);

		if($description)
		{
			print json_encode(array(
				"status" 		=> "Success",
				"description"	=> $description,
				"min_id"		=> min($description)['ID'],
				"max_id"		=> max($description)['ID'],
				"msg"	 		=> "Successfully retrieve description."
			)); 
		}else{
			print json_encode(array(
				"status" 		=> "Error",
				"description"	=> $description,
				"min_id"		=> min($description)['ID'],
				"max_id"		=> max($description)['ID'],
				"msg"	 		=> "Failed to retrieve description."
			)); 
		}
	}

	function sv_form_price()
	{
		$module_access = array();
		if(!empty($_SESSION['all_modules_access']))
		{
			if($this->logged_module['role'] == 'admin' || $_SESSION['user']['division_id'] == 5)
			{
				array_push($module_access,1); // hr
			}

			if($_SESSION['all_modules_access'][0]['access_lvl'] == 'admin' || $_SESSION['user']['division_id'] == 4)
			{
				//array_push($module_access,7); // admin
			}

			if($_SESSION['user']['division_id'] == 8 || $_SESSION['user']['division_id'] == 10)
			{
				array_push($module_access,9); // finance
			}

			if($_SESSION['user']['division_id'] == 19 || $_SESSION['user']['division_id'] == 10)
			{
				array_push($module_access,3); // it admin
			}
		}

		$select = array('a.id as form_id, a.title, b.price, b.affective_date, b.status, b.type as price_type');
		$where = array('a.is_delete' => 0, 'length(a.table_name) > ' => 0);
		$join = array(array('sv__ref_form_price b','b.form_id = a.id and b.is_delete = 0 and b.status = 1','left'));
		$order = array('a.category_id' => 'asc', 'a.id' => 'asc');
		$where_in = array('a.category_id' => $module_access);

		$data = array
		(
			'page_setup'  	=> $this->template->pageSetup('Online Form', '', 'Service Form Price'),
			'form_detail'	=> $this->model_form->sv__filter('hr__form a', $select, $where, $join, $order, null, null, null, null, $where_in),
		);

		$this->template->view('hr/policyprocedure/form/service_form_detail', $data);
	}

	function update_sv_form_price()
	{
		$input 		= $this->input->post();
		$tbl_name 	= 'sv__ref_form_price';
		$form_price = $this->model_form->sv__filter($tbl_name,array('*'),array('form_id'=>$input['service_form_id']))[0];
		$detail 	= array();

		$detail['type'] 			= $input['service_form_type'];
		$detail['affective_date'] 	= date('Y-m-d'); 
		$detail['price'] 			= ($input['service_form_type'] == 1)?($input['service_form_price']/100):$input['service_form_price'];

		if($form_price)
		{
			$detail['updatedBY'] 		= $this->logged_user['id']; 
			$detail['updatedTS'] 		= date('Y-m-d H:i:s'); 
			$where['form_id'] 			= $input['service_form_id']; 

			$saveFormPrice = $this->model_general->update($tbl_name,$detail,$where);
		}else{
			$detail['form_id'] 			= $input['service_form_id']; 
			$detail['status'] 			= 1; 
			$detail['createdBY'] 		= $this->logged_user['id'];

			$saveFormPrice = $this->model_general->insert($tbl_name,$detail);
		}

		if($saveFormPrice)
		{
			$this->session->set_flashdata('success',"Successfully update service form price. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update service form price Please try again.");
		}

		redirect(base_url('hr/serviceform/sv_form_price'));
	}

	function zoom_booking_list()
	{
		$this->load->model('hr/model_zoom_booking'); 
		$zoomBookingList = $this->model_zoom_booking->getZoomRequestList();
		$year			 = ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');

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

		if(!empty($zoomBookingList))
		{
			foreach ($zoomBookingList as $key => $detail) 
			{
				$createdTS   = date('Y-m-d',strtotime($detail['createdTS']));
				$start_date  = $detail['start_date'];
				$end_date	 = $detail['end_date'];
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['dept_name'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = $detail['requester_staff_id'];
				$tmpEvent['start']          = $start_date;
				$tmpEvent['end']			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title']          = $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']    = $detail['requester_name'].' request to book "'.$detail['account'].'".';
				$tmpEvent['color']          = $detail['color_code'];
				$tmpEvent['textColor']      = '#ffffff';

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

		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		$data = array
		(
			'page_setup'        => $this->template->pageSetup('Online Form', '', 'Zoom Booking Request List'),
			'zoom_account_list' => $this->model_zoom_booking->getZoomAccountList(),
			'zoom_booking_year' => $this->model_zoom_booking->getZoomBookingByYear($year),
			'department' 		=> $this->model_company->getDepartments(),
			'zoomBookingList'	=> ($module_access['access_lvl'] =='admin' || $this->logged_user['division_id'] == 4)?$this->model_zoom_booking->getZoomRequestList(null,null,$year):$this->model_zoom_booking->getZoomRequestList(null,$this->logged_user['id'],$year),
			'fc_res'            => json_encode($fc_res),
			'fc_event'          => json_encode($fc_event),
			'resource'          => json_encode($resource),
		);

		$this->template->view('hr/policyprocedure/form/zoom_booking_list', $data);
	}

	function zoom_booking_form($ID=null, $mode = null)
	{
		$this->load->model('admin/model_user');
		$this->load->model('hr/model_zoom_booking');

		$zoomBookingList = $this->model_zoom_booking->getZoomRequestList();

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

		if(!empty($zoomBookingList))
		{
			foreach ($zoomBookingList as $key => $detail) 
			{
				$createdTS   = date('Y-m-d',strtotime($detail['createdTS']));
				$start_date  = $detail['start_date'];
				$end_date	 = $detail['end_date'];
				
				$tmpRes                     = array(); $tmpEvent = array();
				$tmpRes['id']               = $detail['ID'];
				$tmpRes['title']            = $detail['dept_name'];

				$tmpEvent['id']             = $key;
				$tmpEvent['resourceId']     = $detail['requester_staff_id'];
				$tmpEvent['start']          = $start_date;
				$tmpEvent['end']			= date('Y-m-d',strtotime($end_date."+1 days"));
				$tmpEvent['title']          = $detail['dept_name'].'/'.$detail['branchName'];
				$tmpEvent['description']    = $detail['requester_name'].' request to book "'.$detail['account'].'".';
				$tmpEvent['color']          = $detail['color_code'];
				$tmpEvent['textColor']      = '#ffffff';

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

		$data = array
		(
			'ID'         			=> $ID,
			'mode'					=> $mode,
			'listName'				=> $this->model_user->getUsers2(),
			'zoom_booking_day' 		=> $this->model_zoom_booking->getZoomBookingByDay(),
			'zoom_account'			=> $this->model_zoom_booking->getZoomAccountList(),
			// 'upcoming_request'	=> $this->model_zoom_booking->getBookingCarByWeek(),
			'zoomBookingDetail' 	=> $this->model_zoom_booking->getZoomRequestList($ID)[0],
			'fc_res'            	=> json_encode($fc_res),
			'fc_event'          	=> json_encode($fc_event),
			'resource'          	=> json_encode($resource),
		);

		// debug($data['zoom_account']);
		// die();

        $filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl']=='admin' || $this->logged_user['division_id'] == 4){
	        if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__zoom_booking';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'zoom_booking_list';
	            $data_approval['form_name'] = 'Zoom Booking Form';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__zoom_booking','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
		}

		$data['page_setup'] = $this->template->pageSetup('Online Form', '', 'Zoom Booking Form');
		$this->template->view('hr/policyprocedure/form/zoom_booking', $data);
	}

	function get_zoom_detail()
	{
		$this->load->model('hr/model_zoom_booking');
		$input 	= $this->input->post();
		$mode 	= $input['mode'];
		$detail = array();

		if($mode == 'create_zoom_account')
		{
			$query = $this->model_zoom_booking->getZoomAccountList();
		}elseif($mode == 'check_staff_password')
		{
			$this->load->model('admin/model_login');
			$query = $this->model_login->verifyLoginData($input['input_value']);
			$detail = (!empty($input['detail']))?$input['detail']:$detail;
		}

		if($query)
		{
			print json_encode(array(
				"status" 	=> "Success",
				"query"		=> $query,
				"detail"	=> ($detail && ((strtotime(date('Y-m-d H:i:00')) >= strtotime($detail['start_date'].' '.$detail['start_time'])) && (strtotime(date('Y-m-d H:i:00')) <= strtotime($detail['end_date'].' '.$detail['end_time']))))?true:false,
			)); 
		}else{
			print json_encode(array(
				"status" 	=> "Error",
				"query"		=> $query,
				"detail"	=> $detail,
			)); 
		}
	}

	function update_zoom_detail()
	{
		$input 		= $this->input->post();
		$save_mode	= ucwords(implode(" ", explode('_',$input['mode'])));

		if(explode('_',$input['mode'])[0] == 'update' || explode('_',$input['mode'])[0] == 'delete') // edit & delete
		{
			$input['input_value']['updatedBY'] = $this->logged_user['id'];
			$input['input_value']['updatedTS'] = date('Y-m-d H:i:s');

			$where = array
			(
				'ID' 		=> $input['input_value']['ID'],
			);
			
			unset($input['input_value']['ID']);

			$query = $this->model_general->update($input['table_name'], $input['input_value'], $where);
			
			if($query)
			{
				if($input['table_name'] == 'sv__zoom_booking' && explode('_',$input['mode'])[0] == 'delete') 
				{
					$this->model_approval->update_sv_status($input['table_name'],$where['ID']);
					
					$update_zoom_detail = $this->model_general->update('sv__approval',array('is_delete'=>$input['input_value']['is_delete'], 'updated_by'=>$input['input_value']['updatedBY'], 'updatedTS'=>$input['input_value']['updatedTS']), array('table_name'=>"'".$input['table_name']."'", 'id_table'=>$where['ID']));
				}
			}
		}else{
			$input['input_value']['createdBY'] 	= $this->logged_user['id'];
			$input['input_value']['color_code'] = '#'.sprintf("%02x%02x%02x", rand(0,255), rand(0,255), rand(0,255));

			$query = $this->model_general->insert($input['table_name'], $input['input_value']);
		}

		if($query)
		{
			print json_encode(array(
				"status"	=> "Success",
                "msg"		=> "Successfully ".$save_mode.".",
				"query"		=> $query,
			));
		}else{
			print json_encode(array(
				"status"	=> "Error",
                "msg"		=> "Successfully ".$save_mode.".",
				"query"		=> $query,
			));

		}
	}

	function zoom_booking_save()
	{
		$this->load->model('hr/model_zoom_booking');

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

		$user_dept_id 	= $this->model_user->getUsers2(isset($input['guest_details'])?$input['guest_details']:$input['reqName_id'])['department_id'];
		$user_id 		= (isset($input['guest_details']))?$input['guest_details']:$input['reqName_id'];

		$insertData = array(
			'requester_id'	=> $user_id,
			'department_id' => $user_dept_id,
			'account_id' 	=> $input['account_id'],
			'meeting_type'	=> $input['meeting_type'],
			'topic' 		=> $input['topic'],
            'start_date'	=> date('Y-m-d',strtotime($input['start_date'])),
			'start_time' 	=> date('H:i:s',strtotime($input['start_time'])),
			'end_date' 		=> date('Y-m-d',strtotime($input['end_date'])),
			'end_time' 		=> date('H:i:s',strtotime($input['end_time'])),
			'createdBY' 	=> $this->logged_user['id']
		);

		$startDate 	= (isset($input['start_date']) && !empty($input['start_date']))?date('Y-m-d',strtotime($input['start_date'])):'';
		$startTime 	= (isset($input['start_time']) && !empty($input['start_time']))?date('H:i:s',strtotime($input['start_time'])):'';
		$endDate 	= (isset($input['end_date']) && !empty($input['end_date']))?date('Y-m-d',strtotime($input['end_date'])):'';
		$endTime 	= (isset($input['end_time']) && !empty($input['end_time']))?date('H:i:s',strtotime($input['end_time'])):'';

		$where = array
		(
			"(('".$startDate."' BETWEEN start_date AND end_date OR '".$endDate."' BETWEEN start_date AND end_date)
			OR 
			(start_date BETWEEN '".$startDate."' AND '".$endDate."' OR end_date BETWEEN '".$startDate."' AND '".$endDate."'))
			AND
			(('".$startTime."' BETWEEN start_time AND end_time OR '".$endTime."' BETWEEN start_time AND end_time)
			OR 
			(start_time BETWEEN '".$startTime."' AND '".$endTime."' OR end_time BETWEEN '".$startTime."' AND '".$endTime."'))",
		);
		
		$getBookingData = $this->model_zoom_booking->getZoomBookingDate($input['account_id'], $where);

		if(!empty($getBookingData)){ //date have been booked.
			$this->session->set_flashdata('error',"Date requested have already been booked. Please choose another date.");
		} else { //date approved
			$newZoomBooking = $this->model_general->insert('sv__zoom_booking', $insertData);
			if(!empty($newZoomBooking))
			{
				$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['reqName_id']))[0];
				$account_name 			= $this->model_zoom_booking->getZoomAccountList($input['account_id'])[0];

				$form_detail = array 
				(
					'name' 					=> $input['reqName'],
					'email_address'			=> ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']),
					'department'			=> $input['department'],
					'date_request'			=> $input['reqDate'],
					'account_name'  		=> $account_name['account'],
					'start_date'  			=> $input['start_date'].' / '.date('h:iA',strtotime($input['start_time'])),
					'end_date'  			=> $input['end_date'].' / '.date('h:iA',strtotime($input['end_time'])),
					'purpose' 				=> ($input['meeting_type'] == 0)?'Meeting':'Webinar',
					'topic'  				=> $input['topic'],
				);

				$user_email 	= array();
				$admin_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 4'));
				if($admin_detail) foreach($admin_detail as $admin_email) 
				{
					// array_push($user_email, ($admin_email['primary_email']) ? $admin_email['primary_email'] : (($admin_email['secondary_email']) ? $admin_email['secondary_email'] : $admin_email['email']));
				}

				$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
				
				$form_requestor_name 	= $this->model_user->getUserDetail($input['reqName_id'])['name'];

				if($user_email)
				{
					$emailSubject 		= 'New Zoom Booking Request - '.$form_requestor_name.' ['.str_pad($newZoomBooking,5,0,STR_PAD_LEFT).']';
					$emailMessage 		= $form_requestor_name.' has request zoom booking on '.$input['reqDate'].'. Below is the detail:- ';
					$emailDetailForm	= $form_detail;

					$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
				}

				$this->model_approval->updateOrCreateNew('sv__zoom_booking',$newZoomBooking,'Pending',0);

				$this->session->set_flashdata('success',"Successfully add new request for zoom. Thank you.");
			}else{
				$this->session->set_flashdata('error',"System failed to add new request for zoom. Please try again.");
			}
		}
		
		redirect(base_url('hr/serviceform/zoom_booking_list'));
	}

	function zoom_booking_edit()
	{
		$this->load->model('hr/model_zoom_booking');

		$input 			= $this->input->post();
		$user_dept_id 	= $this->model_user->getUsers2((isset($input['guest_details']))?$input['guest_details']:((isset($input['guest_details_input']))?$input['guest_details_input']:$input['reqName_id']))['department_id'];
		$user_id 		= (isset($input['guest_details']))?$input['guest_details']:((isset($input['guest_details_input']))?$input['guest_details_input']:$input['reqName_id']);

		$sets = array(
			'requester_id'	=> $user_id,
			'department_id' => $user_dept_id,
			'account_id' 	=> $input['account_id'],
			'meeting_type'	=> $input['meeting_type'],
			'topic' 		=> $input['topic'],
            'start_date'	=> date('Y-m-d',strtotime($input['start_date'])),
			'start_time' 	=> date('H:i:s',strtotime($input['start_time'])),
			'end_date' 		=> date('Y-m-d',strtotime($input['end_date'])),
			'end_time' 		=> date('H:i:s',strtotime($input['end_time'])),
			'updatedBY' 	=> $this->logged_user['id'],
			'updatedTS' 	=> date('Y-m-d H:i:s')
		);

		$where = array('ID' => $input['zoomBookingID']);

		$startDate 	= (isset($input['start_date']) && !empty($input['start_date']))?date('Y-m-d',strtotime($input['start_date'])):'';
		$startTime 	= (isset($input['start_time']) && !empty($input['start_time']))?date('H:i:s',strtotime($input['start_time'])):'';
		$endDate 	= (isset($input['end_date']) && !empty($input['end_date']))?date('Y-m-d',strtotime($input['end_date'])):'';
		$endTime 	= (isset($input['end_time']) && !empty($input['end_time']))?date('H:i:s',strtotime($input['end_time'])):'';

		$checking_where = array
		(
			"(('".$startDate."' BETWEEN start_date AND end_date OR '".$endDate."' BETWEEN start_date AND end_date)
			OR 
			(start_date BETWEEN '".$startDate."' AND '".$endDate."' OR end_date BETWEEN '".$startDate."' AND '".$endDate."'))
			AND
			(('".$startTime."' BETWEEN start_time AND end_time OR '".$endTime."' BETWEEN start_time AND end_time)
			OR 
			(start_time BETWEEN '".$startTime."' AND '".$endTime."' OR end_time BETWEEN '".$startTime."' AND '".$endTime."'))",
			"ID != ".$input['zoomBookingID']
		);
		
		$getBookingData = $this->model_zoom_booking->getZoomBookingDate($input['account_id'], $checking_where);

		if(!empty($getBookingData)){ //date have been booked.
			$this->session->set_flashdata('error',"Date requested have already been booked. Please choose another date.");
		} else { //date approved
			$affected_rows = $this->model_zoom_booking->update_zoomBooking($sets,$where);
			if($affected_rows){	
				$this->session->set_flashdata('success',"Successfully update requested zoom booking. Thank you.");
			} else {
				$this->session->set_flashdata('error',"System failed to update requested zoom booking.");
			}
		}

		redirect(base_url('hr/serviceform/zoom_booking_list'));
	}

	function capex_request_list()
	{
		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		$this->load->model('hr/model_capex_request');
		$data = array
		(
			'page_setup' 		=> $this->template->pageSetup('Online Form', '', 'CAPEX Request List'),
			'department'		=> $this->model_company->getDepartments(),
			'capexRequestList'	=> ($module_access['access_lvl'] == 'admin' || $this->logged_user['division_id'] == 4)?$this->model_capex_request->getCapexRequestList():$this->model_capex_request->getCapexRequestList(null,$this->logged_user['id']),
		);

		foreach ($data['capexRequestList'] as $key => $value) 
		{		
			if(!empty($value['category_name']))
			{ 
				$data['capexRequestList'][$key]['category'] = explode(',',$value['category']); 
			}else{
				$data['capexRequestList'][$key]['category'] = '';
			}

			if(!empty($value['item_id']))
			{ 
				$data['capexRequestList'][$key]['item_id'] = explode(',',$value['item_id']); 
			}else{
				$data['capexRequestList'][$key]['item_id'] = '';
			}

			if(!empty($value['item']))
			{ 
				$data['capexRequestList'][$key]['item'] = explode(',',$value['item']); 
			}else{
				$data['capexRequestList'][$key]['item'] = '';
			}

			if(!empty($value['quantity']))
			{ 
				$data['capexRequestList'][$key]['quantity'] = explode(',',$value['quantity']); 
			}else{
				$data['capexRequestList'][$key]['quantity'] = '';
			}
		}

		// die(debug($this->session->userdata('user')));

		$this->template->view('hr/policyprocedure/form/capex_request_list', $data);
	}

	function capex_request_form($ID = null, $mode = null)
	{
		$this->load->model('hr/model_capex_request');

		$data = array
		(
			'page_setup'        		=> $this->template->pageSetup('Online Form', '', 'CAPEX Request Form'),
			'ID'						=> $ID,
			'mode'						=> $mode,
			'capexRequestDetail'		=> $this->model_capex_request->getCapexRequestList($ID)[0],
			'capexCategoryItemDetail'	=> $this->model_capex_request->getCapexItemDetail($ID),
		);

		// debug($data['capexCategoryItemDetail']);
		// die();

		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 1
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl']=='admin' || $this->logged_user['division_id'] == 4){
	        if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__capex_request';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'capex_request_list';
	            $data_approval['form_name'] = 'CAPEX Request Form';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__capex_request','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
		}

		$this->template->view('hr/policyprocedure/form/capex_request_form', $data);
	}

	function get_capex_detail()
	{
		$this->load->model('hr/model_capex_request');

		$input = $this->input->post();
		$query = $this->model_capex_request->getCapexCategoryItem($input['input_value']['category_id']);

		if($query)
		{
			print json_encode(array(
				"status" 	=> "Success",
				"query"		=> $query,
			)); 
		}else{
			print json_encode(array(
				"status" 	=> "Error",
				"query"		=> $query,
			)); 
		}
	}

	function capex_request_save($mode = null)
	{
		$input 		= $this->input->post();
		$status		= '';
		$msg 		= '';
		$capexID 	= '';

		if(isset($mode))
		{
			if($mode == 'item')
			{
				$input['createdBY'] = $this->logged_user['id'];
				
				$newCapex = $this->model_general->insert('sv__capex_item_detail',$input);

				if($newCapex)
				{					
					$status = 'success';
					$msg 	= "Successfully add new item detail for CAPEX. Thank you.";
				}else{
					$status = 'error';
					$msg 	= "System failed to add new item detail for CAPEX. Please try again.";
				}

				$capexID = $input['capex_id'];
			}
		}else{
			$insert = array
			(
				'requester_id'	=> $input['reqName_id'],
				'department_id'	=> $input['department_id'],
				'purpose'		=> $input['purpose'],
				'createdBY' 	=> $this->logged_user['id']
			);

			$newCapex = $this->model_general->insert('sv__capex_request',$insert);
			
			if($newCapex)
			{
				$this->model_approval->updateOrCreateNew('sv__capex_request',$newCapex,'Pending',0);
				
				$status = 'success';
				$msg 	= "Successfully create new request for CAPEX. Thank you.";
			}else{
				$status = 'error';
				$msg 	= "System failed to create new request for CAPEX. Please try again.";
			}

			$capexID = $newCapex;
		}

		$this->session->set_flashdata($status,$msg);

		redirect(base_url('hr/serviceform/capex_request_form/'.$capexID));
	}

	function capex_request_edit($mode = null)
	{
		$this->load->model('hr/model_capex_request');

		$input 			= $this->input->post();
		$status 	= '';
		$msg 		= '';
		$redirect	= '';

		if(isset($mode))
		{
			if($mode == 'item')
			{
				$capexID 	= $input['capex_id'];
				$where 		= array('ID'=>$input['ID']);
				unset($input['capex_id']);
				unset($input['ID']);
				
				$input['updatedBY'] = $this->logged_user['id'];
				$input['updatedTS'] = date('Y-m-d H:i:s');

				$updateCapex = $this->model_general->update('sv__capex_item_detail',$input,$where);

				if($updateCapex)
				{					
					$status = 'success';
					$msg 	= "Successfully update item detail for CAPEX. Thank you.";
				}else{
					$status = 'error';
					$msg 	= "System failed to update item detail for CAPEX. Please try again.";
				}

				$redirect = base_url('hr/serviceform/capex_request_form/'.$capexID);
			}
		}else{
			$where 			= array('ID'=>$input['capexID']);
			$capex_detail 	= $this->model_capex_request->getCapexRequestList($input['capexID'])[0];
			unset($input['capexID']);

			$update = array
			(
				'purpose'		=> $input['purpose'],
				'updatedBY'		=> $this->logged_user['id'],
				'updatedTS'		=> date('Y-m-d H:i:s'),
			);

			$updateCapex = $this->model_general->update('sv__capex_request',$update,$where);
			
			if($updateCapex)
			{
				if(!empty(strtotime($capex_detail['updatesTS'])) && strtotime($capex_detail['updatesTS']) > 0)
				{
					$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['reqName_id']))[0];

					$form_detail = array 
					(
						'name' 					=> $input['reqName'],
						'email_address'			=> ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']),
						'department'			=> $input['department'],
						'date_request'			=> $input['reqDate'],
						'purpose'  				=> $input['purpose'],
					);

					$user_email 	= array();
					$admin_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 4'));
					if($admin_detail) foreach($admin_detail as $admin_email) 
					{
					// array_push($user_email, ($admin_email['primary_email']) ? $admin_email['primary_email'] : (($admin_email['secondary_email']) ? $admin_email['secondary_email'] : $admin_email['email']));
					}

					$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));

					$form_requestor_name 	= $this->model_user->getUserDetail($input['reqName_id'])['name'];

					if($user_email)
					{
						$emailSubject 		= 'New CAPEX Request - '.$form_requestor_name.' ['.str_pad($newZoomBooking,5,0,STR_PAD_LEFT).']';
						$emailMessage 		= $form_requestor_name.' has request CAPEX item on '.$input['reqDate'].'. Below is the detail:- ';
						$emailDetailForm	= $form_detail;

						$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
					}
				}

				$status = 'success';
				$msg 	= "Successfully update request for CAPEX. Thank you.";
			}else{
				$status = 'error';
				$msg 	= "System failed to update request for CAPEX. Please try again.";
			}

			$redirect = base_url('hr/serviceform/capex_request_list');
		}


		$this->session->set_flashdata($status,$msg);

		redirect($redirect);
	}

	function capex_request_delete($mode = null)
	{
		$input 		= $this->input->post();
		$msg 		= '';

		if(isset($mode))
		{
			if($mode == 'item')
			{
				$item 		= $input['input_value']['item'];
				$capexID 	= $input['input_value']['capex_id'];
				$where 		= array('ID'=>$input['input_value']['ID']);
				unset($input['input_value']['capex_id']);
				unset($input['input_value']['ID']);
				unset($input['input_value']['item']);
				
				$input['input_value']['updatedBY'] = $this->logged_user['id'];
				$input['input_value']['updatedTS'] = date('Y-m-d H:i:s');

				$deleteCapex = $this->model_general->update('sv__capex_item_detail',$input['input_value'],$where);

				if($deleteCapex)
				{
					$msg 	= "Successfully delete ".$item." for CAPEX. Thank you.";
				}else{
					$msg 	= "System failed to delete ".$item." for CAPEX. Please try again.";
				}
			}
		}else{
			$where = array('ID'=>$input['capexID']);
			unset($input['capexID']);

			$update = array
			(
				'purpose'		=> $input['purpose'],
				'updatedBY'		=> $this->logged_user['id'],
				'updatedTS'		=> date('Y-m-d H:i:s'),
			);

			$deleteCapex = $this->model_general->update('sv__capex_request',$update,$where);
			
			if($deleteCapex)
			{
				$msg 	= "Successfully delete request for CAPEX. Thank you.";
			}else{
				$msg 	= "System failed to delete request for CAPEX. Please try again.";
			}
		}
		
		if($deleteCapex)
		{
			print json_encode(array(
				"status" 	=> "Success",
				"msg"		=> $msg,
			)); 
		}else{
			print json_encode(array(
				"status" 	=> "Error",
				"msg"		=> $msg,
			)); 
		}
	}

	function talent_referral_list()
	{
		$this->load->model('hr/model_talent_referral');
        $year	   	= ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');

		$data = array
		(
			'department'			=> $this->model_company->getDepartments(),
			'page_setup'    		=> $this->template->pageSetup('Online Form', '', 'Talent Referral Program List'),
			'talentReferralList'	=> ($this->logged_module['role'] == 'admin')?$this->model_talent_referral->getTalentReferralList(null,null,$year):$this->model_talent_referral->getTalentReferralList(null,$this->logged_user['id'],$year),
		);

		$this->template->view('hr/policyprocedure/form/talent_referral_list', $data);
	}

	function talent_referral_form($ID = null, $mode = null)
	{
		$this->load->model('hr/model_talent_referral');

		$where = array //for candidate list
		(
			'c.date_join between (last_day(now() - interval 2 month) + interval 1 day) and (last_day(now()))',
			// '(c.action_type_id = 0 or c.action_type_id = 1)',
			'c.position_id != ' => 51,
		);

		$data = array
		(
			'page_setup'        		=> $this->template->pageSetup('Online Form', '', 'Talent Referral Program Form'),
			'ID'						=> $ID,
			'mode'						=> $mode,
			'talentReferralDetail'		=> $this->model_talent_referral->getTalentReferralList($ID)[0],
			'business_entity'			=> $this->model_company->getBusinesses(0,$this->logged_user['business_entity_id']),
			'candidate_list'			=> $this->model_talent_referral->getCandidateList($where),
		);

		$this->template->view('hr/policyprocedure/form/talent_referral_form', $data);
	}

	function talent_referral_save()
	{
		$input = $this->input->post();
		debug($input);
		die();

		$insert = array
		(
			'requester_id' 			=> $input['reqName_id'],
			'department_id'			=> $input['department_id'],
			'candidate_name' 		=> $input['candidate_name'],
		    'candidate_email' 		=> $input['candidate_email'],
		    'candidate_contact' 	=> $input['candidate_contact'],
		    'candidate_position' 	=> $input['candidate_position'],
		    'createdBY'				=> $this->logged_user['id'],
		);

		$newTalentReferral = $this->model_general->insert('sv__talent_referral',$insert);

		if($newTalentReferral)
		{
			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['reqName_id']))[0];

			$form_detail = array 
			(
				'employee'."'s".'_name'		=> $input['reqName'],
				'email_address'	=> ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']),
				'department'				=> $input['department'],
				'date'						=> $input['reqDate'],
				'candidate'."'s".'_name'  	=> $input['candidate_name'],
				'e-mail_address'  			=> $input['candidate_email'],
				'telephone_number'  		=> $input['candidate_contact'],
				'position_applied'  		=> $input['candidate_position'],
			);

			$user_email = array();
			// $user_email = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));
			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				// array_push($user_email, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			
			$form_requestor_name 	= $this->model_user->getUserDetail($input['reqName_id'])['name'];

			if($user_email)
			{
				$emailSubject 		= 'New Talent Referral Program Form - '.$form_requestor_name.' ['.str_pad($newTalentReferral,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $form_requestor_name.' has submit form for <b>Talent Referral Program</b> on '.$input['reqDate'].'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->model_approval->updateOrCreateNew('sv__talent_referral',$newTalentReferral,'Pending',0);

			$this->session->set_flashdata('success',"Successfully create new talent referral program form. Thank you.");
		}else{
			$this->session->set_flashdata('error',"Failed to create new talent referral program form. Thank you.");
		}

		redirect('hr/serviceform/talent_referral_list');
	}

	function talent_referral_edit()
	{
		$input = $this->input->post();

		$update = array
		(
			'candidate_name' 		=> $input['candidate_name'],
		    'candidate_email' 		=> $input['candidate_email'],
		    'candidate_contact' 	=> $input['candidate_contact'],
		    'candidate_position' 	=> $input['candidate_position'],
		    'updatedBY'				=> $this->logged_user['id'],
		    'updatedTS'				=> date('Y-m-d H:i:s'),
		);

		$where = array('ID' => $input['talentReferralID']);

		$updateTalentReferral = $this->model_general->update('sv__talent_referral',$update,$where);

		if($updateTalentReferral)
		{
			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$input['reqName_id']))[0];

			$form_detail = array 
			(
				'employee'."'s".'_name'		=> $input['reqName'],
				'email_address'	=> ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']),
				'department'				=> $input['department'],
				'date'						=> $input['reqDate'],
				'candidate'."'s".'_name'  	=> $input['candidate_name'],
				'e-mail_address'  			=> $input['candidate_email'],
				'telephone_number'  		=> $input['candidate_contact'],
				'position_applied'  		=> $input['candidate_position'],
			);

			$user_email = array();
			// $user_email = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));
			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				// array_push($user_email, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			
			$form_requestor_name 	= $this->model_user->getUserDetail($input['reqName_id'])['name'];

			if($user_email)
			{
				$emailSubject 		= 'Talent Referral Program Form Update - '.$form_requestor_name.' ['.str_pad($input['talentReferralID'],5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $form_requestor_name.' has update <b>Talent Referral Program</b> form created on '.$input['reqDate'].'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->session->set_flashdata('success',"Successfully update talent referral program form. Thank you.");
		}else{
			$this->session->set_flashdata('error',"Failed to update talent referral program form. Thank you.");
		}

		redirect('hr/serviceform/talent_referral_list');
	}

	function talent_referral_update_status()
	{
		$this->load->model('hr/model_talent_referral');

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

		$update['status'] 			= $input['statusBtn'];
		$update['application_date'] = date('Y-m-d',strtotime($input['application_date']));
		$update['joining_date']		= date('Y-m-d',strtotime($input['joining_date']));
		if(isset($input['remark'])) $update['remark'] = $input['remark'];
		if(isset($input['payment_status_1'])) $update['payment_status_1'] = $input['payment_status_1'];
		if(isset($input['payment_remark_1'])) $update['payment_remark_1'] = $input['payment_remark_1'];
		if(isset($input['payment_status_2'])) $update['payment_status_2'] = $input['payment_status_2'];
		if(isset($input['payment_remark_2'])) $update['payment_remark_2'] = $input['payment_remark_2'];

		if($input['statusBtn'] == 1) 
		{
			$update['processedBY'] = $this->logged_user['id'];
			$update['processedTS'] = date('Y-m-d H:i:s');
		}elseif($input['statusBtn'] == 2){
			$update['verifiedBY'] = $this->logged_user['id'];
			$update['verifiedTS'] = date('Y-m-d H:i:s');
		}elseif($input['statusBtn'] == 3){
			$update['rejectedBY'] = $this->logged_user['id'];
			$update['rejectedTS'] = date('Y-m-d H:i:s');
		}elseif($input['statusBtn'] == 4){
			$update['completedBY'] = $this->logged_user['id'];
			$update['completedTS'] = date('Y-m-d H:i:s');
		}

		$where['ID'] = $input['talentReferral_ID'];
		
		$updateTalentReferral = $this->model_general->update('sv__talent_referral',$update,$where);

		if($updateTalentReferral)
		{
			if($input['statusBtn'] == 1) $status = 'In_progress';
			elseif($input['statusBtn'] == 2) $status = 'Verified';
			elseif($input['statusBtn'] == 3) $status = 'Rejected';
			elseif($input['statusBtn'] == 4) $status = 'Completed';
			else $status = '';

			if(!empty($status)) $this->model_approval->updateOrCreateNew('sv__talent_referral',$input['talentReferral_ID'],$status,0);

			$this->session->set_flashdata('success',"Successfully update talent referral program form status. Thank you.");
		}else{
			$this->session->set_flashdata('error',"Failed to update talent referral program form status. Thank you.");
		}

		redirect('hr/serviceform/talent_referral_list');
	}

	function talent_referral_delete()
	{
		$input = $this->input->post();

		$update = array
		(
			'is_delete' => 1,
		    'updatedBY'	=> $this->logged_user['id'],
		    'updatedTS'	=> date('Y-m-d H:i:s'),
		);

		$where = array('ID' => $input['talentReferralID']);

		$updateTalentReferral = $this->model_general->update('sv__talent_referral',$update,$where);

		if($updateTalentReferral)
		{
			$this->model_approval->update_sv_status('sv__talent_referral',$input['talentReferralID']);
			
			print json_encode(array(
				"status" 	=> "Success",
				"msg"		=> "Successfully delete talent referral program form. Thank you.",
			)); 
		}else{
			print json_encode(array(
				"status" 	=> "Error",
				"msg"		=> "Failed to delete talent referral program form. Thank you.",
			)); 
		}
	}

	function getCandidateDetail()
	{
		$this->load->model('hr/model_talent_referral');
		$input = $this->input->post();

		$candidate_detail = $this->model_talent_referral->getCandidateList(array('a.id' => $input['candidate_id']));

		if($candidate_detail)
		{
			print json_encode(array(
				"status" 	=> "success",
				"result"	=> $candidate_detail[0],
				"msg"		=> "Successfully retrieved candidate detail. Thank you.",
			));
		}else{
			print json_encode(array(
				"status" 	=> "error",
				"result"	=> null,
				"msg"		=> "Failed to retrieve candidate detail. Thank you.",
			));
		}
	}

	function job_request_list()
	{
		$this->load->model('hr/model_job_request');

		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 2
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		$data = array
		(
			'page_setup'  				=> $this->template->pageSetup('Online Form', '', 'Job Request List'),
			'department'				=> $this->model_company->getDepartments(),
			'job_request_list'			=> ($module_access['access_lvl']=='admin')?$this->model_job_request->getJobRequestList():$this->model_job_request->getJobRequestList(null,$this->logged_user['id']),
			'client'					=> $this->model_crm->getCustomerDetail(),
			'branch'					=> $this->model_company->getBranches(),
		);

		$this->template->view('hr/policyprocedure/form/job_request_list', $data);
	}

	function job_request_form($ID=null, $mode=null)
	{
		$this->load->model('hr/model_job_request');

		$data = array
		(
			'page_setup'  				=> $this->template->pageSetup('Online Form', '', 'Job Request Form'),
			'department'				=> $this->model_company->getDepartments(),
			'ID'						=> $ID,
			'mode'						=> $mode,
			'job_request_list'			=> $this->model_job_request->getJobRequestList($ID)[0],
			'client'					=> $this->model_crm->getCustomer(),
		);

		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 2
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl']=='admin'){
	        if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__job_request';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'job_request_list';
	            $data_approval['form_name'] = 'Job Request Form';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__job_request','a.id_table'=>$ID));
				$data_approval['form_detail'] = $this->model_job_request->getJobRequestList($ID)[0];

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
		}

		$this->template->view('hr/policyprocedure/form/job_request_v2', $data);
	}

	function job_request_save()
	{
		$this->load->model('hr/model_job_request');
		$input = $this->input->post();

		debug($input);
		die();

		$insert = array
		(
			'requester_id'	=> $input['request_name_id'],
			'department_id'	=> $input['request_dept_id'],
			// 'client_id'		=> $input['client_id'],
			'yearEndDate'	=> $input['yearEndDate'],
			'description'	=> $input['description'],
			'remarks'		=> ($input['remarks'])?$input['remarks']:'',
			'deadline'		=> ($input['deadline'])?date('Y-m-d',strtotime($input['deadline'])):'0000-00-00',
			'createdBY'		=> $this->logged_user['id'],
		);

		$newJobRequest = $this->model_general->insert('sv__job_request',$insert);

		if(!empty($newJobRequest))
		{
			// $form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$this->input->post('request_name_id')))[0];
			// $client	= $this->model_crm->getCustomerDetail(array('a.id' => $input['client_id']))[0];

			// $form_detail = array 
			// (
			// 	'name' 					=> $this->input->post('request_name'),
			// 	'email_address'			=> ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']),
			// 	'department'			=> $this->input->post('request_dept'),
			// 	'date_request'			=> $this->input->post('datereq'),
			// 	'client_name'			=> $client->name,
			// 	'year_end'				=> $input['yearEndDate'],
			// 	'description'			=> $input['description'],
			// 	'remarks'				=> ($input['remarks'])?$input['remarks']:'N/A',
			// 	'deadline'				=> ($input['deadline'])?$input['deadline']:'N/A',
			// );

			// $user_email 	= array();
			// $admin_email 	= 'hazwani@salihin.com.my';
			
			// // array_push($user_email, $admin_email);

			// $send_email_checkbox = $input['send_email_checkbox'];

			// $send_copy_form_email = (isset($send_email_checkbox) && $send_email_checkbox == 'on')?$send_email_checkbox:'off';

			// if($send_copy_form_email == 'on')
			// {
			// 	$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			// }
			
			// $form_requestor_name 	= $this->model_user->getUserDetail($this->input->post('request_name_id'))['name'];

			// if($user_email)
			// {
			// 	$emailSubject 		= 'New Job Request - '.$form_requestor_name.' ['.str_pad($newJobRequest,5,0,STR_PAD_LEFT).']';
			// 	$emailMessage 		= $form_requestor_name.' has submit job request on '.$this->input->post('datereq').'. Below is the detail:- ';
			// 	$emailDetailForm	= $form_detail;

			// 	$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			// }

			// $this->model_approval->updateOrCreateNew('sv__job_request',$newJobRequest,'Pending',0);

			$this->session->set_flashdata('success',"Successfully add new job request. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to add new job request. Please try again.");
		}

		redirect(base_url('hr/serviceform/job_request_list'));
	}

	function job_request_edit()
	{
		$input = $this->input->post();

		$update = array
		(
			'requester_id'	=> $input['request_name_id'],
			'department_id'	=> $input['request_dept_id'],
			'client_id'		=> $input['client_id'],
			'yearEndDate'	=> $input['yearEndDate'],
			'description'	=> $input['description'],
			'remarks'		=> ($input['remarks'])?$input['remarks']:'',
			'deadline'		=> ($input['deadline'])?date('Y-m-d',strtotime($input['deadline'])):'0000-00-00',
			'updatedBY'		=> $this->logged_user['id'],
			'updatedTS'		=> date('Y-m-d H:i:s'),
		);

		$where = array('ID'=>$input['jobRequestID']);

		$updateJobRequest = $this->model_general->update('sv__job_request',$update, $where);
		
		if($updateJobRequest){
			$this->session->set_flashdata('success',"Successfully update job request. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update job request. Please try again.");
		}

		redirect(base_url('hr/serviceform/job_request_list'));
	}

	function job_request_clone()
	{
		$this->load->model('hr/model_job_request');
		$input = $this->input->post();
		$job_request_list = $this->model_job_request->getJobRequestList($input['job_request_id'])[0];

		if($job_request_list)
		{
			$insert_clone = array
			(
				'requester_id'	=> $job_request_list['requester_id'],
				'department_id'	=> $job_request_list['department_id'],
				'client_id'		=> $job_request_list['client_id'],
				'yearEndDate'	=> $job_request_list['yearEndDate'],
				'description'	=> $job_request_list['description'],
				'remarks'		=> ($job_request_list['remarks'])?$job_request_list['remarks']:'',
				'deadline'		=> ($job_request_list['deadline'])?$job_request_list['deadline']:'0000-00-00',
				'createdBY'		=> $this->logged_user['id'],
			);

			$clone_job = $this->model_general->insert('sv__job_request',$insert_clone);
		}

		if($clone_job)
		{
			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$this->logged_user['id']))[0];
			$client	= $this->model_crm->getCustomerDetail(array('a.id' => $job_request_list['client_id']))[0];

			$form_detail = array 
			(
				'name' 					=> $this->logged_user['name'],
				'email_address'			=> ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']),
				'department'			=> $this->logged_user['department_name'].' ['.$this->logged_user['branch_name'].']',
				'date_clone'			=> date('Y-m-d'),
				'client_name'			=> $client->name,
				'year_end'				=> $job_request_list['yearEndDate'],
				'description'			=> $job_request_list['description'],
				'remarks'				=> ($job_request_list['remarks'])?$job_request_list['remarks']:'N/A',
				'deadline'				=> ($job_request_list['deadline'])?$job_request_list['deadline']:'N/A',
			);

			$user_email 	= array();
			$admin_email 	= 'hazwani@salihin.com.my';
			
			// array_push($user_email, $admin_email);

			$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			
			$form_requestor_name 	= $this->model_user->getUserDetail($this->logged_user['id'])['name'];

			if($user_email)
			{
				$emailSubject 		= 'New Job Request Clone - '.$form_requestor_name.' ['.str_pad($clone_job,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $form_requestor_name.' has clone job request '.' ['.str_pad($job_request_list['ID'],5,0,STR_PAD_LEFT).'] on '.date('Y-m-d').'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->model_approval->updateOrCreateNew('sv__job_request',$clone_job,'Pending',0);
			
			print json_encode(array(
				"status" 	=> "Success",
				"msg"		=> "Successfully clone job request detail. Thank you.",
			)); 
		}else{
			print json_encode(array(
				"status" 	=> "Error",
				"msg"		=> "Failed to clone job request detail. Thank you.",
			)); 
		}
	}

	function job_request_delete()
	{
		$input = $this->input->post();

		$delete = array
		(
			'is_delete'		=> 1,
			'updatedBY'		=> $this->logged_user['id'],
			'updatedTS'		=> date('Y-m-d H:i:s'),
		);

		$deleteJobRequest = $this->model_general->update('sv__job_request',$delete,array('ID'=>$input['job_request_id']));

		if($deleteJobRequest)
		{
			$this->model_approval->update_sv_status('sv__job_request',$input['job_request_id']);

			print json_encode(array(
				"status" 	=> "Success",
				"msg"		=> "Successfully delete job request. Thank you.",
			)); 
		}else{
			print json_encode(array(
				"status" 	=> "Error",
				"msg"		=> "Failed to delete job request. Thank you.",
			)); 
		}
	}

	function client_new_resignation_list()
	{
		$this->load->model('hr/model_client_new_resignation');
		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 2
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		$data = array
		(
			'page_setup'  	=> $this->template->pageSetup('Online Form', '', 'New Client / Resignation List'),
			'department'	=> $this->model_company->getDepartments(),
			'request_list'	=> ($module_access['access_lvl'] == 'admin')?$this->model_client_new_resignation->getClientNewResignationList():$this->model_client_new_resignation->getClientNewResignationList(null, $this->logged_user['id']),
			'client'		=> $this->model_crm->getCustomerDetail(array('a.is_delete'=>0)),
			'master_client'	=> $this->model_crm->getMasterCostomerALL(),
		);

		$this->template->view('hr/policyprocedure/form/client_new_resignation_list', $data);
	}

	function client_new_resignation_form($type, $ID=null, $mode=null)
	{
		if(empty($type)) redirect(base_url('hr/serviceform/client_new_resignation_list'));
		$this->load->model('hr/model_client_new_resignation');

		$title = ($type == 1)?'New Client':'Client Resignation';
		$data = array
		(
			'page_setup'  	=> $this->template->pageSetup('Online Form', '', $title.' Form'),
			'department'	=> $this->model_company->getDepartments(),
			'ID'			=> $ID,
			'mode'			=> $mode,
			'type'			=> $type,
			'request_list'	=> $this->model_client_new_resignation->getClientNewResignationList($ID)[0],
			'client'		=> $this->model_crm->getCustomerDetail(array('a.is_delete'=>0)),
			'master_client'	=> $this->model_crm->getMasterCostomerALL(),
		);

		$filter1 = array
		(
			'a.id'			=> $this->logged_user['id'],
			'j.module_id'	=> 2
		);

		$module_access = $this->model_user->getUserByModuleAccess($filter1)[0];

		if($module_access['access_lvl']=='admin'){
	        if(!empty($ID)){
	            $data_approval['tblname'] = 'sv__client_new_resignation';
	            $data_approval['ID'] = $ID;
	            $data_approval['link'] = 'client_new_resignation_list';
	            $data_approval['form_name'] = 'New Client / Resignation Form';
	            $data_approval['rsApproval'] = $this->model_approval->getApproval(array('a.table_name'=>'sv__client_new_resignation','a.id_table'=>$ID));

	            $data['approval'] = $this->load->view('hr/policyprocedure/form/approval',$data_approval,true);
	        }
		}

		$this->template->view('hr/policyprocedure/form/client_new_resignation', $data);
	}

	function client_new_resignation_save()
	{
		$input = $this->input->post();
		$msg = ($input['type'] == 1)?'New client':'Client Resignation';

		$insert = array
		(
			'requester_id'		=> $input['request_name_id'],
			'department_id'		=> $input['request_dept_id'],
			'type'				=> $input['type'],
			'master_id'			=> ($input['type'] == 1)?(($input['master_id'])?$input['master_id']:0):0,
			'client_id'			=> ($input['type'] == 2)?$input['client_id']:0,
			'client_name'		=> ($input['type'] == 1)?$input['client_name']:'',
			'director_name'		=> ($input['type'] == 1)?(($input['director_name'])?$input['director_name']:''):'',
			'nature_business'	=> ($input['type'] == 1)?$input['nature_business']:'',
			'reason'			=> ($input['type'] == 2)?$input['reason']:'',
			'createdBY'			=> $this->logged_user['id'],
		);

		$createClientNewResignation = $this->model_general->insert('sv__client_new_resignation',$insert);

		if($createClientNewResignation)
		{
			$this->load->library('File_upload');

			$upload_directory = 'assets/upload/hr/Form/clientNewResignationForm/'.$input['type'].'/';

			$upload_status = $this->file_upload
				->set_file_type(FILE_TYPE_UPLOAD)
				->set_directory_public()
				->set_upload_directory($upload_directory)
				->uploads('picture_upload');

			if(is_array($upload_status)) 
			{
				$uploadPhoto = array
				(
					'client_new_resignation_id'     => $createClientNewResignation,
					'filename'         				=> (!empty($upload_status['file_name']))? $upload_status['file_name']:'',
					'file_location'     			=> (!empty($upload_status['file_name']))?$upload_directory:'', 
					'createdBY'						=> $this->logged_user['id'],
				);

				$newRequestAttachment = $this->model_general->insert('sv__client_new_resignation_attachment',$uploadPhoto);
			} else {
				echo 'Upload Failed. Please Try Again.';
			}

			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$this->input->post('request_name_id')))[0];
			$client	= ($input['type'] == 2)?$this->model_crm->getCustomerDetail(array('a.id' => $input['client_id']))[0]->name:$input['client_name'];

			$form_detail = array 
			(
				'name' 					=> $this->input->post('request_name'),
				'email_address'			=> ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']),
				'department'			=> $this->input->post('request_dept'),
				'date_request'			=> $this->input->post('datereq'),
				'client_name'			=> $client,
			);

			if($input['type'] == 1)
			{
				if($input['master_id']) $form_detail['group_name'] = $this->model_crm->getCustomer($input['master_id'])[0]->name;
				$form_detail['director'."'s".'_name'] = $input['director_name'];
				$form_detail['nature_of_business'] = $input['nature_business'];
			}elseif($input['type'] == 2)
			{
				$form_detail['reason_of_resignation_/_termination'] = $input['reason'];
			}

			$user_email 	= array();
			$admin_email 	= 'hazwani@salihin.com.my';
			
			// array_push($user_email, $admin_email);

			$send_email_checkbox = (isset($input['send_email_checkbox']))?$input['send_email_checkbox']:'off';

			$send_copy_form_email = (isset($send_email_checkbox) && $send_email_checkbox == 'on')?$send_email_checkbox:'off';

			if($send_copy_form_email == 'on')
			{
				$form_requestor_email 	= array_push($user_email, ($form_requestor_detail['primary_email']) ? $form_requestor_detail['primary_email'] : (($form_requestor_detail['secondary_email']) ? $form_requestor_detail['secondary_email'] : $form_requestor_detail['email']));
			}
			
			$form_requestor_name 	= $this->model_user->getUserDetail($this->input->post('request_name_id'))['name'];

			if($user_email)
			{
				$emailSubject 		= 'New '.$msg.' - '.$form_requestor_name.' ['.str_pad($createClientNewResignation,5,0,STR_PAD_LEFT).']';
				$emailMessage 		= $form_requestor_name.' has submit request '.strtolower($msg).' on '.$this->input->post('datereq').'. Below is the detail:- ';
				$emailDetailForm	= $form_detail;

				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, array_unique($user_email));
			}

			$this->model_approval->updateOrCreateNew('sv__client_new_resignation',$createClientNewResignation,'Pending',0);

			$this->session->set_flashdata('success',"Successfully request ".strtolower($msg).". Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to request ".strtolower($msg).". Please try again.");
		}

		redirect(base_url('hr/serviceform/client_new_resignation_list'));
	}

	function client_new_resignation_edit()
	{
		$input = $this->input->post();
		$msg = ($input['type'] == 1)?'New client':'Client Resignation';

		$update = array
		(
			'requester_id'		=> $input['request_name_id'],
			'department_id'		=> $input['request_dept_id'],
			'type'				=> $input['type'],
			'master_id'			=> ($input['type'] == 1)?(($input['master_id'])?$input['master_id']:0):0,
			'client_id'			=> ($input['type'] == 2)?$input['client_id']:0,
			'client_name'		=> ($input['type'] == 1)?$input['client_name']:'',
			'director_name'		=> ($input['type'] == 1)?(($input['director_name'])?$input['director_name']:''):'',
			'nature_business'	=> ($input['type'] == 1)?$input['nature_business']:'',
			'reason'			=> ($input['type'] == 2)?$input['reason']:'',
			'createdBY'			=> $this->logged_user['id'],
		);

		$where = array
		(
			'ID' => $input['clientNewResignationID'],
		);

		$updateClientNewResignation = $this->model_general->update('sv__client_new_resignation',$update,$where);

		if($updateClientNewResignation)
		{
			$this->load->library('File_upload');

			$upload_directory = 'assets/upload/hr/Form/clientNewResignationForm/'.$input['type'].'/';

			$upload_status = $this->file_upload
				->set_file_type(FILE_TYPE_UPLOAD)
				->set_directory_public()
				->set_upload_directory($upload_directory)
				->uploads('picture_upload');

			if(is_array($upload_status)) 
			{
				$updateAttachment = array
				(
					'is_delete'		=> 1,
					'updatedBY'		=> $this->logged_user['id'],
					'updatedTS'		=> date('Y-m-d H:i:s')
				);

				$whereAttachment = array
				(
					'client_new_resignation_id' => $input['clientNewResignationID'],
				);

				$updateRequestAttachment = $this->model_general->update('sv__client_new_resignation_attachment',$updateAttachment, $whereAttachment);
				
				$uploadPhoto = array
				(
					'client_new_resignation_id' 	=> $input['clientNewResignationID'],
					'filename'         				=> (!empty($upload_status['file_name']))? $upload_status['file_name']:'',
					'file_location'     			=> (!empty($upload_status['file_name']))?$upload_directory:'',
					'createdBY'						=> $this->logged_user['id'],
				);
				
				$newRequestAttachment = $this->model_general->insert('sv__client_new_resignation_attachment',$uploadPhoto);
				
			} else {
				echo 'Upload Failed. Please Try Again.';
			}

			$this->session->set_flashdata('success',"Successfully update request ".strtolower($msg).". Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to update request ".strtolower($msg).". Please try again.");
		}

		redirect(base_url('hr/serviceform/client_new_resignation_list'));
	}

	function client_new_resignation_delete()
	{
		$input = $this->input->post();

		$delete = array
		(
			'is_delete'		=> 1,
			'updatedBY'		=> $this->logged_user['id'],
			'updatedTS'		=> date('Y-m-d H:i:s'),
		);

		$deleteJobRequest = $this->model_general->update('sv__client_new_resignation',$delete,array('ID'=>$input['request_id']));

		if($deleteJobRequest)
		{
			$this->model_general->update('sv__client_new_resignation_attachment',$delete,array('client_new_resignation_id'=>$input['request_id']));
			$this->model_approval->update_sv_status('sv__client_new_resignation',$input['request_id']);

			print json_encode(array(
				"status" 	=> "Success",
				"msg"		=> "Successfully delete request. Thank you.",
			)); 
		}else{
			print json_encode(array(
				"status" 	=> "Error",
				"msg"		=> "Failed to delete request. Thank you.",
			)); 
		}
	}

	private function upload($type, $file, $file_location)
	{
		$fcpath = str_replace('\\','/',FCPATH);
		$dir = str_replace('\\','/',$fcpath.'assets/upload/'.$file_location);
		$dir = str_replace('\\','/',$dir);
		$file_name = str_replace(' ', '_', trim(addslashes(substr($_FILES[$file]['name'],-50))));
		$url = NULL;

		(!file_exists($dir))?mkdir($dir, 0777, true):chmod($dir, 0777);

		if (is_uploaded_file($_FILES[$file]['tmp_name']))
		{
			if($type == 'document') $file_types = 'pdf|doc|docx|xls|xlsx|pptx|jpg|jpeg|bmp|png';
			if($type == 'image') $file_types = 'jpg|jpeg|bmp|png|gif|svg|ico';
			// if($type == 'attachment') $file_types = 'pdf|doc|docx|jpg|jpeg|bmp|png|gif|svg|ico';

			$config = array(
				'allowed_types' => $file_types,
				'upload_path' => $dir,
				'file_name' => $file_name,
				'max_size' => 0,
				'overwrite' => TRUE
			);

			$this->load->library('upload', $config);

			if ($this->upload->do_upload($file))
			{
				if($upload_data = $this->upload->data())
				{
					if($type=="image")
					{
						// GET WIDTH & HEIGHT TO RESIZE & CROP
						$oriWidth  = (isset($upload_data['image_width']) > 0) ? $upload_data['image_width'] : 1; // ORIGINAL WIDTH
						$oriHeight = $upload_data['image_height'];											   // ORIGINAL HEIGHT
						$resWidth  = floor(($oriWidth > 500) ? 500 : $oriWidth); 							   // WIDTH TO RESIZE
						$resHeight = floor(($resWidth/$oriWidth)*$oriHeight); 								   // HEIGHT TO RESIZE

						if ($resHeight > 500)
						{
							$resWidth = floor((500/$resHeight)*$resWidth);
							$resHeight = 500;
						}

						// MANIPULATION CONFIGURATION FOR RESIZING
						$manipulate['image_library']  = 'gd2';
						$manipulate['source_image']   = $upload_data['full_path'];
						$manipulate['maintain_ratio'] = TRUE;
						$manipulate['width']     	  = $resWidth;
						$manipulate['height']   	  = $resHeight;

						$this->load->library('image_lib', $manipulate);
						$this->image_lib->resize();
					}

					$data['filename'] 	   = $upload_data['file_name'];
					$data['file_location'] = 'assets/upload/'.$file_location;
				}
				else
				{
					if($type=="image")
					{
						$data['filename'] 	   = 'default.png';
						$data['file_location'] = 'assets/upload/defaults';
					}
					
				}
			}
			else
			{
				if($type=="image")
				{
					$data['filename'] 	   = 'default.png';
					$data['file_location'] = 'assets/upload/defaults';
				}
			}
		}

		return $data;
	}

	public function test_email()
	{
		$form_detail = array();
		
		$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = 304'));

		// $form_requestor_detail 	= $this->model_user->getUsersEmails(array('c.module_id IN (2)','c.access_lvl IN ("moderator","admin")','c.status = 0','c.is_delete = 0','d.department_id IN (5,2)','d.is_delete = 0','d.status = 0'));
		
		if($form_requestor_detail)
		{
			foreach ($form_requestor_detail as $key => $value) {
				$form_requestor_email 	= ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);


				$emailSubject 		= 'Testing email by Ariff - '.date('d-m-Y H:i:s');
				$emailMessage 		= 'Testing email by Ariff - '.date('d-m-Y H:i:s');
				$emailDetailForm	= $form_detail;

				// debug($emailSubject);
				// debug($emailMessage);
				$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $form_requestor_email);
				debug($emailSend);
			}
		}
	}

	private function send_copy_email($subject = '', $message = '', $detail_form = array(), $user_email = array())
	{
		$email_data['subject'] = $subject;
		$email_data['message'] = $message;
		$email_data['emailDetailForm'] = $detail_form;
		$email_data['emails']  = [];

		if(!is_array($user_email)) 
		{
			array_push($email_data['emails'], $user_email);
		}else{
			$email_data['emails'] = $user_email;
		}

		// $hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

		// if($hr_detail) foreach($hr_detail as $hr_email) 
		// {
		// 	array_push($email_data['emails'], ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
		// }
		$this->load->library('email');
		$this->load->library('parser');
		$this->load->library('encrypt');

		$email_template = $this->load->view("template/email/header", "", true);
		$email_template .= $this->load->view("template/email/body/serviceForm", $email_data, true);
		$email_template .= $this->load->view("template/email/footer", "", true);
		
		$this->email->from('noreply@salihin.com.my')
					->to($email_data['emails'])
					->subject($subject)
					->message($email_template)
					->set_mailtype("html");
		
		// if($this->logged_user['id'] == 304) 
					$send = $this->email->send();
		// else $send = 1;

		$logEmail['userID']=$this->session->userdata('user')['id'];
		$logEmail['to']= implode(' ',$email_data['emails']);
		$logEmail['result']= $send;
		$logEmail['text']= print_r($this->email,true);
		$this->db->insert('_log__email',$logEmail);

		if($send)
		{
			$this->session->set_flashdata('success',"Successfully Send Email. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to Send Email. Please try again.");
		}

		return $send;
	}

	private function ObjToArray($obj,$single=false)
	{
		return (!empty($obj)) ? json_decode(json_encode(($single)?$obj[0]:$obj),true) : NULL;
	}

	public function complaint_list()
	{
		$year = ($this->input->post('filtered_year'))?($this->input->post('filtered_year')):date('Y');

		$data = array
		(
            'page_setup' 	=> $this->template->pageSetup('Online Form', '', 'Complaint List'),
            'count_request'	=> $this->model_complaint->getRequestByCompany($year),
            'get_hod'		=> $this->model_form->getHod($this->session->userdata('user')['department_id']),
            'department' 	=> $this->model_company->getDepartments(),
		);

		if($_SESSION['all_modules_access'][1]['access_lvl'] == 'admin'){ //CRM Admin
			$data['complaint_list']	= $this->model_complaint->getComplaintListAdmin();
		}else if($data['get_hod'][0]->hod_id == $this->logged_user['id']){
			$data['complaint_list']	= $this->model_complaint->getComplaintListHOD($this->logged_user['department_id'], $this->logged_user['id']);
		}else{
			$data['complaint_list']	= $this->model_complaint->getComplaintListUser($this->logged_user['id']);
		}

		$this->template->view('hr/policyprocedure/form/complaint_list', $data);
	}

	public function complaint_form($ID = null, $mode = '')
	{
		$data = array
		(
			'mode'				=> $mode,
			'page_setup' 		=> $this->template->pageSetup('Online Form', '', 'Complaint Form'),
			'data_ref_no'		=> $this->model_general->fetchAll('view_serial_sv__complaint', array('*'), null, null, null),
			'department' 		=> $this->model_company->getDepartments(),
			'data_client'       => $this->model_general->fetchAll('customer', array('*'), array('is_delete' => 0), null, array('name' => 'ASC')),
			'data_services'     => $this->ObjToArray($this->model_crm->services_all()),
			'data_job'     		=> $this->ObjToArray($this->model_crm->job_all()),
			'data_method'		=> $this->model_general->fetchAll('_ref__complaint_method', array('*'), null, null, array('id' => 'ASC')),
			'data_about'		=> $this->model_general->fetchAll('_ref__complaint_about', array('*'), null, null, array('id' => 'ASC'))
		);

		$this->template->view('hr/policyprocedure/form/complaint_form', $data);
	}

	public function getClientList()
	{
		$client_type = $this->input->post('client_type');

		if($client_type == 1){
			$data['client_list'] = $this->model_general->fetchAll('customer', array('*'), array('is_delete' => 0), null, array('name' => 'ASC'));
			print json_encode(array("status"=>"success", "message"=>$data['client_list']));
		}else{
			$data['client_list'] = $this->model_company->getDepartments();
			print json_encode(array("status"=>"success", "message"=>$data['client_list']));
		}
	}

	public function getClientDetails()
	{
		$client_id = $this->input->post('client_id');

		if(!empty($client_id)){
			$data['client_address'] = $this->model_general->fetchAll('customer', array('*'), array('id' => $client_id, 'is_delete' => 0), null, array('name' => 'ASC'));
			$data['client_contact']	= $this->model_general->fetchAll('customer__contact', array('*'), array('customer_id' => $client_id, 'is_delete' => 0), null, array('name' => 'ASC'));
		}

		print json_encode(array("status"=>"success", "message"=>$data));
	}

	public function getContactNo()
	{
		$contact_id = $this->input->post('contact_id');

		if(!empty($contact_id)){
			$data['client_contact']	= $this->model_general->fetchAll('customer__contact', array('*'), array('id' => $contact_id, 'is_delete' => 0), null, array('name' => 'ASC'));
		}

		print json_encode(array("status"=>"success", "message"=>$data['client_contact']));
	}

	public function getStaffDetails()
	{
		$dept_id = $this->input->post('dept_id');

		if(!empty($dept_id)){
			$data['dept_branch']	= $this->model_company->getDepartments(null, $dept_id);
			$data['staff_list'] 	= $this->model_user->getUsersByDepartment($dept_id,'Inservice');
		}

		print json_encode(array("status"=>"success", "message"=>$data));
	}

	public function getStaffContactNo()
	{
		$staff_id = $this->input->post('staff_id');

		if(!empty($staff_id)){
			$data['staff_contact'] = $this->model_user->getUsers($staff_id,null);
		}

		print json_encode(array("status"=>"success", "message"=>$data['staff_contact']));
	}

	public function saveComplaint() 
	{
		$this->load->model('CRM/model_crm');

		$insertData = array(
			'complaint_for'		=> $this->input->post('complaint_for'), 
			'ref_no'			=> $this->input->post('ref_no'),
			'dept_id' 			=> $this->input->post('dept_id'),
			'services_id'		=> $this->input->post('services_id'),
			'job_id' 			=> $this->input->post('job_id'),
			'client_id' 		=> $this->input->post('client_id'),
			'client_address' 	=> $this->input->post('client_address'),
			'contact_id' 		=> $this->input->post('contact_id'),
			'contact_name' 		=> $this->input->post('contact_name'),
			'phone_no' 			=> $this->input->post('phone_no'),
			'email' 			=> $this->input->post('email'),
			'business_impact' 	=> $this->input->post('business_impact'),
			'addressee_id' 		=> $this->input->post('addressee_id'),
			'date' 				=> date('Y-m-d',strtotime($this->input->post('date'))),
			'complaint_type' 	=> $this->input->post('complaint_type'),
			'complaint_details' => $this->input->post('complaint_details'),
			'reso_desired' 		=> $this->input->post('reso_desired'),
			'urgency' 			=> $this->input->post('urgency'),
			'created_by'		=> $this->logged_user['id']
		);

		$complaint_method 			= $this->input->post('complaint_method');
		$complaint_about 			= $this->input->post('complaint_about');
		$complaint_method_others 	= $this->input->post('complaint_method_others');
		$complaint_about_others 	= $this->input->post('complaint_about_others');
		$attachment 				= $this->input->post('attachments');

		$newComplaint = $this->model_general->insert('sv__complaint', $insertData);

		if($complaint_method){ 
			foreach ($complaint_method as $value) {
				$this->db->query("INSERT INTO sv__complaint_method (complaint_id, method_id, created_by) VALUES ('".$newComplaint."', '".$value."', '".$this->logged_user['id']."')");
			}

			if($complaint_method_others){
				$this->db->query("UPDATE sv__complaint_method SET others_details = '".$complaint_method_others."' WHERE complaint_id = '".$newComplaint."' AND method_id = 7 AND is_delete = 0");
			}
		}

		if($complaint_about){ 
			foreach ($complaint_about as $value) {
				$this->db->query("INSERT INTO sv__complaint_about (complaint_id, about_id, created_by) VALUES ('".$newComplaint."', '".$value."', '".$this->logged_user['id']."')");
			}

			if($complaint_about_others){
				$this->db->query("UPDATE sv__complaint_about SET others_details = '".$complaint_about_others."' WHERE complaint_id = '".$newComplaint."' AND about_id = 8 AND is_delete = 0");
			}
		}
 
		//add others contact to crm contact for external complaint
		if($this->input->post('complaint_for') == 1 && ($this->input->post('contact_name') != '' || $this->input->post('contact_name') != null || $this->input->post('contact_name') != 0 || $this->input->post('email') != null || $this->input->post('email') != 0)){

			$existingContact = $this->model_crm->getContactByCustomerAndName($this->input->post('client_id'), $this->input->post('contact_name')); 

			if(empty($existingContact)){

				$insertDataContact = array(
					'customer_id'	=> $this->input->post('client_id'),
					'name'			=> $this->input->post('contact_name'),
					'phone_mobile'	=> $this->input->post('phone_no'),
					'email'			=> $this->input->post('email'),
					'created_by'	=> $this->logged_user['id']
				);

				$newContact = $this->model_general->insert('customer__contact', $insertDataContact);
			}
		}

		if(!empty($newComplaint))
		{
			if(!empty($attachment))
			{	
				$batch_complaint = array();
				foreach ($attachment as $key => $att) 
				{
					$complaint_attachment 	= array
					(
						'complaint_id'			 => $newComplaint,
						'filename'		 		 => $att['orig_name'],
						'file_type'				 => $att['file_type'],
						'file_ext'				 => str_replace('.','',$att['file_ext']),
						'description'			 => $att['description'],
						'file_location'			 => 'assets/upload/hr/Form/complaintForm/',
						'unique_id'				 => uniqid(),
						'class_id'				 => 1,
						'type'					 => 0,
						'is_delete'				 => 0 
					);
					array_push($batch_complaint,$complaint_attachment);
				}
				$this->model_complaint->createAttachment($batch_complaint);
			}

			$this->complaintEmail('new_complaint', $newComplaint);

			$this->session->set_flashdata('success',"Successfully create new complaint. Thank you.");
			
			print json_encode(array(
				"status" => "success",
				"message" => $newComplaint
			));

		}else{
			$this->session->set_flashdata('error',"System failed to create new complaint.");
		}
	}

	public function complaint_form_edit($id = 0, $mode = null)
	{
		$data = array
		(
			'mode'				=> $mode,
			'page_setup' 		=> $this->template->pageSetup('Online Form', '', 'Edit Complaint Form'),
			'department' 		=> $this->model_company->getDepartments(),
			'data_client'       => $this->model_general->fetchAll('customer', array('*'), array('is_delete' => 0), null, array('name' => 'ASC')),
			'data_services'     => $this->ObjToArray($this->model_crm->services_all()),
			'data_job'     		=> $this->ObjToArray($this->model_crm->job_all()),
			'data_method'		=> $this->model_general->fetchAll('_ref__complaint_method', array('*'), null, null, array('id' => 'ASC')),
			'data_about'		=> $this->model_general->fetchAll('_ref__complaint_about', array('*'), null, null, array('id' => 'ASC'))
		);

		$data['data_complaint']			= $this->model_complaint->getComplaintListByID($id);
		$data['data_complaint_contact']	= $this->model_general->fetchAll('customer__contact', array('*'), array('is_delete' => 0, 'customer_id' => $data['data_complaint'][0]->client_id), null, array('name' => 'ASC'));
		$data['data_complaint_method']	= $this->model_general->fetchAll('sv__complaint_method', array('*'), array('is_delete' => 0, 'complaint_id' => $data['data_complaint'][0]->id), null, array('id' => 'ASC'));
		$data['data_complaint_about']	= $this->model_general->fetchAll('sv__complaint_about', array('*'), array('is_delete' => 0, 'complaint_id' => $data['data_complaint'][0]->id), null, array('id' => 'ASC'));
		$data['department_staff']		= $this->model_general->fetchAll('user__employment_detail', array('*'), array('is_delete' => 0, 'status' => 0, 'department_id' => $data['data_complaint'][0]->dept_id), null, array('name' => 'ASC'));
		$data['data_staff_contact']		= $this->model_user->getUsersByDepartment($data['data_complaint'][0]->client_id,'Inservice');
		$data['data_complaint_time']	= $this->model_general->fetchAll('sv__complaint_time_promise', array('*'), array('is_delete' => 0, 'complaint_id' => $data['data_complaint'][0]->id), null, array('id' => 'ASC'));
		$data['date_promise']			= $this->model_general->fetchAll('sv__complaint_time_promise', array('date_promise'), array('is_delete' => 0, 'complaint_id' => $data['data_complaint'][0]->id, 'time_id' => 2), null, array('id' => 'ASC'));
		$data['data_attachment_main']	= $this->model_complaint->getComplaintAttachment_main($id);
		$data['data_attachment']		= $this->model_complaint->getComplaintAttachment_reso($id);
		$data['get_hod']				= $this->model_form->getHod($data['data_complaint'][0]->dept_id);

		$this->template->view('hr/policyprocedure/form/complaint_form_edit', $data);
	}

	public function saveEditComplaint()
	{
		$complaint_id = $this->input->post('id');

		$updateData = array(
			'complaint_for'		=> $this->input->post('complaint_for'), 
			'ref_no'			=> $this->input->post('ref_no'),
			'dept_id' 			=> $this->input->post('dept_id'),
			'services_id'		=> $this->input->post('services_id'),
			'job_id' 			=> $this->input->post('job_id'),
			'client_id' 		=> $this->input->post('client_id'),
			'client_address' 	=> $this->input->post('client_address'),
			'contact_id' 		=> $this->input->post('contact_id'),
			'contact_name' 		=> $this->input->post('contact_name'),
			'phone_no' 			=> $this->input->post('phone_no'),
			'email' 			=> $this->input->post('email'),
			'business_impact' 	=> $this->input->post('business_impact'),
			'addressee_id' 		=> $this->input->post('addressee_id'),
			'date' 				=> date('Y-m-d',strtotime($this->input->post('date'))),
			'complaint_type' 	=> $this->input->post('complaint_type'),
			'complaint_details' => $this->input->post('complaint_details'),
			'reso_desired' 		=> $this->input->post('reso_desired'),
			'urgency' 			=> $this->input->post('urgency'),
			'created_by'		=> $this->logged_user['id']
		);

		$complaint_method 			= $this->input->post('complaint_method');
		$complaint_about 			= $this->input->post('complaint_about');
		$complaint_method_others 	= $this->input->post('complaint_method_others');
		$complaint_about_others 	= $this->input->post('complaint_about_others');

		$updateComplaint = $this->model_general->update('sv__complaint', $updateData, array('id' => $complaint_id));

		if($complaint_method){ 

			$this->db->query("UPDATE sv__complaint_method SET is_delete = 1 WHERE complaint_id = '".$complaint_id."'");

			foreach ($complaint_method as $value) {
				$this->db->query("INSERT INTO sv__complaint_method (complaint_id, method_id, created_by) VALUES ('".$complaint_id."', '".$value."', '".$this->logged_user['id']."')");
			}

			if($complaint_method_others){
				$this->db->query("UPDATE sv__complaint_method SET others_details = '".$complaint_method_others."' WHERE complaint_id = '".$complaint_id."' AND method_id = 7 AND is_delete = 0");
			}
		}

		if($complaint_about){ 

			$this->db->query("UPDATE sv__complaint_about SET is_delete = 1 WHERE complaint_id = '".$complaint_id."'");

			foreach ($complaint_about as $value) {
				$this->db->query("INSERT INTO sv__complaint_about (complaint_id, about_id, created_by) VALUES ('".$complaint_id."', '".$value."', '".$this->logged_user['id']."')");
			}

			if($complaint_about_others){
				$this->db->query("UPDATE sv__complaint_about SET others_details = '".$complaint_about_others."' WHERE complaint_id = '".$complaint_id."' AND about_id = 8 AND is_delete = 0");
			}
		}

		if($this->input->post('complaint_for') == 1 && ($this->input->post('contact_name') != '' || $this->input->post('contact_name') != null || $this->input->post('contact_name') != 0)){

			$existingContact = $this->model_crm->getContactByCustomerAndName($this->input->post('client_id'), $this->input->post('contact_name')); 

			if(empty($existingContact)){

				$insertDataContact = array(
					'customer_id'	=> $this->input->post('client_id'),
					'name'			=> $this->input->post('contact_name'),
					'phone_mobile'	=> $this->input->post('phone_no'),
					'email'			=> $this->input->post('email'),
					'created_by'	=> $this->logged_user['id']
				);

				$newContact = $this->model_general->insert('customer__contact', $insertDataContact);
			}
		}

		if(!empty($updateComplaint))
		{
			$this->session->set_flashdata('success',"Successfully update complaint. Thank you.");
			
			print json_encode(array(
				"status" => "success",
				"message" => $updateComplaint
			));

		}else{
			$this->session->set_flashdata('error',"System failed to update complaint.");
		}
	}

	public function saveComplaintPIC() 
	{
		$id 		= $this->input->post('id');
		$pic_id 	= $this->input->post('pic_id');
		$remarks 	= $this->input->post('remarks');

		$updatePIC = $this->db->query("UPDATE sv__complaint SET pic_id = '".$pic_id."', updated_by = '".$this->logged_user['id']."', remarks = '".$remarks."', status = 1 WHERE id = '".$id."' AND is_delete = 0");

		if(!empty($updatePIC))
		{
			$this->complaintEmail('new_pic', $id);

			$this->complaintEmail('new_pic_crm', $id);

			$this->session->set_flashdata('success',"Successfully update Person In Charge and Acknowledge Complaint.");
			
			print json_encode(array(
				"status" => "success"
			));

		}else{
			$this->session->set_flashdata('error',"System failed to update Person In Charge and Acknowledge Complaint.");
		}
	}

	public function verifyComplaint() 
	{
		$id 		= $this->input->post('id');
		$remarks 	= $this->input->post('remarks');

		$verifyComplaint = $this->db->query("UPDATE sv__complaint SET updated_by = '".$this->logged_user['id']."', remarks = '".$remarks."', status = 3 WHERE id = '".$id."' AND is_delete = 0");

		if(!empty($verifyComplaint))
		{
			$this->complaintEmail('verified_crm', $id);

			$this->session->set_flashdata('success',"Successfully verify Complaint.");
			
			print json_encode(array(
				"status" => "success"
			));

		}else{
			$this->session->set_flashdata('error',"System failed to verify Complaint.");
		}
	}

	public function complaint_reso($id = null, $mode = '')
	{
		$data = array
		(
			'mode'				=> $mode,
			'page_setup' 		=> $this->template->pageSetup('Online Form', '', 'Complaint Resolution'),
		);

		$data['data_complaint']			= $this->model_complaint->getComplaintListByID($id);
		$data['data_complaint_time']	= $this->model_general->fetchAll('sv__complaint_time_promise', array('*'), array('is_delete' => 0, 'complaint_id' => $data['data_complaint'][0]->id), null, array('id' => 'ASC'));
		$data['department_staff']		= $this->model_general->fetchAll('user__employment_detail', array('*'), array('is_delete' => 0, 'status' => 0, 'department_id' => $data['data_complaint'][0]->dept_id), null, array('name' => 'ASC'));
		$data['date_promise']			= $this->model_general->fetchAll('sv__complaint_time_promise', array('date_promise'), array('is_delete' => 0, 'complaint_id' => $data['data_complaint'][0]->id, 'time_id' => 2), null, array('id' => 'ASC'));
		$data['data_attachment']		= $this->model_complaint->getComplaintAttachment_reso($id);

		$this->template->view('hr/policyprocedure/form/complaint_reso', $data);
	}

	public function saveResolution() 
	{
		$id 	  = $this->input->post('id');
		$resolved = $this->input->post('complaint_resolved');

		$updateData = array(
			'actual_reso'		=> $this->input->post('actual_reso'), 
			'promise_made' 		=> $this->input->post('promise_made'),
			'investigate_report'=> $this->input->post('investigate_report'),
			'root_cause'		=> $this->input->post('root_cause'),
			'action_taken'		=> $this->input->post('action_taken'),
			'prevent_recurrence'=> $this->input->post('prevent_recurrence'),
			'updated_by'		=> $this->logged_user['id']
		);

		$updateResolution 		= $this->model_general->update('sv__complaint', $updateData, array('id' => $id));

		if($resolved == 1){

			$updateDataStatus = array(
				'status'		=> 2,
				'date_solved' 	=> date('Y-m-d')
			);

			$updateStatus = $this->model_general->update('sv__complaint', $updateDataStatus, array('id' => $id));

			$this->complaintEmail('resolve_crmhod', $id);
		}

		$complaint_time_promise 		= $this->input->post('time_promise');
		$complaint_time_promise_through = $this->input->post('complaint_time_promise_through');
		$complaint_time_promise_date 	= date('Y-m-d',strtotime($this->input->post('complaint_time_promise_date')));

		if($complaint_time_promise){ 

			$this->db->query("UPDATE sv__complaint_time_promise SET is_delete = 1 WHERE complaint_id = '".$id."'");

			foreach ($complaint_time_promise as $value) {
				$this->db->query("INSERT INTO sv__complaint_time_promise (complaint_id, time_id, created_by) VALUES ('".$id."', '".$value."', '".$this->logged_user['id']."')");
			}

			if($complaint_time_promise_through){
				$this->db->query("UPDATE sv__complaint_time_promise SET others_details = '".$complaint_time_promise_through."' WHERE complaint_id = '".$id."' AND time_id = 3 AND is_delete = 0");
			}

			if($complaint_time_promise_date){
				$this->db->query("UPDATE sv__complaint_time_promise SET date_promise = '".$complaint_time_promise_date."' WHERE complaint_id = '".$id."' AND time_id = 2 AND is_delete = 0");
			}
		}

		if(!empty($updateResolution))
		{
			$this->session->set_flashdata('success',"Successfully update resolution. Thank you.");
			
			print json_encode(array(
				"status" => "success"
			));

		}else{
			$this->session->set_flashdata('error',"System failed to update resolution.");
		}
	}

	public function deleteComplaint()
	{
		$complaint_id  = $this->input->post('complaint_id');

		$sets = array(
			'is_delete'   => 1,
			'updated_by'  => $this->logged_user['id']
		);

		$where = array(
			'id' => $complaint_id,
		);

		$affected_rows = $this->model_general->update('sv__complaint', $sets,$where);

		if($affected_rows){

			$sets_detail = array(
				'is_delete'   => 1,
				'updated_by'  => $this->logged_user['id']
			);

			$where_detail = array(
				'complaint_id' => $complaint_id,
			);

			$this->model_general->update('sv__complaint_about',$sets_detail,$where_detail);
			$this->model_general->update('sv__complaint_method',$sets_detail,$where_detail);
			$this->model_general->update('sv__complaint_time_promise',$sets_detail,$where_detail);

			print json_encode(array(
				"status" => "Success",
				"msg"  	 => "Successfully deleted complaint."
			)); 
		}else{
			print json_encode(array(
				"status" => "Error",
				"msg"    => "System failed to delete complaint."
			));
		}
	}

	public function approveComplaint() 
	{
		$complaint_id 	= $this->input->post('complaint_id');
		// $status 		= $this->input->post('status');

		// $clientSatiscation 	= $this->db->query("UPDATE sv__complaint SET updated_by = '".$this->logged_user['id']."', client_satisfaction = '".$status."' WHERE id = '".$complaint_id."' AND is_delete = 0");

		$approveComplaint 	= $this->db->query("UPDATE sv__complaint SET updated_by = '".$this->logged_user['id']."', status = 4 WHERE id = '".$complaint_id."' AND is_delete = 0");

		if($approveComplaint)
		{
			$this->complaintEmail('approved_crmhod', $complaint_id);

			print json_encode(array(
				"status" => "Success",
				"msg"  	 => "Successfully approve complaint."
			)); 
		}else{
			print json_encode(array(
				"status" => "Error",
				"msg"    => "System failed to approve complaint."
			));
		}
	}

	public function uploadToStorage($path,$file_name)
	{
		$config['upload_path']          = $path;
		$config['allowed_types']        = 'gif|jpg|png|doc|docx|pdf|xlsx|jpeg';
		// $config['encrypt_name'] 		= TRUE;

        $this->load->library('upload', $config);

        $data = array();

        if(!is_dir($config['upload_path'])){
        	mkdir($config['upload_path'],0777,true);
        }

        if (!$this->upload->do_upload($file_name))
        {
        	$data['status'] = false;
            $error = array('error' => $this->upload->display_errors());
            array_push($data, $error);
        }
        else
        {
        	$uploaded = $this->upload->data();
        	$uploaded['status'] = true;
        	return $uploaded;
        }
        return $data;
	}

	public function addComplaintAttachment()
	{
		$data 					= $this->uploadToStorage('./assets/upload/hr/Form/complaintForm/','files');
		$data['description']	= $this->input->post('description');
		echo json_encode($data);
		return true;
	}

	public function complaint_attachment($id)
	{
		$data = array
		(
			'page_setup' => $this->template->pageSetup('Online Form', '', 'Complaint Form')
		);

		$data['data_complaint']		= $this->model_complaint->getComplaintListByID($id);
		$data['data_attachment']	= $this->model_complaint->getComplaintAttachment_main($id);

		$this->template->view('hr/policyprocedure/form/complaint_attachment', $data);
	}

	public function upload_complaint_attachment()
	{
		if(isset($_FILES['attachment'])){

			$data = $this->input->post();

			$data_attachment 			    	= $this->upload("document", "attachment", 'hr/Form/complaintForm/');
			$data_attachment['description'] 	= $data['description'];
			$data_attachment['complaint_id']	= $data['complaint_id'];
			$data_attachment['class_id']		= $data['class_id'];
			$data_attachment['unique_id']		= uniqid();
			$data_attachment['created_by']  	= $this->logged_user['id'];

			$id = $this->model_general->insert("sv__complaint_attachment", $data_attachment);

			if($id)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Attachment uploaded successfully."
				));
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to upload attachment."
				));
			}
		}
	}

	public function delete_complaint_attachment()
	{
		$attachment_id  = $this->input->post('id');

		$sets = array(
			'is_delete'   => 1,
			'updated_by'  => $this->logged_user['id']
		);

		$where = array(
			'id' => $attachment_id,
		);

		$affected_rows = $this->model_general->update('sv__complaint_attachment', $sets,$where);

		if($affected_rows){

			print json_encode(array(
				"status" => "Success",
				"msg"  	 => "Successfully deleted complaint."
			)); 
		}else{
			print json_encode(array(
				"status" => "Error",
				"msg"    => "System failed to delete complaint."
			));
		}
	}

	public function test_email_complaint()
	{
		$get_hod		= $this->model_form->getHod(1);
		$new_crmhod 	= $this->model_user->getUserEmail($get_hod[0]->hod_id);
		$data['new_crmadmin'] 	= $this->model_user->getUsersEmails(array('c.module_id IN (2)','c.access_lvl IN ("admin")','c.status = 0','c.is_delete = 0','d.department_id IN (2)','d.is_delete = 0','d.status = 0'));
		// $data['new_crmpic'] = $this->model_user->getUsersEmails(array('b.id = 79'));
		// $data['verified_crm'] = $this->model_user->getUsersEmails(array('c.module_id IN (2)','c.access_lvl IN ("admin")','c.status = 0','c.is_delete = 0','d.department_id IN (2)','d.is_delete = 0','d.status = 0')); 
		echo $this->db->last_query();
		debug($new_crmhod['primary_email']);
		debug($data['new_crmadmin']);
	}

	public function complaintEmail($mode, $id)
	{
		if($mode == 'new_complaint'){

			$form_detail 			= array();
			$data['data_complaint']	= $this->model_complaint->getComplaintListByID($id);
			$emailSubject 			= 'New Complaint Received - [Serial No.'.str_pad($data['data_complaint'][0]->ref_no, 4,'0', STR_PAD_LEFT).'] '.$data['data_complaint'][0]->department_name.'|'.$data['data_complaint'][0]->branch_name.' by '.$data['data_complaint'][0]->client_name;
			$emailMessage 			= 'A new complaint was received for your departmental reference. Please take an appropriate action. <br> Link : '.base_url('hr/serviceform/complaint_form_edit/'.$data['data_complaint'][0]->id.'/view');
			$emailDetailForm		= $form_detail;

			$get_hod				= $this->model_form->getHod($data['data_complaint'][0]->dept_id);
			$new_complainthod 		= $this->model_user->getUserEmail($get_hod[0]->hod_id);
			$new_complaintadmin 	= $this->model_user->getUsersEmails(array('c.module_id IN (2)','c.access_lvl IN ("admin")','c.status = 0','c.is_delete = 0','d.department_id IN (2)','d.is_delete = 0','d.status = 0'));

			if($new_complainthod){
				$new_complainthod_email = ($new_complainthod['primary_email']) ? $new_complainthod['primary_email'] : (($new_complainthod['secondary_email']) ? $new_complainthod['secondary_email'] : $new_complainthod['email']);
				$emailSend 				= $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $new_complainthod_email);
			}
			
			if($new_complaintadmin)
			{
				foreach ($new_complaintadmin as $key => $value) {
					$new_complaintadmin_email 	= ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);
					$emailSend 					= $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $new_complaintadmin_email);
				}
			}

			return $id;

		} else if($mode == 'new_pic'){

			$form_detail 			= array();
			$data['data_complaint']	= $this->model_complaint->getComplaintListByID($id);
			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('b.id = '.$data['data_complaint'][0]->pic_id));

			if($form_requestor_detail)
			{
				foreach ($form_requestor_detail as $key => $value) {

					$form_requestor_email 	= ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);

					$emailSubject 		= '(PIC) New Complaint Received - [Serial No.'.str_pad($data['data_complaint'][0]->ref_no, 4,'0', STR_PAD_LEFT).'] '.$data['data_complaint'][0]->department_name.'|'.$data['data_complaint'][0]->branch_name.' by '.$data['data_complaint'][0]->client_name;
					$emailMessage 		= 'A new complaints have been received for your departmental reference and you have been appointed as the person in charge (PIC). Please take an appropriate action. <br> Link : '.base_url('hr/serviceform/complaint_form_edit/'.$data['data_complaint'][0]->id.'/view');
					$emailDetailForm	= $form_detail;

					$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $form_requestor_email);
				}
			}

			return $id;

		} else if($mode == 'resolve_crmhod'){

			$form_detail 			= array();
			$data['data_complaint']	= $this->model_complaint->getComplaintListByID($id);
			$emailSubject 			= 'Complaint Action Taken - [Serial No.'.str_pad($data['data_complaint'][0]->ref_no, 4,'0', STR_PAD_LEFT).'] '.$data['data_complaint'][0]->department_name.'|'.$data['data_complaint'][0]->branch_name.' by '.$data['data_complaint'][0]->client_name;
			$emailMessage 			= 'The action has been taken by the person in charge. Please proceed with verification. <br> Link : '.base_url('hr/serviceform/complaint_form_edit/'.$data['data_complaint'][0]->id.'/view');
			$emailDetailForm		= $form_detail;

			$get_hod					= $this->model_form->getHod($data['data_complaint'][0]->dept_id);
			$resolved_complainthod 		= $this->model_user->getUserEmail($get_hod[0]->hod_id); 
			$resolved_complaintadmin	= $this->model_user->getUsersEmails(array('c.module_id IN (2)','c.access_lvl IN ("admin")','c.status = 0','c.is_delete = 0','d.department_id IN (2)','d.is_delete = 0','d.status = 0'));

			if($resolved_complainthod){
				$resolved_complainthod_email = ($resolved_complainthod['primary_email']) ? $resolved_complainthod['primary_email'] : (($resolved_complainthod['secondary_email']) ? $resolved_complainthod['secondary_email'] : $resolved_complainthod['email']);
				$emailSend 					 = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $resolved_complainthod_email);
			}

			if($resolved_complaintadmin)
			{
				foreach ($resolved_complaintadmin as $key => $value) {
					$resolved_complaintadmin_email 	= ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);
					$emailSend 						= $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $resolved_complaintadmin_email);
				}
			}

			return $id;

		} else if($mode == 'verified_crm'){

			$form_detail 			= array();
			$data['data_complaint']	= $this->model_complaint->getComplaintListByID($id);
			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('c.module_id IN (2)','c.access_lvl IN ("admin")','c.status = 0','c.is_delete = 0','d.department_id IN (2)','d.is_delete = 0','d.status = 0'));

			if($form_requestor_detail)
			{
				foreach ($form_requestor_detail as $key => $value) {
					$form_requestor_email 	= ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);

					$emailSubject 			= 'Complaint Verified - [Serial No.'.str_pad($data['data_complaint'][0]->ref_no, 4,'0', STR_PAD_LEFT).'] '.$data['data_complaint'][0]->department_name.'|'.$data['data_complaint'][0]->branch_name.' by '.$data['data_complaint'][0]->client_name;
					$emailMessage 			= 'This complaint has been verified by HOD. Please proceed with approval. <br> Link : '.base_url('hr/serviceform/complaint_form_edit/'.$data['data_complaint'][0]->id.'/view');
					$emailDetailForm		= $form_detail;

					$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $form_requestor_email);
				}
			}

			return $id;

		} else if($mode == 'approved_crmhod'){

			$form_detail 			= array();
			$data['data_complaint']	= $this->model_complaint->getComplaintListByID($id);
			$emailSubject 			= 'Complaint Approved - [Serial No.'.str_pad($data['data_complaint'][0]->ref_no, 4,'0', STR_PAD_LEFT).'] '.$data['data_complaint'][0]->department_name.'|'.$data['data_complaint'][0]->branch_name.' by '.$data['data_complaint'][0]->client_name;
			$emailMessage 			= 'This complaint has been approved by CRM. Thank you for taking a good action. <br> Link : '.base_url('hr/serviceform/complaint_form_edit/'.$data['data_complaint'][0]->id.'/view');
			$emailDetailForm		= $form_detail;

			$get_hod				= $this->model_form->getHod($data['data_complaint'][0]->dept_id);
			$approve_complainthod 	= $this->model_user->getUserEmail(79); //$get_hod[0]->hod_id
			$approve_complaintadmin	= $this->model_user->getUsersEmails(array('c.module_id IN (2)','c.access_lvl IN ("admin")','c.status = 0','c.is_delete = 0','d.department_id IN (2)','d.is_delete = 0','d.status = 0'));

			if($approve_complainthod){
				$approve_complainthod_email 	= ($approve_complainthod['primary_email']) ? $approve_complainthod['primary_email'] : (($approve_complainthod['secondary_email']) ? $approve_complainthod['secondary_email'] : $approve_complainthod['email']);
				$emailSend 					 	= $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $approve_complainthod_email);
			}

			if($approve_complaintadmin)
			{
				foreach ($approve_complaintadmin as $key => $value) {
					$approve_complaintadmin_email 	= ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);
					$emailSend 						= $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $approve_complaintadmin_email);
				}
			}

			return $id;

		} else if($mode == 'new_pic_crm'){

			$form_detail 			= array();
			$data['data_complaint']	= $this->model_complaint->getComplaintListByID($id);
			$form_requestor_detail 	= $this->model_user->getUsersEmails(array('c.module_id IN (2)','c.access_lvl IN ("admin")','c.status = 0','c.is_delete = 0','d.department_id IN (2)','d.is_delete = 0','d.status = 0'));

			if($form_requestor_detail)
			{
				foreach ($form_requestor_detail as $key => $value) {

					$form_requestor_email 	= ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);

					$emailSubject 		= 'Complaint Assigned to PIC - [Serial No.'.str_pad($data['data_complaint'][0]->ref_no, 4,'0', STR_PAD_LEFT).'] '.$data['data_complaint'][0]->department_name.'|'.$data['data_complaint'][0]->branch_name.' by '.$data['data_complaint'][0]->client_name;
					$emailMessage 		= 'A new complaints have been to the person in charge (PIC). Please take an appropriate action. <br> Link : '.base_url('hr/serviceform/complaint_form_edit/'.$data['data_complaint'][0]->id.'/view');
					$emailDetailForm	= $form_detail;

					$emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $form_requestor_email);
				}
			}

			return $id;

		}
	}
}