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

class Staffprofiling extends MY_Controller
{
	private $isValidUser = false;

	function __construct() 
	{
		$this->load->module('template');
		$this->load->model('admin/model_user');
		$this->load->model('admin/model_company','company');
		$this->load->model('CRM/country');
		$this->load->model('CRM/general_model');
		$this->load->model('hr/model_action_type','action');
		$this->load->model('hr/model_staff_action','staffAction');
		$this->load->model('hr/model_joining_group','join');
		$this->load->model('hr/model_user_address','address');
		$this->load->model('hr/model_user_family','family');
		$this->load->model('hr/Model_user_pcb','pcb');
		$this->load->model('hr/model_academic_qualification','academic');
		$this->load->model('hr/Model_academic_qualification_attachment','academic_attach');
		$this->load->model('hr/model_personal_attachment','attachment');
		$this->load->model('hr/model_job_history','jobs');
		$this->load->model('hr/Model_professional_membership','proMember');
		$this->load->model('hr/Model_professional_membership_attachment','membership_attachment');
		$this->load->model('hr/Model_user_license','license');
		$this->load->model('hr/Model_user_license_attachment','license_attachment');
		$this->load->model('hr/Model_recognition','recognition');
		$this->load->model('hr/Model_recognition_attachment','recognition_attachment');
		$this->load->model('hr/Model_user_contract_element','contract_element');
		$this->load->model('hr/Model_basic_pay','basic_pay');
		$this->load->model('hr/Model_bank','bank'); 
		$this->load->model('hr/Model_statutory_detail','statutory_detail');
		$this->load->model('hr/Model_third_party_payment','third_party');
		$this->load->model('hr/Model_user_recurring','recurring');

		/* newly added */
		$this->load->model('hr/model_user_pursuing_study','pursuing_study');
		$this->load->model('hr/model_user_case_emergency','case_emergency');
		$this->load->model('hr/Model_user_professional_academic','professional_academic');
		$this->load->model('hr/Model_user_professional_academic_attachment','professional_academic_attachment');
		/* newly added */

		$this->load->helper('jwt_helper');
		$token = explode('.', $this->input->post('token'));
		list($headb64, $bodyb64, $cryptob64) = $token;
		$payload = json_e_decode(urlsafe_base64_decode($bodyb64));
		if(count($payload) > 0){
			$user_id = $payload[0]->user_id;
		}

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

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

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

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

		if(!empty($input['birthdate'])){
			$birthdate = DateTime::createFromFormat('d-m-Y', $input['birthdate']);
			$dob = $birthdate->format('Y-m-d');
		}else{
			$dob = null;
		}

		if(!empty($input['married_date']) && $input['marital'] == 1){
			$marrieddate = DateTime::createFromFormat('d-m-Y', $input['married_date']);
			$dom = $marrieddate->format('Y-m-d');
		}else{
			$dom = null;
		}
		
		$insert = 
		array
		(
			'ic_no'				=> $input['nric'],
			'name'				=> $input['name'],
			'title_id' 			=> $input['title'],
			'gender_id'	 		=> $input['gender'],
			'email_secondary'	=> $input['salihin_email'],
			'marital_status' 	=> $input['marital'],
			'married_date'		=> $dom,
			'hobby'				=> $input['hobby'],
			'country_id'		=> $input['country'],
			'citizen_id'		=> $input['nationality'],
			'religion_id'		=> $input['religion'],
			'race_id'			=> $input['race'],
			'birth_date'		=> $dob,
			'birth_place'		=> $input['birthplace'],
			'residential_id'	=> $input['residential']
		);

		$filter = 
		array
		(
			'id' => $input['user_id'],
		);
		$this->general_model->update('user', $insert, $filter);

		$this->updateAddress($input);

		if(!empty($input['passport_expired_date']) && !empty($input['passport_working_expired_date'])){

			$expDate = DateTime::createFromFormat('d-m-Y', $input['passport_expired_date']);
			$doe = $expDate->format('Y-m-d');

			$wexpDate = DateTime::createFromFormat('d-m-Y', $input['passport_working_expired_date']);
			$dowe = $wexpDate->format('Y-m-d');

			$insert2 = 
			array
			(
				'expired_date' 			=> $doe,
				'working_expired_date'	=> $dowe,
				'issue'					=> $input['passport_issue']
			);

			$filter2 = 
			array
			(	
				'staff_id'		=> $input['user_id'],
			);

			$this->general_model->update('user__passport',$insert2,$filter2);
		}
		

		echo json_encode($input);
		return true;
	}

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

		$data = $this->country->country_detail($input['country_id']);
		
		echo json_encode($data);return true;
	}

	function updateAddress($input)
	{
		$data = 
		array(
			'address' 	=> $input['address'],
			'postcode'	=> $input['postcode'],
			'city' 	  	=> $input['city'],
			'state_id'	=> $input['state'],
			'country_id'=> $input['country']
		);

		if(!empty($input['add_id'])){
			$filter = array
			(
				'id' => $input['add_id']
			);
			$this->general_model->update('user__address',$data,$filter);
		}else{
			$this->general_model->insert('user__address',$data);
		}
	}

	function create_workflow()
	{
		$input 		= $this->input->post();
		
		$name 		= $input['name'];
		$workflow 	= json_encode($input['workflow']);

		$data = array('name' => $name,'workflow' => $workflow);
		$id = $this->action->create_works($data);

		if($id){
			$msg = array('status' => 'success','msg' => 'Successfully create a new workflow');
		}else{
			$msg = array('status' => 'failed','msg' => 'failed to create new workflow');
		}

		echo json_encode($msg);
	}

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

		$profiling_id = 0;
		$action_efective_date = date('Y-m-d');

		if($input['uri'] == 'new_action_type' || $input['uri'] == 'mysetting' || $input['uri'] == 'setting'){
			$isNewProfiling = true;
		}else{
			$isNewProfiling = false; //editAction
			$profiling_id = $input['param'];
		}

		foreach ($input['form'] as $key => $inp) {
			
			switch ($inp['info_type']) {
				case -1:
					$action_efective_date = $inp['efective_date'];
					$this->update_ic_no($inp['ic_no'],$inp['user_id']);
					($isNewProfiling)?$profiling_id = $this->createProfiling($inp):$this->updateProfiling($inp,$profiling_id);
					if (!$profiling_id)
					{
						// die(debug($inp));
						echo json_encode(array('status' => 'error','msg' => 'Failed to create new action type, Staff Id need to be unique'));
						return true;
					}
					break;
				case 0:
					$this->updateJoining($inp,$profiling_id,$action_efective_date);
					break;
				case 1:
					$this->updateProfilingAddress($inp,$profiling_id);
					break;
				case 2:
					$this->updateFamilyInfo($inp,$profiling_id);
					break;
				case 3:
					$this->updateAcademicQualification($inp,$profiling_id);
					break;
				case 4:
					($isNewProfiling)?$this->createAddPersonalAttach($inp,$profiling_id):$this->updatePersonalAttach($inp,$profiling_id);
					break;
				case 5:
					$this->updatePrevEmployment($inp,$profiling_id);
					break;
				case 6:
					$this->updateProfessionalMembership($inp,$profiling_id);
					break;
				case 7:
					$this->updateProfessionalLicense($inp,$profiling_id);
					break;
				case 8:
					$this->updateRecognition($inp,$profiling_id);
					break;
				case 9:
					$this->updateContractElement($inp,$profiling_id);
					break;
				case 10:
					$this->updateBasicPay($inp,$profiling_id);
					break;
				case 11:
					$this->updateBankDetail($inp,$profiling_id);
					break;
				case 12:
					($isNewProfiling)?$this->createStatutoryDetail($inp,$profiling_id):$this->updateStatutoryDetail($inp,$profiling_id);
					break;
				case 13:
					$this->updateRecurring($inp,$profiling_id);
					break;
				case 14:
					$this->updateThirdParty($inp,$profiling_id);
					break;
				case 16:
					$this->updateEducationInProgress($inp,$profiling_id);
					break;
				case 17:
					$this->updateEmergencyContact($inp,$profiling_id);
					break;
				case 18:
					$this->updateProfessionalAcademic($inp,$profiling_id,0);
					break;
				case 19:
					$this->updateProfessionalAcademic($inp,$profiling_id,1);
					break;				
				default:	
					break;
			}/*end : switch statement */
		}

		/*
			- remove existing value
		*/
		echo json_encode(array('status' => 'success','msg' => 'You have create a new action for this user'));
		return true;
	}

	function remove_workflow()
	{
		$id = $this->input->post('work_id');

		$this->action->removeWorkflow($id);
		echo json_encode(array('status' => 'success','msg' => 'You have remove a workflow from your list'));
		return true;
	}

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


		$this->staffAction->removeAction($input['id']);
		$data = array(
			'status'	=> 'Success',
			'msg'		=> 'You have remove one item.',
			);

		echo json_encode($input);
		return true;
	}

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

		$config['upload_path']          = APPPATH.'/storage/hr/profiling/'.$input['staff_id'].'/'.$input['infotype'];
		$config['allowed_types']        = 'gif|jpg|png|doc|docx|pdf|xlsx';

        $this->load->library('upload', $config);

        if(!is_dir($config['upload_path'])){
        	mkdir($config['upload_path'],0777,true);
        }

        if (!$this->upload->do_upload('attachment'))
        {
            $error = array('error' => $this->upload->display_errors());
            echo json_encode($error);return true;
        }
        else
        {
        	echo json_encode($this->upload->data());return true;
        }
	}

	private function createProfiling($input)
	{	
		$user_profiling = $this->staffAction->fetchAction(null, $input['user_id'],date('Y-m-d',strtotime($input['efective_date'])));
		$staff_dept_id 	= $this->join->fetchJoiningGroup(null,null,0, $input['user_id'])[0]->personnel_area_id;

		/**
		* check if have department
		*/
		if($staff_dept_id)
		{
			if($staff_dept_id == 1 || $staff_dept_id == 4 || $staff_dept_id == 5) //for mysa
			{
				$ext_no_front = '03-61871426/';
			}else{
				$ext_no_front = '03-61859970/';
			}
		}else{
			$ext_no_front = '03-61859970/';
		}

		/**
		* if latest data, update staff_id if it is not matched with any other person	
		*/
		if(empty($user_profiling)){
			$user = $this->model_user->getUsersByFilter(array('a.id !=' => $input['user_id'],'a.staff_id' => $input['staff_id']));
			if(empty($user)){
				$this->model_user->updateUser($input['user_id'],array('staff_id' => $input['staff_id']));	
			}else{
				return false; 
				//give error message and stop the process if input data is latest but staff_id is not unique
			}
		}

		$data = array(
			'user_id' 					=> $input['user_id'],
			'staff_id'					=> (!empty($input['staff_id']))?$input['staff_id']:null,
			'title_id'					=> (!empty($input['title']))?$input['title']:null,
			'gender_id'					=> (!empty($input['gender']))?$input['gender']:null,
			'ic_no'						=> (!empty($input['ic_no']))?$input['ic_no']:null,
			'passport_expired_date' 	=> (!empty($input['passport_expired_date']))?date('Y-m-d',strtotime($input['passport_expired_date'])):null,
			'working_expired_date'		=> (!empty($input['working_expired_date']))?date('Y-m-d',strtotime($input['working_expired_date'])):null,
			'place_issue'				=> (!empty($input['passport_issued_country']))?$input['passport_issued_country']:null,
			'birth_date'				=> (!empty($input['birth_date']))?date('Y-m-d',strtotime($input['birth_date'])):null,
			'birth_place'				=> (!empty($input['birth_place']))?$input['birth_place']:null,
			'hobby'						=> (!empty($input['hobby']))?$input['hobby']:null, //tak masuk
			'citizen_id'				=> (!empty($input['nationality']))?$input['nationality']:null,
			'religion_id'				=> (!empty($input['religion']))?$input['religion']:null,
			'race_id'					=> (!empty($input['race']))?$input['race']:null,
			'residential_id'			=> (!empty($input['residential_status']))?$input['residential_status']:null,
			'marital_status'			=> (!empty($input['marital_status']))?$input['marital_status']:null,
			'married_date'				=> (!empty($input['married_date']))?date('Y-m-d',strtotime($input['married_date'])):null,
			'primary_email'				=> (!empty($input['primary_email']))?$input['primary_email']:null,
			'secondary_email'			=> (!empty($input['secondary_email']))?$input['secondary_email']:null,
			'action_type_id'			=> $input['action_type'],
			'action_efective_date'		=> (!empty($input['efective_date']))?date('Y-m-d',strtotime($input['efective_date'])):null,
			'phone'						=> $input['staff_phone'],
			'ext_no'					=> (!empty($input['staff_ext_no']))?$ext_no_front.''.$input['staff_ext_no']:null,
			'created_by'				=> $this->session->userdata('user')['id'],
			'is_delete'					=> 0
		);

		/* update by Ariff 17/12/2020 */
		// if($input['action_type'] == 12 || $input['action_type'] == 13 || $input['action_type'] == 14 )
		// {
		// 	$update_user_access = array
		// 	(
		// 		'is_delete'		=> 1,
		// 		// 'status'		=> 1,
		// 		'deleted_by'	=> $this->session->userdata('user')['id'],
		// 		'deleted_ts'	=> date('Y-m-d H:i:s')
		// 	);

		// 	$this->model_general->update('user__login', $update_user_access, array('user_id' => $input['user_id']));
		// 	$this->model_user->updateUser($input['user_id'],$update_user_access);
		// }
		// else{
		// 	$update_user_access = array
		// 	(
		// 		'is_delete'		=> 0,
		// 		// 'status'		=> 0,
		// 		'updated_by'	=> $this->session->userdata('user')['id'],
		// 		'updated_ts'	=> date('Y-m-d H:i:s')
		// 	);

		// 	$this->model_general->update('user__login', $update_user_access, array('user_id' => $input['user_id']));
		// 	$this->model_user->updateUser($input['user_id'],$update_user_access);	
		// }

		return $this->staffAction->registerProfiling($data);
	}

	private function updateProfiling($input,$profiling_id)
	{
		$user_profiling = $this->staffAction->fetchAction(null, $input['user_id'],date('Y-m-d',strtotime($input['efective_date'])));
		$staff_dept_id 	= $this->join->fetchJoiningGroup(null,null,0, $input['user_id'])[0]->personnel_area_id;

		/**
		* check if have department
		*/
		if($staff_dept_id)
		{
			if($staff_dept_id == 1 || $staff_dept_id == 4 || $staff_dept_id == 5) //for mysa
			{
				$ext_no_front = '03-61871426/';
			}else{
				$ext_no_front = '03-61859970/';
			}
		}else{
			$ext_no_front = '03-61859970/';
		}
		
		/*
		* if latest data, update staff_id no if it is not matched with any other person
		* TODO:  ic tak update
		*/
		if(empty($user_profiling)){
			$user = $this->model_user->getUsersByFilter(array('a.id !=' => $input['user_id'],'a.staff_id' => $input['staff_id']));
			if(empty($user)){
				$this->model_user->updateUser($input['user_id'],array('staff_id' => $input['staff_id']));
			}else{
				return false;
				//give error message and stop the process if input data is latest but staff_id is not unique
			}
		}


		$inputs = array(
			'staff_id' 					=> $input['staff_id'],
			'title_id'					=> (!empty($input['title']))?$input['title']:null,
			'gender_id'					=> (!empty($input['gender']))?$input['gender']:null,
			'ic_no'						=> (!empty($input['ic_no']))?$input['ic_no']:null,
			'passport_expired_date' 	=> (!empty($input['passport_expired_date']))?date('Y-m-d',strtotime($input['passport_expired_date'])):null,
			'working_expired_date'		=> (!empty($input['working_expired_date']))?date('Y-m-d',strtotime($input['working_expired_date'])):null,
			'place_issue'				=> (!empty($input['passport_issued_country']))?$input['passport_issued_country']:null,
			'birth_date'				=> (!empty($input['birth_date']))?date('Y-m-d',strtotime($input['birth_date'])):null,
			'birth_place'				=> (!empty($input['birth_place']))?$input['birth_place']:null,
			'hobby'						=> (!empty($input['hobby']))?$input['hobby']:null,
			'citizen_id'				=> (!empty($input['nationality']))?$input['nationality']:null,
			'religion_id'				=> (!empty($input['religion']))?$input['religion']:null,
			'race_id'					=> (!empty($input['race']))?$input['race']:null,
			'residential_id'			=> (!empty($input['residential_status']))?$input['residential_status']:null,
			'marital_status'			=> (!empty($input['marital_status']))?$input['marital_status']:null,
			'married_date'				=> (!empty($input['married_date']))?date('Y-m-d',strtotime($input['married_date'])):null,
			'primary_email'				=> (!empty($input['primary_email']))?$input['primary_email']:null,
			'secondary_email'			=> (!empty($input['secondary_email']))?$input['secondary_email']:null,
			'action_type_id'			=> $input['action_type'],
			'action_efective_date'		=> (!empty($input))?date('Y-m-d',strtotime($input['efective_date'])):null,
			'phone'						=> $input['staff_phone'],
			'ext_no'					=> (!empty($input['staff_ext_no']))?$ext_no_front.''.$input['staff_ext_no']:null,
			'updated_by'				=> $this->session->userdata('user')['id'],
		);

		/* update by Ariff 17/12/2020 */
		// if($input['action_type'] == 12 || $input['action_type'] == 13 || $input['action_type'] == 14 )
		// {
		// 	$update_user_access = array
		// 	(
		// 		'is_delete'		=> 1,
		// 		// 'status'		=> 1,
		// 		'deleted_by'	=> $this->session->userdata('user')['id'],
		// 		'deleted_ts'	=> date('Y-m-d H:i:s')
		// 	);

		// 	$this->model_general->update('user__login', $update_user_access, array('user_id' => $input['user_id']));
		// 	$this->model_user->updateUser($input['user_id'],$update_user_access);
		// }
		// else{
		// 	$update_user_access = array
		// 	(
		// 		'is_delete'		=> 0,
		// 		// 'status'		=> 0,
		// 		'updated_by'	=> $this->session->userdata('user')['id'],
		// 		'updated_ts'	=> date('Y-m-d H:i:s')
		// 	);

		// 	$this->model_general->update('user__login', $update_user_access, array('user_id' => $input['user_id']));
		// 	$this->model_user->updateUser($input['user_id'],$update_user_access);	
		// }

		$this->staffAction->updateProfiling($inputs,$profiling_id);
	}

	private function updateJoining($input,$profiling_id,$action_efective_date)
	{
		// die(debug($input));
		$datagrade = (!empty($input['hiring_position']))? $this->model_general->fetchSingle('company__position', array('grade'), array('id' => $input['hiring_position'])):'';

		$data = array(
			'profiling_id' 			=> $profiling_id,
			'date_join'				=> (!empty($action_efective_date))?date('Y-m-d',strtotime($action_efective_date)):null,
			'reason_id'				=> (!empty($input['hiring_reason']))?$input['hiring_reason']:'',
			'position_id'			=> (!empty($input['hiring_position']))?$input['hiring_position']:'',
			'position_information'	=> (!empty($input['position_information']))?$input['position_information']:'',
			// 'employee_grade'		=> (!empty($input['employee_grade']))?$input['employee_grade']:'',
			'employee_grade'		=> $datagrade['grade'],
			'user_reporting_id'		=> (!empty($input['reporting_to']))?$input['reporting_to']:'',
			'business_entity_id'	=> (!empty($input['business_entity']))?$input['business_entity']:'',
			'branch_id'				=> (!empty($input['branch']))?$input['branch']:'',
			'personnel_area_id'		=> (!empty($input['personnel_area']))?$input['personnel_area']:'',
			'personal_subarea_id'	=> (!empty($input['personal_subarea']))?$input['personal_subarea']:'',
			'employee_group_id'		=> (!empty($input['emp_group']))?$input['emp_group']:'',
			'contract_element_id'	=> (!empty($input['contract_type']))?$input['contract_type']:'',
			'employee_subgroup_id'	=> (!empty($input['emp_subgroup']))?$input['emp_subgroup']:'',
			'is_active'				=> (!empty($input['status']))?$input['status']:'',
			'is_delete'				=> 0,
		);

		$join_group = $this->join->fetchJoiningGroup(null,$profiling_id,0);
		if($join_group){
			$this->join->updateJoin($data,$profiling_id);
		}else{
			$this->join->createJoin($data);
		}
	}

	private function update_ic_no($ic_no,$user_id)
	{
		$this->model_user->updateUser($user_id,array('ic_no' => preg_replace('/[^a-zA-Z0-9]/','', $ic_no)));
	}
	

	private function updateProfilingAddress($input,$profiling_id)
	{
		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;

		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$user_address = $this->address->fetchAddress(null,false,$profiling_id);
		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) {
			$data = array(
				'profiling_id' 	=> $profiling_id,
				'user_id'		=> $inpt['user_id'],
				'type' 			=> $inpt['type'],
				'address'		=> $inpt['address'],
				'postcode'		=> $inpt['postcode'],
				'city'			=> $inpt['city'],
				'state_id'		=> $inpt['state'],
				'country_id'	=> $inpt['country'],
				'contact_no'	=> $inpt['contact_header'].$inpt['contact_number'],
				'is_delete'		=> 0,
				);
			if(!empty($inpt['id']) && $flag)
			{				
				if(!empty($user_address))foreach ($user_address as $key => $orig_address) {

					if($inpt['id'] == $orig_address->id){
						array_splice($user_address, $key,1);
					}
				}
				$this->address->editAddress($data,$inpt['id']);
			}else{
				$this->address->createAddress($data);
			}
		}

		//remove remaining address from the list
		if(!empty($user_address)) foreach ($user_address as $key => $orig_address){
			$delete = array(
				'is_delete' 		=> 1,
			);
			$this->address->editAddress($delete,$orig_address->id);
		}
	}

	private function updateFamilyInfo($input,$profiling_id)
	{
		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;
		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$family_info = $this->family->fetchFamilyInfo(null, false, $profiling_id);

		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) {
			
			$data = array(
				'profiling_id' 			=> $profiling_id,
				'staff_id'				=> $inpt['user_id'],
				'name'					=> $inpt['name'],
				'ic_no'					=> $inpt['ic_no'],
				'relation'				=> $inpt['relation'],
				'birthdate'				=> (!empty($inpt['birthdate']))?date('Y-m-d',strtotime($inpt['birthdate'])):null,
				'phone_no'				=> $inpt['contact_header'].$inpt['contact_no'],
				'email'					=> $inpt['email'],
				'address'				=> $inpt['address'],
				'oku_status'			=> $inpt['oku_status'],
				'study_status'			=> $inpt['student_status'],
				'academic_lavel'		=> $inpt['academic_level'],
				'academic_institution'	=> $inpt['academic_institution'],
				'occupation'			=> $inpt['occupation'],
				'is_delete'				=> 0,
			);

			if(!empty($inpt['id']) && $flag){
				$this->family->editFamily($data,$inpt['id']);
				if(!empty($family_info))foreach ($family_info as $key => $family) {
					if ($inpt['id'] === $family->id) {
						array_splice($family_info, $key,1);
					}
				}

			}else{ //create new family information and check for it pcb consideration
				$family_id = $this->family->createFamily($data);
				if($family_id && !empty($inpt['pcb_consideration'])){
					$pcb_array = array(
						'user_id' 			=> $inpt['user_id'],
						'profiling_id'		=> $profiling_id,
						'family_id'			=> $family_id,
						'responsible_id'	=> $inpt['responsibility'],
						'status'			=> 0,
						'is_delete'			=> 0,
					);
					$this->pcb->createPCB($pcb_array);
				}
			}
		}

		if(!empty($family_info)) foreach ($family_info as $key => $family) {
			$delete = array(
				'is_delete' => 1,
			);
			$this->family->removeFamily($delete,$family->id);
		}
	}

	private function updateAcademicQualification($input,$profiling_id)
	{
		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;
		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$academic_qualification = $this->academic->fetchQualification(null,false,$profiling_id);
	
		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) {
			// die(debug($inpt));
			$data = array(
				'profiling_id'  => $profiling_id,
				'user_id' 		=> $inpt['user_id'],
				'level_id'		=> $inpt['level_id'],
				'program'		=> $inpt['program'],
				'institution'	=> $inpt['institution'],
				'year'			=> $inpt['year'],
				'cgpa'			=> $inpt['cgpa'],
				'is_delete'		=> 0,	
				);

			if(!empty($inpt['id']) && $flag){
				$this->academic->editQualification($data, $inpt['id']);

				if(!empty($academic_qualification)) foreach ($academic_qualification as $key => $qualification){
					if ($inpt['id'] == $qualification->id) {
						array_splice($academic_qualification,$key,1);
					}
				}

				$academic_id = $inpt['id'];
			}else{
				$academic_id = $this->academic->createQualification($data);
			}

			$attachment = json_decode($inpt['table']);
			if(!empty($attachment)){ //to avoid error in edit when there is no error message ..keep this hack first
				if(empty($attachment->error) && $academic_id){ //when uploading content is failed during create new
					$attach = array(
						'user_id'						=> $inpt['user_id'],
						'academic_qualification_id'		=> $academic_id,
						'attachment_name'				=> $attachment->file_name,
						'location'						=> 'application/storage/hr/profiling/'.$inpt['user_id'].'/qualifications/'.$attachment->file_name,
						'file_type'						=> $attachment->file_type,
						'file_ext'						=> $attachment->file_type,
						'mask_id'						=> 'infotype_'.date('Ymd').'_'.uniqid(),
						'is_delete'						=> 0
					);
					$this->academic_attach->createAttachment($attach);
				}
			}
		}

		if(!empty($academic_qualification)) foreach ($academic_qualification as $key => $qualification){
			$delete = array(
				'is_delete' => 1
			);
			$this->academic->editQualification($delete, $qualification->id);
		}
	}

	private function createAddPersonalAttach($input,$profiling_id)
	{
		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) {
			$attachment = json_decode($inpt['table']);

			if(!empty($attachment)){ //to avoid error in edit when there is no error message.. keep this hack first 
				$data = array(
					'profiling_id' 		=> $profiling_id,
					'user_id'  			=> $inpt['user_id'],
					'detail'			=> $inpt['detail'],
					'description'		=> $inpt['description'],
					'attachment_name'	=> (empty($attachment->error))?$attachment->file_name:'',
					'location'			=> (empty($attachment->error))?'application/storage/hr/profiling/'.$inpt['user_id'].'/'.$attachment->file_name:'',
					'file_type'			=> (empty($attachment->error))?$attachment->file_type:'',
					'file_ext'			=> (empty($attachment->error))?$attachment->file_type:'',
					'mask_id'			=> 'infotype_'.date('Ymd').'_'.uniqid(),
				);
				$personal_id = $this->attachment->createPersonalAttachment($data);
			}
		}
	}

	private function updatePersonalAttach($input,$profiling_id)
	{
		$personal_data = $this->attachment->fetchPersonalAttachment(null,null,false,$profiling_id);

		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) {
			$attachment = json_decode($inpt['table']);

			if(!empty($attachment)){
				$data = array(
					'profiling_id'		=> $profiling_id,
					'user_id'			=> $inpt['user_id'],
					'detail'			=> $inpt['detail'],
					'description'		=> $inpt['description'],
					'attachment_name'	=> (empty($attachment->error))?$attachment->file_name:'',
					'location'			=> (empty($attachment->error))?'application/storage/hr/profiling/'.$inpt['user_id'].'/'.$attachment->file_name:'',
					'file_type'			=> (empty($attachment->error))?$attachment->file_type:'',
					'file_ext'			=> (empty($attachment->error))?$attachment->file_type:'',
					'mask_id'			=> (!empty($attachment->mask_id))?$attachment->mask_id:'infotype_'.date('Ymd').'_'.uniqid(),
				);

				if(!empty($inpt['id'])){ //edit
					if(!empty($personal_data)) foreach ($personal_data as $key => $pdata){
						if($inpt['id'] == $pdata->id){
							array_splice($personal_data, $key,1);
						}
					}
					$this->attachment->editPersonalAttachment($data, $inpt['id'], null);
				}else{ //create new
					$this->attachment->createPersonalAttachment($data);
				}
			}
		}

		if(!empty($personal_data)) foreach ($personal_data as $key => $pdata) {
			$delete = array('is_delete' => 1);
			$this->attachment->editPersonalAttachment($delete, $pdata->id,null);
		}
	}

	private function updatePrevEmployment($input,$profiling_id)
	{
		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;
		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$job_history = $this->jobs->fetchJobHistory(null,false,$profiling_id);
		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) 
		{	
			
			$data = array(
				'profiling_id' 		=> $profiling_id,
				'user_id'			=> $inpt['user_id'],
				'employer_name' 	=> $inpt['employer_name'],
				'employer_address'	=> $inpt['employer_address'],
				'position'			=> $inpt['position'],
				// 'date_enter'		=> date('Y-m-d',strtotime($inpt['date_enter'])),
				// 'date_exit'		=> date('Y-m-d',strtotime($inpt['date_exit'])),
				'date_enter'		=> (!empty($inpt['date_enter']))?date('Y-m-d',strtotime($inpt['date_enter'])):null,
				'date_exit'			=> (!empty($inpt['date_exit']))?date('Y-m-d',strtotime($inpt['date_exit'])):null,
				'length_of_service'	=> $inpt['length_of_service'],
				'description'		=> $inpt['description'],
				'is_delete'			=> 0
			);
			// var_dump($data);
			// exit();

			if(!empty($inpt['id']) && $flag)
			{
				if(!empty($job_history)) foreach ($job_history as $key => $job) 
				{
					if($job->id == $inpt['id'])
					{
						array_splice($job_history,$key,1);
					}	
				}
				$this->jobs->editJobs($data,$inpt['id']);
			}else
			{
				$this->jobs->createJobs($data);
			}
		}

		if(!empty($job_history)) foreach ($job_history as $key => $job) 
		{
			$delete = array('is_delete' => 1);
			$this->jobs->editJobs($delete,$job->id);	
		}
	}

	private function updateProfessionalMembership($input,$profiling_id)
	{

		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;
		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$professional_membership = $this->proMember->fetchMembership(null,false,$profiling_id);

		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) {
			$attachment = json_decode($inpt['table']);

			$data = array(
				'profiling_id'			=> $profiling_id,
				'user_id'				=> $inpt['user_id'],
				'professional_body'		=> $inpt['professional_body'],
				'certificate'			=> $inpt['certificate'],
				'membership'			=> $inpt['membership'],
				'membership_no'			=> $inpt['membership_no'],
				'year'					=> $inpt['year'],
			);

			if(!empty($inpt['id']) && $flag){
				$this->proMember->editMembership($data,$inpt['id']);

				if(!empty($professional_membership)) foreach ($professional_membership as $key => $membership) {
					if($inpt['id'] == $membership->id){
						array_splice($professional_membership,$key,1);
					}
				}

				$professional_membership_id = $inpt['id'];
			}else{
				$professional_membership_id = $this->proMember->createMembership($data);
			}
			
			if(!empty($attachment)){
				if(empty($attachment->error) && $professional_membership_id){
					$attach = array(
						'user_id' => $inpt['user_id'],
						'professional_membership_id' => $professional_membership_id,
						'attachment_name' => $attachment->file_name, 
						'location' => 'application/storage/hr/profiling/'.$inpt['user_id'].'/membership/'.$attachment->file_name,
						'file_type' => $attachment->file_type,
						'file_ext' => $attachment->file_type,
						'mask_id'	=> 'infotype_'.date('Ymd').'_'.uniqid(),
						'is_delete' => 0,
						);	
					$this->membership_attachment->createAttachment($attach);
				}
			}
		}

		if(!empty($professional_membership)) foreach ($professional_membership as $key => $membership) {
			$delete = array('is_delete' => 1);
			$this->proMember->editMembership($delete,$membership->id);
		}
	}

	private function updateProfessionalLicense($input,$profiling_id)
	{
		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;
		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$licenses = $this->license->fetchLicense(null,null,null,false,$profiling_id);

		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) 
		{
			$attachment = json_decode($inpt['table']);

			$data = array(
				'user_id'					=> $inpt['user_id'],
				'profiling_id' 				=> $profiling_id,
				'profession'				=> $inpt['profession'],
				'license_no'				=> $inpt['license_no'],
				'license_body_authority'	=> $inpt['license_body_authority'],
				// 'register_date' => date('Y-m-d',strtotime($inpt['register_date'])),
				// 'renewal_date'  => date('Y-m-d',strtotime($inpt['renewal_date'])),
				'register_date' 			=> (!empty($inpt['register_date']))?date('Y-m-d',strtotime($inpt['register_date'])):null,
				'renewal_date'  			=> (!empty($inpt['renewal_date']))?date('Y-m-d',strtotime($inpt['renewal_date'])):null,
				'next_renewal_date'  		=> (!empty($inpt['next_renewal_date']))?date('Y-m-d',strtotime($inpt['next_renewal_date'])):null,
			);

			if(!empty($inpt['id']) && $flag)
			{

				if(!empty($licenses)) foreach ($licenses as $key => $license) 
				{
					if($inpt['id'] == $license->id)
					{
						array_splice($licenses,$key,1);
					}
				}

				$this->license->editLicense($data,$inpt['id']);
				$license_id = $inpt['id'];
			}else
			{
				$license_id = $this->license->createLicense($data);
			}

			if(!empty($attachment)){ //to avoid error during edit mode because there is no error message..keep this hack first.
				if(empty($attachment->error) && $license_id){
					$attach = array(
						'user_id' 			=> $inpt['user_id'],
						'license_id' 		=> $license_id,
						'attachment_name'	=> $attachment->file_name,
						'location'			=> 'application/storage/hr/profiling/'.$inpt['user_id'].'/license/'.$attachment->file_name,
						'file_type'			=> $attachment->file_type,
						'file_ext'			=> $attachment->file_type,
						'mask_id'			=> 'infotype_'.date('Ymd').'_'.uniqid(),
						'is_delete'			=> 0,
					);
					$this->license_attachment->createAttachment($attach);
				}
			}
		}

		if(!empty($licenses)) foreach ($licenses as $key => $license) {
			$delete = array('is_delete' => 1);
			$this->license->editLicense($delete,$license->id);
		}
	}

	private function updateRecognition($input,$profiling_id)
	{
		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;
		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$recognitions = $this->recognition->fetchRecognition(null,false, $profiling_id);

		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) 
		{
			$attachment = json_decode($inpt['table']);
			$data = array(
				'profiling_id'	 => $profiling_id,
				'user_id'		 => $inpt['user_id'],
				'achievement'	 => $inpt['achievement'],
				'award'			 => $inpt['award'],
				'year'			 => $inpt['year'],
			);
			if(!empty($inpt['id']) && $flag)
			{

				if(!empty($recognitions)) foreach ($recognitions as $key => $recognition) 
				{
					if($inpt['id'] == $recognition->id)
					{
						array_splice($recognitions,$key,1);
					}
				}

				$this->recognition->editRecognition($data,$inpt['id']);
			}else{
				$recognition_id = $this->recognition->createRecognition($data);
			}
			
			if(!empty($attachment))
			{
				if(empty($attachment->error) && $recognition_id)
				{
					$attach = array(
						'user_id' 			=> $inpt['user_id'],
						'recognition_id'	=> $recognition_id,
						'attachment_name'	=> $attachment->file_name,
						'location'			=> 'application/storage/hr/profiling/'.$inpt['user_id'].'/recognition/'.$attachment->file_name,
						'file_type'			=> $attachment->file_type,
						'file_ext'			=> $attachment->file_type,
						'mask_id'			=> 'infotype_'.date('Ymd').'_'.uniqid(),
						'is_delete'			=> 0,
						 );
					$this->recognition_attachment->createAttachment($attach);
				}
			}
		}

		if(!empty($recognitions)) foreach ($recognitions as $key => $recognition) {
			$delete = array('is_delete' => 1);
			$this->recognition->editRecognition($delete,$recognition->id);
		}
	}

	private function updateContractElement($input,$profiling_id)
	{
		$isInsert = $this->contract_element->fetchContract(null,false,$profiling_id);

		$data = array(
			'profiling_id' 				=> $profiling_id,
			'user_id'					=> $input['user_id'],
			'contract_hiring_type_id'	=> $input['contract_type'],
			'confirmation'				=> $input['confirmation'],
			'duration'					=> (!empty($input['duration']))?$input['duration']:0,
			// 'confirmation_date'			=> date('Y-m-d',strtotime($input['confirmation_date'])),
			'confirmation_date'			=> (!empty($input['confirmation_date']))?date('Y-m-d',strtotime($input['confirmation_date'])):null,
			'probation'					=> $input['probationary_period'],
			'probation_duration'		=> $input['probationary_period_type'],
			'er_notice'					=> $input['employer_notice_period'],
			'er_notice_duration'		=> $input['employer_notice_period_type'],
			'ee_notice'					=> $input['employee_notice_period'],
			'ee_notice_duration'		=> $input['employee_notice_period_type'],
			'resign_date'				=> (!empty($input['resign_date']))?date('Y-m-d',strtotime($input['resign_date'])):null,
			'last_working_date' 		=> (!empty($input['last_working_date']))?date('Y-m-d',strtotime($input['last_working_date'])):null,
			'phy_last_working_date' 	=> (!empty($input['phy_last_working_date']))?date('Y-m-d',strtotime($input['phy_last_working_date'])):null,
		);

		// die(debug($data)); 

		if(!empty($isInsert)){
			$this->contract_element->updateContract($data,null,$profiling_id);
		}else{
			$this->contract_element->createContract($data);
		}
	}

	private function updateBasicPay($input,$profiling_id)
	{
		$isInsert = $this->basic_pay->fetchBasicPay(null,false,$profiling_id);

		$data = array(
			'user_id' 			=> $input['user_id'],
			'profiling_id'		=> $profiling_id,
			// 'scale_group'		=> $input['scale_group'],
			'staff_grade_id'	=> $input['scale_group'],
			'amount'			=> $input['amount'],
			'start_date'		=> date('Y-m-d',strtotime($input['start_date'])),
			'end_date'			=> (!empty($input['end_date']))?date('Y-m-d',strtotime($input['end_date'])):null,
			'reason'			=> $input['reason'],
			'status'			=> $input['status'],
			'is_delete'			=> 0,
		);
		if(!empty($isInsert)){
			$this->basic_pay->updateBasicPay($data,null,$profiling_id);
		}else{
			$this->basic_pay->createBasicPay($data);
		}
	}

	private function updateBankDetail($input,$profiling_id)
	{

		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;
		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$bank_details = $this->bank->fetchBanks(null,false,$profiling_id);
		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) {
			$attachment = json_decode($inpt['table']);

			$data = array(
				'profiling_id'	=> $profiling_id,
				'user_id'		=> $inpt['user_id'],
				'bank_id'		=> $inpt['bank_id'],
				'branch'		=> $inpt['branch'],
				'acc_no'		=> $inpt['acc_no'],
				'status'		=> $inpt['status'],
				'is_delete'		=> 0,
			);

			if(!empty($inpt['id']) && $flag){

				if(!empty($bank_details)) foreach ($bank_details as $key => $bank) {
					if($inpt['id'] == $bank->id){
						array_splice($bank_details, $key, 1);
					}	
				}
				$this->bank->editBank($data,$inpt['id']);
			}else{
				$bank_id = $this->bank->createBank($data);

				//bank 
				if(!empty($attachment)){ //to avoid error in edit mode because there is no error message..keep this hack first
					if(empty($attachment->error) && $bank_id){
						// die(debug($attachment));

						$attach = array(
							'user_id' 			=> $inpt['user_id'],
							'bank_detail_id'	=> $bank_id,
							'attachment_name'	=> $attachment->file_name,
							'location'			=> 'application/storage/hr/profiling/'.$inpt['user_id'].'/bank/'.$attachment->file_name,
							'file_type'			=> $attachment->file_type,
							'file_ext'			=> $attachment->file_type,
							'mask_id'			=> 'infotype_'.date('Ymd').'_'.uniqid(),
							'is_delete'			=> 0,
							 );
						$this->bank->createAttachment($attach);
					}
				}
				//bank
			}
		}

		if(!empty($bank_details)) foreach ($bank_details as $key => $bank) {
			$delete = array('is_delete' => 1);
			$this->bank->editBank($delete,$bank->id);
		}
	}

	private function createStatutoryDetail($input,$profiling_id)
	{
		// die(debug($input));
		$data = array(
			'profiling_id' 		=> $profiling_id, 
			'user_id' 			=> (!empty($input['user_id']))?$input['user_id']:'',
			'ee_epf_no'			=> (!empty($input['employee_epf_no']))?$input['employee_epf_no']:'',
			'er_rate'			=> (!empty($input['employer_rate']))?$input['employer_rate']:'',
			'er_percent'		=> (!empty($input['employer_amount_percent']))?$input['employer_amount_percent']:'',
			'ee_rate'			=> (!empty($input['employee_rate']))?$input['employee_rate']:'',
			'ee_percent'		=> (!empty($input['employee_amount_percent']))?$input['employee_amount_percent']:'',
			'ee_socso'			=> (!empty($input['employee_socso_no']))?$input['employee_socso_no']:'',
			'ee_income_tax'		=> (!empty($input['employee_income_tax_no']))?$input['employee_income_tax_no']:'',
			'ee_pcb_deduction'	=> (!empty($input['employee_pcb_deduction']))?$input['employee_pcb_deduction']:0,
			'ee_zakat_deduction'=> (!empty($input['employee_zakat_deduction']))?$input['employee_zakat_deduction']:0,
			'ee_pcb_deduction_percent'	=> (!empty($input['employee_pcb_deduction_percent']))?$input['employee_pcb_deduction_percent']:0,
			'ee_zakat_deduction_percent'=> (!empty($input['employee_zakat_deduction_percent']))?$input['employee_zakat_deduction_percent']:0,
			'status'			=> (!empty($input['status']))?$input['status']:0,
			'year'				=> (!empty($input['year']))?$input['year']:0,
			'is_deleted'		=> 0,
		);
		$this->statutory_detail->createStatutory($data);
	}

	private function updateStatutoryDetail($input,$profiling_id)
	{
		$statutory = ($this->statutory_detail->fetchStatutory(null,false,$profiling_id))?$this->statutory_detail->fetchStatutory(null,false,$profiling_id)[0]:null;
		$data = array(
			'profiling_id' 		=> $profiling_id, 
			'user_id' 			=> (!empty($input['user_id']))?$input['user_id']:'',
			'ee_epf_no'			=> (!empty($input['employee_epf_no']))?$input['employee_epf_no']:'',
			'er_rate'			=> (!empty($input['employer_rate']))?$input['employer_rate']:'',
			'er_percent'		=> (!empty($input['employer_amount_percent']))?$input['employer_amount_percent']:'',
			'ee_rate'			=> (!empty($input['employee_rate']))?$input['employee_rate']:'',
			'ee_percent'		=> (!empty($input['employee_amount_percent']))?$input['employee_amount_percent']:'',
			'ee_socso'			=> (!empty($input['employee_socso_no']))?$input['employee_socso_no']:'',
			'ee_income_tax'		=> (!empty($input['employee_income_tax_no']))?$input['employee_income_tax_no']:'',
			'ee_pcb_deduction'	=> (!empty($input['employee_pcb_deduction']))?$input['employee_pcb_deduction']:0,
			'ee_zakat_deduction'=> (!empty($input['employee_zakat_deduction']))?$input['employee_zakat_deduction']:0,
			'ee_pcb_deduction_percent'	=> (!empty($input['employee_pcb_deduction_percent']))?$input['employee_pcb_deduction_percent']:0,
			'ee_zakat_deduction_percent'=> (!empty($input['employee_zakat_deduction_percent']))?$input['employee_zakat_deduction_percent']:0,
			'status'			=> (!empty($input['status']))?$input['status']:0,
			'year'				=> (!empty($input['year']))?$input['year']:0,
			'is_deleted'		=> 0,
		);

		if(!empty($statutory)){
			$this->statutory_detail->updateStatutory($data,$statutory->id);
		}else{
			 $this->statutory_detail->createStatutory($data);
		}
	}

	private function updateRecurring($input,$profiling_id)
	{
		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;
		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$recur_one = $this->recurring->fetchRecurring(null,false, $profiling_id,0);
		$recur_two = $this->recurring->fetchRecurring(null,false, $profiling_id,1);

		if(!empty($recur_one) && !empty($recur_two)){
			$recurring = array_merge($recur_one,$recur_two);
		}else{
			if(!empty($recur_one)){
				$recurring = $recur_one;
			}elseif (!empty($recur_two)) {
				$recurring = $recur_two;
			}else{
				$recurring = null;
			}
		}

		if(!empty($input['list'])) foreach ($input['list'] as $key => $list) {
			$data = array(
				'profiling_id' 		=> $profiling_id,
				'user_id'			=> $list['user_id'],
				'recurring_type'	=> $list['recurring'],
				'type'				=> $list['type'],
				'amount'			=> $list['amount'],
				// 'date_start'		=> date('Y-m-d',strtotime($list['date_from'])),
				// 'date_end'		=> date('Y-m-d',strtotime($list['date_to'])),
				'date_start'		=> (!empty($list['date_from']))?date('Y-m-d',strtotime($list['date_from'])):null,
				'date_end'			=> (!empty($list['date_to']))?date('Y-m-d',strtotime($list['date_to'])):null,
				'status'			=> $list['status'],
				'is_delete'			=> 0, 
			);

			if(!empty($list['id']) && $flag){

				if(!empty($recurring)) foreach ($recurring as $key => $recurred) {
					if($list['id'] == $recurred->id){
						array_splice($recurring, $key,1);
					}
				}
				$this->recurring->editRecurring($data,$list['id']);
			}else{
				$this->recurring->createRecurring($data);
			}
		}

		if(!empty($recurring)) foreach ($recurring as $key => $recurred) {
			$delete = array('is_delete' => 1);
			$this->recurring->editRecurring($delete,$recurred->id);
		}
	}

	private function updateThirdParty($input,$profiling_id)
	{
		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;
		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$third_party_payments = $this->third_party->fetchPayment(null,false, $profiling_id);

		if(!empty($input['list'])) foreach ($input['list'] as $key => $list) {
			$data = array(
				'profiling_id'  => $profiling_id,
				'user_id'		=> $list['user_id'],
				// 'date_start'	=> date('Y-m-d',strtotime($list['date_start'])),
				// 'date_end'		=> date('Y-m-d',strtotime($list['date_end'])),
				'date_start'	=> (!empty($list['date_start']))?date('Y-m-d',strtotime($list['date_start'])):null,
				'date_end'		=> (!empty($list['date_end']))?date('Y-m-d',strtotime($list['date_end'])):null,
				'type'			=> $list['type'],
				'amount'		=> $list['amount'],
				'status'		=> $list['status'],
				'is_delete'		=> 0,
			);
			if(!empty($list['id']) && $flag){

				if(!empty($third_party_payments)) foreach ($third_party_payments as $key => $payment) {
					if($list['id'] == $payment->id){
						array_splice($third_party_payments,$key,1);
					}
				}

				$this->third_party->editPayment($data,$list['id']);
			}else{
				$this->third_party->createPayment($data);
			}
		}

		if(!empty($third_party_payments)) foreach ($third_party_payments as $key => $payment) {
			$delete = array('is_delete' => 1);
			$this->third_party->editPayment($delete,$payment->id);
		}
	}

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

		$workflowID = $input['work_id'];
		$name 		= $input['name'];

		$update = $this->action->updateWorkflow($workflowID,$name);

		$msg = array('status' => 'success','msg' => 'Successfully update workflow');
		// if($update){
		// }else{
		// 	$msg = array('status' => 'failed','msg' => 'failed to update workflow');
		// }

		echo json_encode($msg);
	}

	public function save_profiling_status()
	{
		$this->load->model('hr/model_profiling');

		$input 			= $this->input->post();
		$user_id 		= $input['user_id'];
		$status 		= $input['status'];
		$existing_data	= $this->model_profiling->countIncompleteDetailList('',$user_id);
		$table_name		= 'user__profiling_status';

		$insert	= array
		(
			'user_id' 		=> $user_id,
			'status'		=> $status,
			'created_by'	=> $_SESSION['user']['id']
		);

		$update = array
		(
			'is_delete'		=> 1,
			'updated_by'	=> $_SESSION['user']['id'],
			'updated_ts'	=> date('Y-m-d H:i:s'),
			'deleted_by'	=> $_SESSION['user']['id'],
			'deleted_ts'	=> date('Y-m-d H:i:s')
		);

		$where = array
		(
			'user_id'	=> $user_id
		);

		$status_msg = '';
		$msg = '';

		if(!empty($existing_data))
		{
			$delete_existing = $this->general_model->update($table_name, $update, $where);
			if($delete_existing)
			{
				$save_status = $this->general_model->insert($table_name, $insert);
				if($save_status)
				{
					$status_msg = 'success';
					$msg = 'Successfully save details';
				}else{
					$status_msg = 'failed';
					$msg = 'Failed to save details';
				}
			}else{
				$status_msg = 'failed';
				$msg = 'Failed to save detail';
			}
		}else{
			$save_status = $this->general_model->insert($table_name, $insert);
			if($save_status)
			{
				$status_msg = 'success';
				$msg = 'Successfully save details';
			}else{
				$status_msg = 'failed';
				$msg = 'Failed to save details';
			}
		}

		$mode = ($status == 1)?'incompleteList':'completeList';

      	echo json_encode(array(
            "status" 		=> $status_msg,
            "msg"			=> $msg,
            "redirect"		=> base_url('hr/StaffProfile/'.$mode)
        ));
	}

	/* newly added */
	private function updateEducationInProgress($input,$profiling_id)
	{
		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;
		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$existing_data = $this->user_pursuing_study->get_pursuing_study(null, false, $profiling_id);

		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) {
			$data = array(
				'profiling_id' 			=> $profiling_id,
				'user_id'				=> $inpt['user_id'],
				'date_start'			=> date('Y-m-d',strtotime($inpt['date_start'])),
				'date_end'				=> date('Y-m-d',strtotime($inpt['date_end'])),
				'institution'			=> $inpt['institution'],
				'program'				=> $inpt['program'],
				'status'				=> $inpt['status'],
				'progress_paper'		=> $inpt['progress_paper'],
			);

			if(!empty($inpt['id']) && $flag)
			{				
				if(!empty($existing_data))foreach ($existing_data as $key => $existing) {
					if($inpt['id'] == $existing->id){
						array_splice($existing_data, $key,1);
					}
				}
				$this->user_pursuing_study->editPursuingStudy($data,$inpt['id']);
			}else{
				$this->user_pursuing_study->createPursuingStudy($data);
			}
		}

		if(!empty($existing_data)) foreach ($existing_data as $key => $existing) {
			$delete = array(
				'is_delete' 	=> 1,
				'deleted_by'	=> $this->session->userdata('user')['id'],
				'deleted_ts'	=> date('Y-m-d H:i:s')
			);
			$this->user_pursuing_study->editPursuingStudy($delete,$existing->id);
		}
	}

	private function updateEmergencyContact($input,$profiling_id)
	{
		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;
		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$existing_data = $this->user_emergency->get_case_of_emergency(null, false, $profiling_id);

		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) {
			$data = array(
				'profiling_id' 		=> $profiling_id,
				'user_id'			=> $inpt['user_id'],
				'name'				=> $inpt['name'],
				'relation'			=> $inpt['relation'],
				'phone_no'			=> $inpt['phone'],
				'email'				=> $inpt['email'],
				'address'			=> $inpt['address'],
			);

			if(!empty($inpt['id']) && $flag)
			{				
				if(!empty($existing_data))foreach ($existing_data as $key => $existing) {
					if($inpt['id'] == $existing->id){
						array_splice($existing_data, $key,1);
					}
				}
				$this->user_emergency->editCaseEmergency($data,$inpt['id']);
			}else{
				$this->user_emergency->createCaseEmergency($data);
			}
		}

		if(!empty($existing_data)) foreach ($existing_data as $key => $existing) {
			$delete = array(
				'is_delete' 	=> 1,
				'deleted_by'	=> $this->session->userdata('user')['id'],
				'deleted_ts'	=> date('Y-m-d H:i:s')
			);
			$this->user_emergency->editCaseEmergency($delete,$existing->id);
		}
	}

	private function updateProfessionalAcademic($input,$profiling_id,$type)
	{
		$http_referer = $_SERVER['HTTP_REFERER'];
		$flag = true;
		if(strpos($http_referer, 'new_action_type') !== false)
		{
			$flag = false;
		}

		$existing_data = $this->professional_academic->fetchProfessionalAcademic(null,false,$profiling_id,null,$type);

		if(!empty($input['list'])) foreach ($input['list'] as $key => $inpt) {
			$attachment = json_decode($inpt['table']);

			$data = array(
				'user_id'				=> $inpt['user_id'],
				'profiling_id'			=> $profiling_id,
				'type'					=> $inpt['type'],
				'level'					=> (isset($inpt['level']))?$inpt['level']:'',
				'associate_name'		=> $inpt['associate_name'],
				'program'				=> $inpt['program'],
				'date_finish'			=> $inpt['date_finish'],
				'result'				=> $inpt['result'],
				'created_by'			=> $this->session->userdata('user')['id']
			);

			if(!empty($inpt['id']) && $flag){
				$data['updated_by'] = $this->session->userdata('user')['id'];
				$data['updated_ts'] = date('Y-m-d H:i:s');

				$this->professional_academic->editProfessionalAcademic($data,$inpt['id']);

				if(!empty($existing_data)) foreach ($existing_data as $key => $existing) {
					if($inpt['id'] == $existing->id){
						array_splice($existing_data,$key,1);
					}
				}

				$professional_academic_id = $inpt['id'];
			}else{
				$professional_academic_id = $this->professional_academic->createProfessionalAcademic($data);
			}
			
			if(!empty($attachment)){
				if(empty($attachment->error) && $professional_academic_id){
					$attach = array(
						'user_id' 					=> $inpt['user_id'],
						'professional_academic_id' 	=> $professional_academic_id,
						'attachment_name' 			=> $attachment->file_name, 
						'location'					=> 'application/storage/hr/profiling/'.$inpt['user_id'].'/professional_academic/'.(($type == 0)?'education':'certificate').'/'.$attachment->file_name,
						'file_type' 				=> $attachment->file_type,
						'file_ext' 					=> $attachment->file_type,
						'mask_id'					=> '6'.$professional_academic_id.''.date('Ymd').''.uniqid(),
						'created_by'				=> $this->session->userdata('user')['id']
						);	
					$this->professional_academic_attachment->createAttachment($attach);
				}
			}
		}

		if(!empty($existing_data)) foreach ($existing_data as $key => $existing) 
		{
			$delete = array('is_delete' => 1);
			$this->professional_academic->editProfessionalAcademic($delete,$existing->id);
		}
	}
}
?>