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

class StaffProfile extends MY_Controller
{
	function __construct()
	{
		parent::__construct();
		$this->load->model('admin/model_company');
		$this->load->model('crm/model_crm');
		$this->load->model('crm/country');
		$this->load->model('crm/general_model');
		$this->load->model('hr/model_user_license','license');
		$this->load->model('hr/model_user_license_attachment','license_attachment');
		$this->load->model('hr/model_user_address','address');
		$this->load->model('hr/model_user_family','family');
		$this->load->model('hr/model_academic_qualification','academic');
		$this->load->model('hr/model_academic_qualification_attachment','academic_attachment');
		$this->load->model('hr/model_professional_membership','promember');
		$this->load->model('hr/model_professional_membership_attachment','promember_attachment');
		$this->load->model('hr/model_job_history','jobs');
		$this->load->model('hr/model_bank','bank');
		$this->load->model('hr/model_recognition','recognition');
		$this->load->model('hr/model_recognition_attachment','recognition_attachment');
		$this->load->model('hr/model_staff_action','staff_action');
		$this->load->model('hr/model_user_contract_element','contract');
		$this->load->model('hr/model_third_party_payment','thirdParty');
		$this->load->model('hr/model_personal_attachment','attachment');
		$this->load->model('hr/model_user_pcb','pcb');
		$this->load->model('hr/model_action_type','action');
		$this->load->model('hr/model_basic_pay','basic_pay');
		$this->load->model('hr/model_statutory_detail','stats');
		$this->load->model('hr/model_joining_group','join_group');
		$this->load->model('hr/model_user_recurring','recurring');
		$this->logged_user = $this->session->userdata('user');

		/* newly added */
		$this->load->model('hr/model_user_case_emergency','user_emergency');
		$this->load->model('hr/model_user_pursuing_study','user_pursuing_study');
		$this->load->model('hr/model_user_working_experience','working_experience');
		$this->load->model('hr/Model_user_professional_academic','professional_academic');
		$this->load->model('hr/Model_user_professional_academic_attachment','professional_academic_attachment');
		/* newly added */

		/* Farid 220129 */
		$this->load->model('hr/model_exam');
		$this->load->model('staff_directory/model_user_list');

		//Fakru add 20211224
		$this->load->model('hr/model_user_professional_experiencemgs','professional_experiencemgs');
		//end#
		if($this->logged_user)
		{
			$this->login->checkModuleAccess(4);
			$this->logged_module = $this->session->userdata('module_data');

			if($this->logged_module['role'] != 'admin'){
				redirect(base_url('/hr'));
			}
			// die(debug($this->logged_module));
		}
		else
		{
			redirect(base_url());
		}	 
	}

	function index()
	{
		$this->dashboard();
	}

	function dashboard()
	{
		$data['role'] = $this->logged_module['role'];

		if($data['role'] != 'admin'){
			redirect(base_url('/hr/staffprofile/staffDetail/'.$_SESSION['user']['id']));
		}
		$data['page_setup'] = $this->template->pageSetup('Staff Profiling', '', 'Dashboard');
		$data['staff']			= $this->model_user->getUsers(null,null);
		$data['company'] 		= $this->model_company->getCompanies(1);

		$this->template->view('hr/staff-profiling/page/dashboard/index', $data);
	}

	function staff_list_report() 
	{
		$data['date'] 			= date("d-m-Y"); 
		$data['staff']			= $this->model_user->getUsers();
		$header['title']		= 'Staff Profile List';
		$this->load->view('hr/report/header.php');
		$this->load->view('hr/report/staff-profiling/staff_list.php', $data);
		$this->load->view('hr/report/footer.php');		
	}

	function new_action_type($staff_id = null)
	{
		$this->load->model('hr/model_profiling');
		$data['role'] = $this->logged_module['role'];
		if ($data['role'] != 'admin') 
		{
			redirect(base_url('hr/staffprofile'));
		}
		$data['workflows']						= $this->action->fetch_works();
		$data['staff']							= $this->model_user->getUserDetail($staff_id);
		$data['titles']							= $this->general_model->get_all('_ref__title');
		$data['genders']						= $this->general_model->get_all('_ref__gender');
		$data['religions']						= $this->general_model->get_all('_ref__religion');
		$data['races']							= $this->general_model->get_all('_ref__race');
		$data['jobPositions']					= $this->model_general->fetchAllObj('company__position', array(), array('parent_id !=' => 0,'is_delete' => 0), array(), array('grade' => 'DESC', 'level' => 'ASC' ));
		$data['designations']					= $this->general_model->get_all('_ref__designation');
		$data['parentPositions']				= $this->model_general->fetchAllObj('company__position', array(), array('parent_id' => 0));
		$data['grade']							= $this->model_general->fetchAllObj('company__position', array(), array('parent_id !=' => 0));
		$data['companies']						= $this->model_company->getCompanies();
		$data['business_entities']				= $this->general_model->get_all('company__business_entity');
		// $data['allStaff']						= $this->model_user->getUsersByFilter(array('d.position_id <' => 13));	 					//salah ni sebab ada yang tak dapat...terutamany yang baru
		//$data['allStaff']						= $this->model_user->get_management_and_up();
		$data['allStaff']					= $this->model_user->getUsers2();
		// die(debug($data['allStaff']));	

		$data['branches']						= $this->model_company->getBranches();														
		$data['divisions']						= $this->model_company->getDivisions();														
		$data['departments']					= $this->model_company->getDepartments();													
		$data['employee_groups']				= $this->general_model->get_all('_ref__employee_group');						
		$data['contractTypes']					= $this->general_model->get_all('_ref__employee_contract_type');
		$data['hiringTypes']					= $this->general_model->get_all('_ref__contract_type');									
		$data['contractConfirmations'] 			= $this->general_model->get_all('_ref__contract_confirmation');
		$data['hiringReasons']					= $this->general_model->get_all('_ref__hiring_reason');											
		$data['salaryScales']					= $this->model_company->getSalaryScales();											
		$data['states']							= $this->general_model->get_all('_ref__state');
		$data['countries']						= $this->country->country_all();
		$data['residenceType']					= $this->general_model->get_all('_ref__residence_type');
		$data['relations']						= $this->general_model->get_all('_ref__relationship');
		$data['qualifications']					= $this->general_model->get_all('_ref__academic');
		$data['banks']							= $this->general_model->get_all('_ref__bank');
		$data['action_type']					= $this->model_profiling->getLatestProfile($staff_id);
		$data['action_types']					= $this->action->fetchActionList();
		$data['page_setup'] 					= $this->template->pageSetup('HR', 'Dashboard', 'New Action');

		// debug($data['action_type']);
		/*
			- get latest data 
		*/
		$data['addresses']						= $this->address->fetchlatest($staff_id);
		$data['family_info']					= $this->family->fetchFamilyInfo($staff_id, true, null);
		$data['academic_qualification'] 		= $this->academic->fetchQualification($staff_id,true,null);
		$data['additional_personal_data']		= $this->attachment->fetchPersonalAttachment($staff_id,null,true,null);
		$data['previous_employment_history']	= $this->jobs->fetchJobHistory($staff_id,true,null);
		$data['professional_membership']		= $this->promember->fetchMembership($staff_id,true,null);
		$data['professional_license']			= $this->license->fetchLicense(null,$staff_id,null,true,null);
		$data['recognition']					= $this->recognition->fetchRecognition($staff_id,true,null);
		$data['bank_details']					= $this->bank->fetchBanks($staff_id,true,null);
		$data['third_party_payments']			= $this->thirdParty->fetchPayment($staff_id,true,null);

		
		//models problem no checking for latest data
		$data['recurring_payments']				= $this->recurring->fetchRecurring($staff_id,true, null,0);
		$data['recurring_deductions']			= $this->recurring->fetchRecurring($staff_id,true, null,1);

		/*newly added*/
		$data['emergency_contact']				= $this->user_emergency->get_case_of_emergency($staff_id,false);
		$data['pursuing_study']					= $this->user_pursuing_study->get_pursuing_study($staff_id,false);
		$data['professional_academic']			= $this->professional_academic->fetchProfessionalAcademic($staff_id,false);

		$this->template->view('hr/staff-profiling/page/transaction/create_update_action',$data);
	}

	function editAction($profiling_id)
	{
		$data['date'] 						= date("d-m-Y");
		$data['action_type']				= ($this->staff_action->fetchAction($profiling_id,null))?$this->staff_action->fetchAction($profiling_id,null)[0]:null;
		{											
			$data['jobPositions']				= $this->model_company->getPositions(array('parent_id !=' => 0));
			$data['parentPositions']			= $this->model_company->getPositions(array('parent_id' => 0));
			$data['companies']					= $this->model_company->getCompanies(); //get all salihin list company
			$data['allStaff']					= $this->model_user->getUserDetail();														
			$data['branches']					= $this->model_company->getBranches();														
			$data['divisions']					= $this->model_company->getDivisions();														
			$data['departments']				= $this->model_company->getDepartments();
			$data['titles']						= $this->general_model->get_all('_ref__title');
			$data['genders']					= $this->general_model->get_all('_ref__gender');
			$data['religions']					= $this->general_model->get_all('_ref__religion');
			$data['races']						= $this->general_model->get_all('_ref__race');													
			$data['employee_groups']			= $this->general_model->get_all('_ref__employee_group');									
			$data['contractTypes']				= $this->general_model->get_all('_ref__employee_contract_type');
			$data['hiringTypes']				= $this->general_model->get_all('_ref__contract_type');										
			$data['contractConfirmations'] 		= $this->general_model->get_all('_ref__contract_confirmation');
			$data['hiringReasons']				= $this->general_model->get_all('_ref__hiring_reason');	
			$data['designations']				= $this->general_model->get_all('_ref__designation');
			$data['business_entities']			= $this->general_model->get_all('company__business_entity');		
			$data['salaryScales']				= $this->model_company->getSalaryScales();	
			$data['workflows']					= $this->action->fetch_works();
			$data['states']						= $this->general_model->get_all('_ref__state');
			$data['countries']					= $this->country->country_all();
			$data['residenceType']				= $this->general_model->get_all('_ref__residence_type');
			$data['relations']					= $this->general_model->get_all('_ref__relationship');
			$data['qualifications']				= $this->general_model->get_all('_ref__academic');
			$data['banks']						= $this->general_model->get_all('_ref__bank');
		}

		if($data['action_type'] && $profiling_id)
		{
			$data['action_types']				= $this->action->fetchActionList();
			$data['staff']						= $this->model_user->getUserDetail($data['action_type']->user_id);
			$data['join_group'] 				= ($this->join_group->fetchJoiningGroup(null,$profiling_id,0))?$this->join_group->fetchJoiningGroup(null,$profiling_id,0)[0]:null;
			$data['addresses']					= $this->address->fetchAddress(null,false,$profiling_id);
			$data['family_info']				= $this->family->fetchFamilyInfo(null, false, $profiling_id);
			$data['academic_qualification'] 	= $this->academic->fetchQualification(null,false,$profiling_id);
			$data['additional_personal_data']	= $this->attachment->fetchPersonalAttachment(null,null,false,$profiling_id);
			$data['previous_employment_history']= $this->jobs->fetchJobHistory(null,false,$profiling_id);
			$data['professional_membership']	= $this->promember->fetchMembership(null,false,$profiling_id);
			$data['professional_license']		= $this->license->fetchLicense(null,null,null,false,$profiling_id);
			$data['recognition']				= $this->recognition->fetchRecognition(null,false,$profiling_id);
			$data['contract_element']			= ($this->contract->fetchContract(null,false,$profiling_id))?$this->contract->fetchContract(null,false,$profiling_id)[0]:null;
			$data['basic_pay']					= ($this->basic_pay->fetchBasicPay(null,false,$profiling_id))?$this->basic_pay->fetchBasicPay(null,false,$profiling_id)[0]:null;
			$data['statutory_details']			= ($this->stats->fetchStatutory(null,false,$profiling_id))?$this->stats->fetchStatutory(null,false,$profiling_id)[0]:null;
			$data['bank_details']				= $this->bank->fetchBanks(null,false,$profiling_id);
			$data['recurring_payments']			= $this->recurring->fetchRecurring(null,false, $profiling_id,0);
			$data['recurring_deductions']		= $this->recurring->fetchRecurring(null,false, $profiling_id,1);
			$data['third_party_payments']		= $this->thirdParty->fetchPayment(null,false, $profiling_id);
			$data['staff']['staff_id'] 			= $data['action_type']->staff_id;

			/*newly added*/
			$data['emergency_contact']			= $this->user_emergency->get_case_of_emergency(null,false,$profiling_id);
			$data['pursuing_study']				= $this->user_pursuing_study->get_pursuing_study(null,false,$profiling_id);
			$data['professional_academic']		= $this->professional_academic->fetchProfessionalAcademic(null,false,$profiling_id);
		}
		
		$data['page_setup'] 					= $this->template->pageSetup('HR', 'Dashboard', 'Edit Action Type');
		$this->template->view('hr/staff-profiling/page/transaction/create_update_action',$data);
	}

	function viewAction($profiling_id)
	{
		$data['date'] 						= date("d-m-Y"); 
		$data['action_type']				= ($this->staff_action->fetchAction($profiling_id,null))?$this->staff_action->fetchAction($profiling_id,null)[0]:null;
		$data['join_group'] 				= ($this->join_group->fetchJoiningGroup(null,$profiling_id,0))?$this->join_group->fetchJoiningGroup(null,$profiling_id,0)[0]:null;
		$data['addresses']					= $this->address->fetchAddress(null,false,$profiling_id);
		$data['family_info']				= $this->family->fetchFamilyInfo(null, false, $profiling_id);
		$data['academic_qualification'] 	= $this->academic->fetchQualification(null,false,$profiling_id);
		$data['additional_personal_data']	= $this->attachment->fetchPersonalAttachment(null,null,false,$profiling_id);
		$data['previous_employment_history']= $this->jobs->fetchJobHistory(null,false,$profiling_id);
		$data['professional_membership']	= $this->promember->fetchMembership(null,false,$profiling_id);
		$data['professional_license']		= $this->license->fetchLicense(null,null,null,false,$profiling_id);
		$data['recognition']				= $this->recognition->fetchRecognition(null,false,$profiling_id);
		$data['contract_element']			= ($this->contract->fetchContract(null,false,$profiling_id))?$this->contract->fetchContract(null,false,$profiling_id)[0]:null;
		$data['basic_pay']					= ($this->basic_pay->fetchBasicPay(null,false,$profiling_id))?$this->basic_pay->fetchBasicPay(null,false,$profiling_id)[0]:null;
		$data['bank_details']				= ($this->bank->fetchBanks(null,false,$profiling_id))? $this->bank->fetchBanks(null,false,$profiling_id):null;
		$data['statutory_details']			= ($this->stats->fetchStatutory(null,false,$profiling_id))?$this->stats->fetchStatutory(null,false,$profiling_id)[0]:null;
		$data['recurring_payments']			= $this->recurring->fetchRecurring(null,false, $profiling_id,0);
		$data['recurring_deductions']		= $this->recurring->fetchRecurring(null,false, $profiling_id,1);
		$data['third_party_payments']		= $this->thirdParty->fetchPayment(null,false, $profiling_id);
		$data['page_setup'] 				= $this->template->pageSetup('HR', 'Dashboard', 'New Action Type');
		$data['pcb_consideration']			= $this->pcb->fetchPCB(null,false,$profiling_id);
		$data['emergency_contact']			= $this->user_emergency->get_case_of_emergency(null,false,$profiling_id);
		$data['pursuing_study']				= $this->user_pursuing_study->get_pursuing_study(null,false,$profiling_id);
		$data['professional_education']		= $this->professional_academic->fetchProfessionalAcademic(null,false,$profiling_id,null,0);
		$data['professional_certificate']	= $this->professional_academic->fetchProfessionalAcademic(null,false,$profiling_id,null,1);

		$this->template->view('hr/staff-profiling/page/view/action',$data);
	}

	function printAction($profiling_id)
	{
		$data['date'] 						= date("d-m-Y"); 
		$data['action_type']				= ($this->staff_action->fetchAction($profiling_id,null))?$this->staff_action->fetchAction($profiling_id,null)[0]:null;
		$data['join_group'] 				= ($this->join_group->fetchJoiningGroup(null,$profiling_id,0))?$this->join_group->fetchJoiningGroup(null,$profiling_id,0)[0]:null;
		$data['addresses']					= $this->address->fetchAddress(null,false,$profiling_id);
		$data['family_info']				= $this->family->fetchFamilyInfo(null, false, $profiling_id);
		$data['academic_qualification'] 	= $this->academic->fetchQualification(null,false,$profiling_id);
		$data['additional_personal_data']	= $this->attachment->fetchPersonalAttachment(null,null,false,$profiling_id);
		$data['previous_employment_history']= $this->jobs->fetchJobHistory(null,false,$profiling_id);
		$data['professional_membership']	= $this->promember->fetchMembership(null,false,$profiling_id);
		$data['professional_license']		= $this->license->fetchLicense(null,null,null,false,$profiling_id);
		$data['recognition']				= $this->recognition->fetchRecognition(null,false,$profiling_id);
		$data['contract_element']			= ($this->contract->fetchContract(null,false,$profiling_id))?$this->contract->fetchContract(null,false,$profiling_id)[0]:null;
		$data['basic_pay']					= ($this->basic_pay->fetchBasicPay(null,false,$profiling_id))?$this->basic_pay->fetchBasicPay(null,false,$profiling_id)[0]:null;
		$data['bank_details']				= ($this->bank->fetchBanks(null,false,$profiling_id))? $this->bank->fetchBanks(null,false,$profiling_id):null;
		$data['statutory_details']			= ($this->stats->fetchStatutory(null,false,$profiling_id))?$this->stats->fetchStatutory(null,false,$profiling_id)[0]:null;
		$data['recurring_payments']			= $this->recurring->fetchRecurring(null,false, $profiling_id,0);
		$data['recurring_deductions']		= $this->recurring->fetchRecurring(null,false, $profiling_id,1);
		$data['third_party_payments']		= $this->thirdParty->fetchPayment(null,false, $profiling_id);
		$data['pcb_consideration']			= $this->pcb->fetchPCB(null,false,$profiling_id);
		$data['emergency_contact']			= $this->user_emergency->get_case_of_emergency(null,false,$profiling_id);
		$data['pursuing_study']				= $this->user_pursuing_study->get_pursuing_study(null,false,$profiling_id);
		$data['professional_education']		= $this->professional_academic->fetchProfessionalAcademic(null,false,$profiling_id,null,0);
		$data['professional_certificate']	= $this->professional_academic->fetchProfessionalAcademic(null,false,$profiling_id,null,1);
		
		$this->load->view('hr/report/header.php');
		$this->load->view('hr/report/staff-profiling/action_type.php', $data);
		$this->load->view('hr/report/footer.php');
	}

	function add_workflow()
	{
		$data['role'] = $this->logged_module['role'];
		if ($data['role'] != 'admin') {
			redirect(base_url('hr/staffprofile'));
		}

		$data['page_setup']			= $this->template->pageSetup('HR','Dashboard','Add Workflow');

		$this->template->view('hr/staff-profiling/page/workflow/add',$data);
	}

	function staffDetail($staff_id = null)
	{
		$this->load->model('hr/model_profiling');
		if(!$staff_id){
			redirect(base_url('/hr/staffprofile/'));
		}

		if (($staff_id == $_SESSION['user']['id']) || $this->logged_module['role'] == 'admin')
		{
			$data['page_setup'] 				= $this->template->pageSetup('HR', 'Dashboard', 'Staff Detail');
			$data['join_groups'] 				= ($join_group = $this->join_group->fetchJoiningGroup(null,null,0,$staff_id))?$join_group:null;
			$data['staff_id']					= $staff_id;
			$data['session_id'] 				= $this->logged_user['id'];
			$data['role'] 						= $this->logged_module['role'];
			$data['rsStaff']					= $this->model_user->getUserDetail($staff_id);
			$data['latest_profile']				= $this->model_profiling->getLatestProfile($staff_id);
			$data['countries']					= $this->country->country_all();
			$data['titles']						= $this->general_model->get_all('_ref__title') ;
			$data['religions']					= $this->general_model->get_all('_ref__religion');
			$data['races']						= $this->general_model->get_all('_ref__race');
			$data['professionalLicense']		= $this->license->fetchLicense(null,$staff_id,null,false);
			$data['states']						= $this->general_model->get_all('_ref__state');			
			$data['addresses'] 					= $this->address->fetchAddress($staff_id,false);	
			$data['families']					= $this->family->fetchFamilyInfo($staff_id,false);
			$data['relations']					= $this->general_model->get_all('_ref__relationship');
			$data['qualifications']				= $this->general_model->get_all('_ref__academic','seq ASC');
			$data['academics']					= $this->academic->fetchQualification($staff_id,false);
			$data['professionalMemberships'] 	= $this->promember->fetchMembership($staff_id,false);
			$data['jobHistories']				= $this->jobs->fetchJobHistory($staff_id,false);
			$data['banks']						= $this->general_model->get_all('_ref__bank');
			$data['staff_bank']					= $this->bank->fetchBanks($staff_id,false);
			$data['recognitions']				= $this->recognition->fetchRecognition($staff_id,false);
			$data['staffActions']				= $this->staff_action->fetchType();
			$data['contracts']					= $this->contract->fetchContract($staff_id,false);
			$data['jobPositions']				= $this->model_general->fetchAllObj('company__position', array(), array('parent_id !=' => 0,'is_delete' => 0), array(), array('grade' => 'DESC', 'level' => 'ASC' ));
			$data['designations']				= $this->general_model->get_all('_ref__designation');
			$data['parentPositions']			= $this->model_general->fetchAllObj('company__position', array(), array('parent_id' => 0));
			$data['branches']					= $this->model_company->getBranches();
			$data['salaryScales']				= $this->model_company->getSalaryScales();
			$data['recurring_payments'] 		= $this->recurring->fetchRecurring($staff_id,false,null,'0');
			$data['recurring_deductions'] 		= $this->recurring->fetchRecurring($staff_id,false,null,1);
			$data['thirdPartyPayments'] 		= $this->thirdParty->fetchPayment($staff_id,false);
			$data['additional_personal_data']	= $this->attachment->fetchPersonalAttachment($staff_id,null,false);
			$data['pcb']						= $this->pcb->fetchPCB($staff_id);
			$data['action_profile']				= $this->staff_action->fetchAction(null,$staff_id);
			$data['basic_payment']				= $this->basic_pay->fetchBasicPay($staff_id,false);
			$data['statutory_details']			= $this->stats->fetchStatutory($staff_id,false);
			$data['hiringReasons']				= $this->general_model->get_all('_ref__hiring_reason');
			$data['residenceType']				= $this->general_model->get_all('_ref__residence_type');		
			$data['allStaff']					= $this->model_user->getUsers2();
			$data['staff_list']					= $this->model_user_list->getUsers($staff_id);
			$data['divisions']					= $this->model_company->getDivisions();														
			$data['departments']				= $this->model_company->getDepartments();
			$data['employee_groups']			= $this->general_model->get_all('_ref__employee_group');									
			$data['contractTypes']				= $this->general_model->get_all('_ref__employee_contract_type');
			$data['business_entities']			= $this->general_model->get_all('company__business_entity');
			$data['totalWorkingExperienceOTH']	= $this->model_user->getTotalWorkingExperience($staff_id);
			$data['staff_date_joined']			= $this->model_user->getDateJoined($staff_id);
			$data['emergency_contact']			= $this->user_emergency->get_case_of_emergency($staff_id,false);
			$data['pursuing_study']				= $this->user_pursuing_study->get_pursuing_study($staff_id,false);
			$data['professional_academic']		= $this->professional_academic->fetchProfessionalAcademic($staff_id,false);
			$data['hiringTypes']				= $this->general_model->get_all('_ref__contract_type');	
			$data['contractConfirmations'] 		= $this->general_model->get_all('_ref__contract_confirmation');

			// $data['profiling_attachment_all']	= $this->model_profiling->getProfilingAttachments_all($staff_id,false);
			$data['profiling_attachmentCat'] 	= $this->model_general->fetchAll("hr__profile_category", array('*'), array("main_id" => 0, "is_delete" => 0));

			foreach($data['profiling_attachmentCat'] as $category){
				$data['attachments'][$category['id']] = $this->model_profiling->getProfilingAttachments($staff_id, $category['id']);
			}

			/* Farid 220129 */
			$data['exam_list_ep'] = $this->model_exam->get_exam_list($staff_id, 1);
			$data['exam_list_pe'] = $this->model_exam->get_exam_list($staff_id, 2);
			$data['exam_list_pc'] = $this->model_exam->get_exam_list($staff_id, 3);
			
			//fakru add 20211224
			$data['professional_experiencemgs']	= $this->professional_experiencemgs->getExpMgs($staff_id);
			//end#

			$this->template->view('hr/staff-profiling/page/list/list', $data);
		}else{
			redirect(base_url('/hr/staffprofile/'));
		}
	}

	function actionReport($staff_id,$mode = null)
	{
		$this->load->model('hr/model_profiling');
		$data['date'] 			= date("d-m-Y");
		$data['actions']		= $this->staff_action->fetchAction(null, $staff_id);
		$data['staff']			= $this->model_user->getUserDetail($staff_id);
		$data['titles']			= $this->general_model->get_all('_ref__title') ;
		$data['latest_profile']	= $this->model_profiling->getLatestProfile($staff_id);
		$data['religions']		= $this->general_model->get_all('_ref__religion');
		$data['races']		 	= $this->general_model->get_all('_ref__race');
		$data['countries']		= $this->country->country_all();

		if(!empty($data['staff']['profile_picture_id']))
		{
			$data['profile_picture'] = $this->model_profiling->getPicture($data['staff']['profile_picture_id']);
		}else
		{
			$data['profile_picture'] = base_url('assets/themes/web/img/users.png');
		}

		if(!empty($mode))
		{
			$data['mode'] = $mode;
		}

		if($data['actions']) foreach ($data['actions'] as $key => $row) 
		{

			if(empty($mode) || $mode == 17){
				$data['actions'][$key]->joining_group 				= $this->join_group->fetchJoiningGroup(null,$row->id,0);
			}
			
			if(empty($mode) || $mode == 1){
				$data['actions'][$key]->address 					= $this->address->fetchAddress(null,false,$row->id);
			}

			if(empty($mode) || $mode == 2){
				$data['actions'][$key]->family_info 				= $this->family->fetchFamilyInfo(null,false,$row->id);
			}

			if(empty($mode) || $mode == 3){
				$data['actions'][$key]->academic_qualification 		= $this->academic->fetchQualification(null,false,$row->id);
			}

			if(empty($mode) || $mode == 4){
				$data['actions'][$key]->additional_personal_data	= $this->attachment->fetchPersonalAttachment(null,null,false,$row->id);
			}

			if(empty($mode) || $mode == 5){
				$data['actions'][$key]->previous_employment_history = $this->jobs->fetchJobHistory(null,false,$row->id);
			}

			if(empty($mode) || $mode == 6){
				$data['actions'][$key]->professional_membership 	= $this->promember->fetchMembership(null,false,$row->id);
			}

			if(empty($mode) || $mode == 7){
				$data['actions'][$key]->professional_license		= $this->license->fetchLicense(null,null,null,false,$row->id);
			}

			if(empty($mode) || $mode == 8){
				$data['actions'][$key]->recognition 				= $this->recognition->fetchRecognition(null,false,$row->id);
			}

			if(empty($mode) || $mode == 9){
				$data['actions'][$key]->contract_element 			= ($this->contract->fetchContract(null,false,$row->id))?$this->contract->fetchContract(null,false,$row->id)[0]:null;
			}

			if(empty($mode) || $mode == 10){
				$data['actions'][$key]->basic_pay 					= ($this->basic_pay->fetchBasicPay(null,false,$row->id))?$this->basic_pay->fetchBasicPay(null,false,$row->id)[0]:null;
			}

			if(empty($mode) || $mode == 11){
				$data['actions'][$key]->bank_details 				= $this->bank->fetchBanks(null,false,$row->id);
			}

			if(empty($mode) || $mode == 12){
				$data['actions'][$key]->statutory_details 			= ($this->stats->fetchStatutory(null,false,$row->id))?$this->stats->fetchStatutory(null,false,$row->id)[0]:null;
			}

			if(empty($mode) || $mode == 13 || $mode == 14){
				$data['actions'][$key]->recurring_payment 	 		= $this->recurring->fetchRecurring(null,false,$row->id,0);
				$data['actions'][$key]->recurring_deduct 			= $this->recurring->fetchRecurring(null,false,$row->id,1);
				
			}

			// if(empty($mode) || $mode == 14){
			// 	$data['actions'][$key]->recurring_payment 	 		= $this->recurring->fetchRecurring(null,false,$row->id,0);
			// 	$data['actions'][$key]->recurring_deduct 			= $this->recurring->fetchRecurring(null,false,$row->id,1);
			// }

			if(empty($mode) || $mode == 15) {
				$data['actions'][$key]->third_party 				= $this->thirdParty->fetchPayment(null,false,$row->id);
			}

			if(empty($mode) || $mode == 16){
				$data['actions'][$key]->pcb_consideration 			= $this->pcb->fetchPCB(null,false,$row->id);
			}

			if(empty($mode) || $mode == '19_0'){
				$data['actions'][$key]->professional_education 		= $this->professional_academic->fetchProfessionalAcademic($staff_id,false,$row->id,null,0);
			}

			if(empty($mode) || $mode == '19_1'){
				$data['actions'][$key]->professional_certificate 	= $this->professional_academic->fetchProfessionalAcademic($staff_id,false,$row->id,null,1);
			}

			// if(empty($mode) || $mode == '18'){
			// 	$data['actions'][$key]->working_experience 			= $this->working_experience->fetchWorkingExperience($staff_id, false, $row->id);
			// }

			if(empty($mode) || $mode == '20'){
				$data['actions'][$key]->pursuing_study 				= $this->user_pursuing_study->get_pursuing_study($staff_id,false, $row->id);
			}

			if(empty($mode) || $mode == '21'){
				$data['actions'][$key]->emergency_contact 			= $this->user_emergency->get_case_of_emergency($staff_id,false, $row->id);
			}
			//fakru add 20211228
			if(empty($mode) || $mode == '22'){
				$data['actions'][$key]->professional_experiencemgs = $this->professional_experiencemgs->getExpMgs($staff_id);
			}
			//end fakru add
		}
		
		$this->load->view('hr/report/header.php');
		if(empty($mode)){
			$this->load->view('hr/report/staff-profiling/action_detail.php', $data);
		}else{
			$this->load->view('hr/report/staff-profiling/action_each_report.php', $data);
		}
		$this->load->view('hr/report/footer.php');
	}

	function expMgsReport($staff_id,$year=null,$type=null)
	{
		$data['date'] 			= date("d-m-Y");
		if ($year!=null && $year=='empty'){
			$year=null;
		}
		$data['professional_experiencemgs'] = $this->professional_experiencemgs->getExpMgs($staff_id, $year, $type);

		$this->load->view('hr/report/header.php');
		$this->load->view('hr/report/staff-profiling/report_expmgs.php', $data);
		$this->load->view('hr/report/footer.php');
	}

	public function createProfessionalLicense()
	{
		$staff_id = $this->uri->segment(4);

		if(!$this->input->post()){
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}

		$input['user_id'] = $staff_id;
		$input['profession'] = $this->input->post('profession');
		$input['license_no'] = $this->input->post('licenseNo');
		$input['license_body_authority'] = $this->input->post('licenseBodyAuthority');
		$input['register_date'] = date('Y-m-d',strtotime($this->input->post('initDate')));
		$input['renewal_date'] = date('Y-m-d',strtotime($this->input->post('renewDate')));
		$input['next_renewal_date'] = date('Y-m-d',strtotime($this->input->post('nextRenewDate')));

		if(!empty($this->input->post('id'))){
			//edit
			$id = $this->input->post('id');
			$this->license->editLicense($input,$id);
			$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$staff_id.'/license'.'/','attachment');
			if ($uploaded){
	        	$temp = explode('/', $uploaded['file_type']); 
				$attachment = 
					array(
						'user_id' => $staff_id,
						'license_id' => $id,
						'attachment_name' => $uploaded['file_name'], 
						'location' => '/storage/hr/profiling/'.$staff_id.'/license'.'/'.$uploaded['file_name'],
						'file_type' => $uploaded['file_type'],
						'file_ext' => $temp[1],
						'mask_id' => time().uniqid(),
						'is_delete' => 0
					);
				
				$attachmentID = $this->input->post('attachmentID');
				if($attachmentID){
					$this->license_attachment->editAttachment($attachment,$attachmentID);
				}else{
					$this->license_attachment->createAttachment($attachment);
				}
			}

		}else{

			$license_id = $this->license->createLicense($input);
			$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$staff_id.'/license'.'/','attachment');
			
			if ($uploaded){
	        	$temp = explode('/', $uploaded['file_type']); 
				$attachment = 
					array(
						'user_id' => $staff_id,
						'license_id' => $license_id,
						'attachment_name' => $uploaded['file_name'], 
						'location' => '/storage/hr/profiling/'.$staff_id.'/license'.'/'.$uploaded['file_name'],
						'file_type' => $uploaded['file_type'],
						'file_ext' => $temp[1],
						'mask_id' => time().uniqid(),
						'is_delete' => 0
					);
				$this->license_attachment->createAttachment($attachment);
			}

		}
		
		$this->staffDetail($staff_id);
	}

	public function createAddress()
	{
		$staff_id = $this->uri->segment(4);

		if(!$this->input->post()){
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}

		$input['user_id'] = $staff_id;
		$input['type'] = $this->input->post('type');
		$input['address'] = $this->input->post('address');
		$input['postcode'] = $this->input->post('postcode');
		$input['city'] = $this->input->post('city');
		$input['state_id'] = $this->input->post('state');
		$input['country_id'] = $this->input->post('country');
		$input['contact_no'] = $this->input->post('contact');

		if (!empty($this->input->post('id'))){
			$address_id = $this->input->post('id');
			$this->address->editAddress($input,$address_id);
		}else{
			$this->address->createAddress($input);
		}
		$this->staffDetail($staff_id);
	}

	public function createFamilyMember()
	{
		$staff_id = $this->uri->segment(4);

		if(!$this->input->post()){
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}
		
		$input['staff_id'] = $staff_id;
		$input['name'] = $this->input->post('name');
		$input['ic_no'] = $this->input->post('ic_no');
		$input['relation'] = $this->input->post('relation');
		$input['birthdate'] = (!empty($this->input->post('birthdate')))?date('Y-m-d',strtotime($this->input->post('birthdate'))):null;
		$input['phone_no'] = $this->input->post('phone_no');
		$input['email'] = $this->input->post('email');
		$input['address'] = $this->input->post('address');
		$input['oku_status'] = $this->input->post('oku_status');
		$input['study_status'] = $this->input->post('study_status');
		$input['academic_lavel'] = $this->input->post('academic_lavel');
		$input['academic_institution'] = $this->input->post('academic_institution');
		$input['occupation'] = $this->input->post('occupation');
		
		if($input['study_status'] == 0){ 
			//if it still a student
			$input['occupation'] = '';	
		}else{ 
			//if it has been working
			$input['academic_level'] = null;
			$input['academic_institution'] = '';
		}

		if(!empty($this->input->post('id'))){
			$family_id = $this->input->post('id');
			$this->family->editFamily($input,$family_id);
		}else{
			$this->family->createFamily($input);
		}
		$this->staffDetail($staff_id);
	}

	public function createQualification()
	{
		$staff_id = $this->uri->segment(4);

		if(!$this->input->post()){
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}

		$input['user_id'] 	 	= $staff_id;
		$input['level_id'] 	 	= $this->input->post('level_id');
		$input['program'] 	 	= $this->input->post('program');
		$input['institution']	= $this->input->post('institution');
		$input['cgpa'] 			= $this->input->post('cgpa');
		$input['year']		 	= $this->input->post('year');

		if(!empty($this->input->post('id'))){
			$academic_id = $this->input->post('id');
			$this->academic->editQualification($input,$academic_id);

			$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$staff_id.'/qualifications'.'/','attachment');
			if ($uploaded){
	        	$temp = explode('/', $uploaded['file_type']); 
				$attachment = 
					array(
						'user_id' => $staff_id,
						'academic_qualification_id' => $academic_id,
						'attachment_name' => $uploaded['file_name'], 
						'location' => '/storage/hr/profiling/'.$staff_id.'/qualifications'.'/'.$uploaded['file_name'],
						'file_type' => $uploaded['file_type'],
						'file_ext' => $temp[1],
						'mask_id' => time().uniqid(),
						'is_delete' => 0
					);
				$attachmentID = $this->input->post('attachmentID');
				if ($attachmentID) {
					$this->academic_attachment->editAttachment($attachment, $attachmentID);
				}else{
					$this->academic_attachment->createAttachment($attachment);
				}
			}

		}else{
	        $qualification_id = $this->academic->createQualification($input);
			$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$staff_id.'/qualifications'.'/','attachment');
			
			if ($uploaded){
	        	$temp = explode('/', $uploaded['file_type']); 
				$attachment = 
					array(
						'user_id' => $staff_id,
						'academic_qualification_id' => $qualification_id,
						'attachment_name' => $uploaded['file_name'], 
						'location' => '/storage/hr/profiling/'.$staff_id.'/qualifications'.'/'.$uploaded['file_name'],
						'file_type' => $uploaded['file_type'],
						'file_ext' => $temp[1],
						'mask_id' => time().uniqid(),
						'is_delete' => 0
					);
				$this->academic_attachment->createAttachment($attachment);
			}
		}
		$this->staffDetail($staff_id);
	}

	public function createMembership()
	{
		$staff_id = $this->uri->segment(4);

		if(!$this->input->post()){
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}
		
		$input['professional_body'] = $this->input->post('professional_body');
		$input['certificate'] = $this->input->post('certificate');
		$input['membership'] = $this->input->post('membership');
		$input['membership_no'] = $this->input->post('membership_no');
		$input['year'] = $this->input->post('year');
		$input['user_id'] = $staff_id;

		if(!empty($this->input->post('id'))){

			$id = $this->input->post('id');
			$this->promember->editMembership($input,$id);

			$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$staff_id.'/membership'.'/','attachment');
			if ($uploaded){
	        	$temp = explode('/', $uploaded['file_type']); 
				$attachment = 
					array(
						'user_id' => $staff_id,
						'professional_membership_id' => $id,
						'attachment_name' => $uploaded['file_name'], 
						'location' => '/storage/hr/profiling/'.$staff_id.'/membership'.'/'.$uploaded['file_name'],
						'file_type' => $uploaded['file_type'],
						'file_ext' => $temp[1],
						'mask_id' => time().uniqid(),
						'is_delete' => 0
					);
				
				$attachmentID = $this->input->post('attachmentID');
				if($attachmentID){
					$this->promember_attachment->editAttachment($attachment,$attachmentID);
				}else{
					$this->promember_attachment->createAttachment($attachment);
				}
			}
		}else{
			$membership_id = $this->promember->createMembership($input);

			$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$staff_id.'/membership'.'/','attachment');
			if ($uploaded){
	        	$temp = explode('/', $uploaded['file_type']); 
				$attachment = 
					array(
						'user_id' => $staff_id,
						'professional_membership_id' => $membership_id,
						'attachment_name' => $uploaded['file_name'], 
						'location' => '/storage/hr/profiling/'.$staff_id.'/membership'.'/'.$uploaded['file_name'],
						'file_type' => $uploaded['file_type'],
						'file_ext' => $temp[1],
						'mask_id' => time().uniqid(),
						'is_delete' => 0
					);
					$this->promember_attachment->createAttachment($attachment);
			}
		}
		$this->staffDetail($staff_id);
	}

	public function createJobHistory()
	{
		$staff_id = $this->uri->segment(4);

		if(!$this->input->post()){
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}
		$input			  = $this->input->post();
		$input['user_id'] = $staff_id;
		$input['date_enter'] = date('Y-m-d',strtotime($input['date_enter']));
		$input['date_exit'] = date('Y-m-d',strtotime($input['date_exit']));

		if(!empty($this->input->post('id'))){
			$jobs_id = $this->input->post('id');
			$this->jobs->editJobs($input,$jobs_id);

		}else{
			$this->jobs->createJobs($input);
		}
		$this->staffDetail($staff_id);
	}

	public function createBanks()
	{
		$staff_id = $this->uri->segment(4);
		if(!$this->input->post())
		{
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}

		$data = array(
			'user_id'		=>  $staff_id,
			'bank_id'		=>  $this->input->post('bank_id'),
			'branch'		=>  $this->input->post('branch'),
			'acc_no'		=>  $this->input->post('acc_no'),
			'status'		=>  $this->input->post('status'),
		);

		$upload_path = 'application/storage/application/storage/hr/profiling/'.$staff_id.'/bank';
		$upload = $this->uploadToStorage($upload_path,'file');
	
		if(!empty($this->input->post('id'))){
			$id = $this->input->post('id');
			$bank_detail_id = $this->bank->editBank($data,$id);

			if($upload && $bank_detail_id)
			{

				$attachment = array
				(
					'user_id' 			=> $staff_id,
					'bank_detail_id' 	=> $bank_detail_id,
					'attachment_name' 	=> $upload['file_name'],
					'location'			=> $upload_path.'/'.$upload['file_name'],
					'file_type' 		=> $upload['file_type'],
					'file_ext' 			=> $upload['file_ext'],
					'mask_id' 			=> uniqid(),
					'is_delete' 		=> 0,
				);
				$this->bank->updateAttachment($attachment,$attachment['bank_detail_id']);
			}
		}else{
			$this->bank->createBank($data);
		}
		$this->staffDetail($staff_id);
	}

	public function createRecognition()
	{
		$staff_id = $this->uri->segment(4);

		if(!$this->input->post()){
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}
		
		$input['achievement'] = $this->input->post('achievement');
		$input['award'] = $this->input->post('award');
		$input['year'] = $this->input->post('year');
		$input['user_id'] = $staff_id;
		
		if (!empty($this->input->post('id'))) {
			$id = $this->input->post('id');
			$this->recognition->editRecognition($input,$id);
			$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$staff_id.'/recognition'.'/','attachment');
			if ($uploaded){
	        	$temp = explode('/', $uploaded['file_type']); 
				$attachment = 
					array(
						'user_id' => $staff_id,
						'recognition_id' => $id,
						'attachment_name' => $uploaded['file_name'], 
						'location' => '/storage/hr/profiling/'.$staff_id.'/recognition'.'/'.$uploaded['file_name'],
						'file_type' => $uploaded['file_type'],
						'file_ext' => $temp[1],
						'mask_id' => time().uniqid(),
						'is_delete' => 0
					);
					$attachmentID = $this->input->post('attachmentID');
					if($attachmentID){
						$this->recognition_attachment->editAttachment($attachment,$attachmentID);
					}else{
						$this->recognition_attachment->createAttachment($attachment);
					}
			}

		}else{
			$recognition_id = $this->recognition->createRecognition($input);
			$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$staff_id.'/recognition'.'/','attachment');
			if ($uploaded){
	        	$temp = explode('/', $uploaded['file_type']); 
				$attachment = 
					array(
						'user_id' => $staff_id,
						'recognition_id' => $recognition_id,
						'attachment_name' => $uploaded['file_name'], 
						'location' => '/storage/hr/profiling/'.$staff_id.'/recognition'.'/'.$uploaded['file_name'],
						'file_type' => $uploaded['file_type'],
						'file_ext' => $temp[1],
						'mask_id' => time().uniqid(),
						'is_delete' => 0
					);
					$this->recognition_attachment->createAttachment($attachment);
			}
		}
		$this->staffDetail($staff_id);
	}
		
	public function createRecurringPay()
	{
		$staff_id = $this->uri->segment(4);

		if(!$this->input->post()){
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}
		$input 					= $this->input->post();
		$input['user_id'] 		= $staff_id;
		$input['date_start'] 	= date('Y-m-d',strtotime($input['date_start']));
		$input['date_end'] 		= date('Y-m-d',strtotime($input['date_end']));

		$id = $this->input->post('id');
		$this->recurring->editRecurring($input,$id);
		
		$this->staffDetail($staff_id);
	}

	public function createRecurringDeduct()
	{
		$staff_id = $this->uri->segment(4);

		if(!$this->input->post()){
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}

		$input = $this->input->post();
		$input['user_id'] = $staff_id;
		$input['date_start'] = date('Y-m-d',strtotime($input['date_start']));
		$input['date_end'] = date('Y-m-d',strtotime($input['date_end']));

		$id = $this->input->post('id');
		$this->recurring->editRecurring($input,$id);

		$this->staffDetail($staff_id);
	}

	public function createThirdParty()
	{
		$staff_id = $this->uri->segment(4);

		if (!$this->input->post()) {
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}
		$input = $this->input->post();
		$input['user_id'] = $staff_id;
		$input['date_start'] = date('Y-m-d',strtotime($input['date_start']));
		$input['date_end'] = date('Y-m-d',strtotime($input['date_end']));

		if (!empty($this->input->post('id'))) {
			$id = $this->input->post('id');
			$this->thirdParty->editPayment($input,$id);
		}else{
			$this->thirdParty->createPayment($input);
		}
		$this->staffDetail($staff_id);
	}

	public function createAdditionalAttachment()
	{
		$staff_id = $this->uri->segment(4);
		if (!$this->input->post()) {
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}
		$input = $this->input->post();

		$id = $this->input->post('id');
		if (!empty($id)) {
			$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$staff_id.'/','attachment');
			if($uploaded){
				$temp = explode('/', $uploaded['file_type']); 
		    	$data = array(
		    		'user_id' 			=> $staff_id,
		    		'detail'  			=> $input['detail'],
		    		'description' 		=> $input['description'],
		    		'attachment_name'	=> $uploaded['file_name'],
		    		'location'			=> '/storage/hr/profiling/'.$staff_id.'/'.$uploaded['file_name'],
		    		'file_type'			=> $uploaded['file_type'],
		    		'file_ext'			=> $temp[1],
		    		'mask_id'			=> time().uniqid()
		    	);
			}else{
		    	$data = array(
		    		'user_id'			=> $staff_id,
		    		'detail'			=> $input['detail'],
		    		'description'		=> $input['description']
		    		);
			}
		    $this->attachment->editPersonalAttachment($data,$id,null);
		}else{
			//create new 
			$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$staff_id.'/','attachment');
			if($uploaded){
				$temp = explode('/', $uploaded['file_type']); 
		    	$data = array(
		    		'user_id' 			=> $staff_id,
		    		'detail'  			=> $input['detail'],
		    		'description' 		=> $input['description'],
		    		'attachment_name'	=> $uploaded['file_name'],
		    		'location'			=> '/storage/hr/profiling/'.$staff_id.'/'.$uploaded['file_name'],
		    		'file_type'			=> $uploaded['file_type'],
		    		'file_ext'			=> $temp[1],
		    		'mask_id'			=> time().uniqid()
		    	);
		    	$this->attachment->createPersonalAttachment($data);
			}else{
				$data = array(
		    		'user_id' 			=> $staff_id,
		    		'detail'  			=> $input['detail'],
		    		'description' 		=> $input['description'],
		    	);
		    	$this->attachment->createPersonalAttachment($data);
			}
		}
		$this->staffDetail($staff_id);
	}

	public function createPCB()
	{
		$staff_id = $this->uri->segment(4);
		if (!$this->input->post()) {
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}
		$input = $this->input->post();
		$input['user_id'] = $staff_id;

		if (!empty($this->input->post('id'))){
			$id = $this->input->post('id');
			$this->pcb->editPCB($input,$id);
		}else{
			$this->pcb->createPCB($input);
		}
		$this->staffDetail($staff_id);
	}

	public function updateBasicPay()
	{
		$id = $this->input->post('id');
		$input = array(
			// 'scale_group'	=> $this->input->post('scale'),
			'staff_grade_id'=> $this->input->post('staff_grade_id'),
			'amount'		=> $this->input->post('amount'),
			'start_date'	=> date('Y-m-d',strtotime($this->input->post('start_date'))),
			'end_date'		=> date('Y-m-d',strtotime($this->input->post('end_date'))),
			'reason'		=> $this->input->post('reason'),
			'status'		=> $this->input->post('status'),
		);
		$this->basic_pay->updateBasicPay($input,$id);

		echo json_encode(array('status' => 'success','msg' => 'You have update one record for basic payment'));
		return true;
	}

	public function updateContractElement()
	{
		$id = $this->input->post('id');
		$input = array(
			'contract_hiring_type_id' 	=> $this->input->post('type_id'),
			'duration'					=> $this->input->post('duration'),
			'confirmation'				=> $this->input->post('confirmation'),
			'confirmation_date'			=> (!empty($this->input->post('confirmation_date')))? date('Y-m-d',strtotime($this->input->post('confirmation_date'))) : null,
			'probation' 				=> $this->input->post('probationary_period'),
			'probation_duration'		=> $this->input->post('probationary_duration'),
			'er_notice'					=> $this->input->post('er_notice'),
			'er_notice_duration'		=> $this->input->post('er_notice_duration'),
			'ee_notice' 				=> $this->input->post('ee_notice'),
			'ee_notice_duration' 		=> $this->input->post('ee_notice_duration'),
			'resign_date'				=> (!empty($this->input->post('resign_date')))? date('Y-m-d',strtotime($this->input->post('resign_date'))) : null,
			'last_working_date'			=> (!empty($this->input->post('last_working_date')))?date('Y-m-d',strtotime($this->input->post('last_working_date'))) : null,
			'phy_last_working_date'		=> (!empty($this->input->post('phy_last_working_date')))?date('Y-m-d',strtotime($this->input->post('phy_last_working_date'))) : null,
			
		);
		$this->contract->updateContract($input,$id);

		echo json_encode(array('status' => 'success','msg' => 'You have update one record for contract element'));
		return true;
	}

	public function removeAddress()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->address->editAddress($input, $id);
		echo json_encode(array('status' => 'ok'));
		return exit;
	}

	public function removeFamily()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->family->removeFamily($input, $id);
		echo json_encode(array('status' => 'ok'));
		return exit;
	}

	public function removeAcademicQualification()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->academic->editQualification($input, $id);
		echo json_encode(array('status' => 'ok'));
		return exit;
	}

	public function removeJobs()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->jobs->editJobs($input, $id);
		echo json_encode(array('status' => 'ok'));
		return exit;
	}

	public function removeMembership()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->promember->editMembership($input, $id);
		echo json_encode(array('status' => 'ok'));
		return exit;
	}

	public function removeLicense()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->license->editLicense($input, $id);
		echo json_encode(array('status' => 'ok'));
		return exit;
	}

	public function removeRecognition()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->recognition->editRecognition($input,$id);
		echo json_encode(array('status' => 'ok'));
		return exit;
	}

	public function removeBank()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->bank->editBank($input,$id);
		echo json_encode(array('status' => 'ok'));
		return exit;
	}

	public function removeRecurringPay()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->recurring->editRecurring($input,$id);
		echo json_encode(array('status' => 'ok','msg' => 'Successfully remove payment record'));
		return exit;
	}
	
	public function removeRecurringDeduct()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->recurring->editRecurring($input,$id);
		echo json_encode(array('status' => 'ok','msg' => 'Successfully remove deduction record'));
		return exit;
	}
	
	public function removeThirdParty()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->thirdParty->editPayment($input,$id);
		echo json_encode(array('status' => 'ok', 'msg' => 'Successfully remove third party payment'));
		return exit;
	}

	public function removePCB()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->pcb->editPCB($input,$id);

		echo json_encode(array('status' => 'ok','msg' => 'Successfully remove PCB'));
		return exit;
	}

	public function removeAdditionalPersonalData()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->attachment->editPersonalAttachment($input,$id,null);

		echo json_encode(array('status' => 'ok','msg' => 'Successfully remove additional personal data'));
		return exit;
	}

	public function removeBasicPay()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->basic_pay->updateBasicPay($input,$id);
		echo json_encode(array('status' => 'ok','msg' => 'Successfully remove basic payment'));
		return exit;		
	}

	public function removeContractElement()
	{
		$id = $this->input->post('id');
		$input = array('is_delete' => 1);
		$this->contract->updateContract($input,$id);
		echo json_encode(array('status' => 'ok','msg' => 'Successfully remove contract element'));
		return exit;
	}

	public function removeJoiningGroup()
	{
		$input = $this->input->post();
		$this->join_group->removeJoin(array('is_delete' => 1),$input['id']);
		echo json_encode(array('status' => 'success','msg' => 'Successfully removed employment detail'));
		return true;
	}

	public function updateEmploymentDetail()
	{
		$input = $this->input->post();
		$datagrade = (!empty($input['position']))? $this->model_general->fetchSingle('company__position', array('grade'), array('id' => $input['position'])):'';
		$data = array(
			'reason_id'				=> $input['reason'],
			'position_id' 			=> $input['position'],
			'position_information'	=> $input['pos_info'],
			'employee_grade'		=> $datagrade['grade'],
			'user_reporting_id'		=> $input['reporting_to'],
			'business_entity_id'	=> $input['business_entity'],
			'branch_id'				=> $input['branch'],
			'personnel_area_id'		=> $input['personnel_area'],
			'personal_subarea_id'	=> $input['personal_area'],
			'employee_group_id'		=> $input['emp_group'],
			'contract_element_id'	=> $input['contract_elem'],
			'employee_subgroup_id'	=> $input['emp_subgroup'],
			'is_active'				=> $input['status'],
		);
		$this->join_group->updateJoin($data,$input['id']);
		redirect($input['url']);
	}

	public function removeStatutoryDetails()
	{
		$input = $this->input->post();
		$data = array(
			'is_deleted' => 1
		);

		$this->stats->updateStatutory($data,$input['id']);
		echo json_encode(array('status' => 'success','msg' => 'Successfully deleted statutory details'));
	}

	public function updateStatutory()
	{
		$input = $this->input->post();
		$data = array(
			'ee_epf_no'			=> $input['epf_no'],
			'er_rate'			=> $input['er_rate'],
			'er_percent'		=> $input['er_percent'],
			'ee_rate'			=> $input['ee_rate'],
			'ee_percent'		=> $input['ee_percent'],
			'ee_socso'			=> $input['socso'],
			'ee_income_tax'		=> $input['income_tax'],
			'ee_pcb_deduction'	=> $input['pcb_deduction'],
			'ee_zakat_deduction'=> $input['zakat_deduction'],
			'status'			=> $input['status'],
			'year'				=> $input['year'],					
		);

		$this->stats->updateStatutory($data,$input['id']);
		redirect($input['url']);
	}

	public function createaActionType()
	{
		$input = $this->input->post();
		$data = array(
			'icon' 			=> $input['icon'],
			'color' 		=> $input['color'],
			'type'			=> $input['type'],
			'is_delete'		=> 0
		);
		$this->action->createActionType($data);
		redirect($input['redirect']);
	}

	public function createHiringReason()
	{
		$input = $this->input->post();
		$data = array(
			'type' 			=> $input['type'],
			'is_delete'		=> 0,
		);
		$this->general_model->insert('_ref__hiring_reason',$data);
		redirect($input['redirect']);
	}

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

		$company_position  = array(
			'parent_id' => ($input['level'])?$input['level']:0,
			'position'	=> $input['position'],
			'status'	=> 0,
			'is_delete'	=> 0,
		);
		$this->general_model->insert('company__position',$company_position);

		$level = $this->general_model->get_byFilter('company__position',$select=array('*'),$filter=array('id' => $input['level']))[0];

		$scale = array(
			'level'			=> $level->id,
			'grade'			=> $input['grade'],
			'indicator'		=> $input['indicator'],
			'designation'	=> $input['position'],
		);

		$this->general_model->insert('_ref__salary_scale',$scale);
		redirect($input['redirect']);
	}	

	public function createDesignation()
	{
		$input = $this->input->post();
		$designation  = array(
			'position_id'	=> $input['position'],
			'designation'	=> $input['designation'],
			'is_delete'		=> 0,
		);
		$this->general_model->insert('_ref__designation',$designation);
		redirect($input['redirect']);
	}

	public function createBranch()
	{
		$input = $this->input->post();
		$branch = array(
			'company_id' => 1,
			'name'		 => $input['branch'],
			'address'	 => $input['address'],
			'postcode'	 => $input['postcode'],
			'city'		 => $input['city'],
			'state_id'	 => $input['state'],
			'country_id' => $input['country'],
			'latitude'	 => $input['latitude'],
			'longitude'	 => $input['longitude'],
			'phone'		 => $input['phone'],
			'fax'		 => $input['fax'],
			'email'		 => $input['email'],
			'status'	 => 0, 
		);

		$this->general_model->insert('company__branch',$branch);
		redirect($input['redirect']);
	}

	public function createDivision()
	{
		$input = $this->input->post();
		$data  = array(
			'code' 			=> $input['code'],
			'name' 			=> $input['division'],
			'department_id'	=> ($input['department_id'])?$input['department_id']:null,
		);
		$this->general_model->insert('company__division',$data);
		redirect($input['redirect']);
	}

	public function createDepartment()
	{
		$input = $this->input->post();
		$data = array(
			'branch_id' 	=> $input['branch'],
			'name'			=> $input['department'],
			'description'	=> ($input['description'])?$input['description']:'',
		);
		$this->general_model->insert('company__department',$data);
		redirect($input['redirect']);
	}

	public function createEmployeeGroup()
	{
		$input = $this->input->post();
		$data = array(
			'type' => $input['type']
		);
		$this->general_model->insert('_ref__employee_group',$data);
		redirect($input['redirect']);
	}

	public function createContractElement()
	{
		$input = $this->input->post();
		$data = array(
			'type' 	=> $input['contract']
		);

		$this->general_model->insert('_ref__employee_contract_type',$data);
		redirect($input['redirect']);
	}

	public function createAddressType()
	{
		$input = $this->input->post();
		$data = array(
			'type'	=> $input['type']
		);

		$this->general_model->insert('_ref__residence_type',$data);
		redirect($input['redirect']);
	}

	public function createRelation()
	{
		$input = $this->input->post();
		$data = array(
			'relations' 		=> $input['relation']
		);
		$this->general_model->insert('_ref__relationship',$data);
		redirect($input['redirect']);
	}

	public function createAcademicLevel()
	{
		$input = $this->input->post();
		$data = array(
			'level' => $input['level'],
			'seq'	=> 10,
		);
		$this->general_model->insert('_ref__academic',$data);
		redirect($input['redirect']);
	}

	public function createContractType()
	{
		$input = $this->input->post();
		$data = array(
			'type'	=> $input['type'],
			'is_delete' => 0,
			);
		$this->general_model->insert('_ref__contract_type',$data);
		redirect($input['redirect']);
	}

	public function createConfirmationType()
	{
		$input = $this->input->post();
		$data = array(
			'type'			=> $input['type'],
			'is_delete'		=> 0,
		);
		$this->general_model->insert('_ref__contract_confirmation',$data);
		redirect($input['redirect']);
	}

	public function createBankRef()
	{
		$input = $this->input->post();
		$data = array(
			'name'		=> $input['bank'],
			'shortcode'	=> $input['shortcode'],
		);
		$this->general_model->insert('_ref__bank',$data);
		redirect($input['redirect']);
	}

	public function createTitles()
	{
		$input = $this->input->post();
		
		$data = array(
			'title' => $input['title'],

		);
		$this->general_model->insert('_ref__title',$data);
		redirect($input['redirect']);
	}

	public function createReligion()
	{
		$input = $this->input->post();
		$data = array(
			'name' => $input['name'], 
		);
		$this->general_model->insert('_ref__religion',$data);
		redirect($input['redirect']);
	}

	public function createRaces()
	{
		$input = $this->input->post();
		$data = array(
			'race' => $input['race'], 
		);
		$this->general_model->insert('_ref__race',$data);
		redirect($input['redirect']);
	}

	//mode
	//	[0 / null => additional personal data]
	//  [1 => academic qualification]
	//	[2 => professional membership]
	//	[3 => professional license]
	// 	[4 => recognition]
	// 	[5 => bank details]
	// 	[6 => professional academic]
	public function openAttachment($mask_id,$mode = null)
	{

		if($mode == 0 || !$mode)
		{
			$attachment = $this->attachment->fetchPersonalAttachment(null,$mask_id);
		}
		
		if ($mode == 1) 
		{
			$attachment = $this->academic_attachment->fetchAttachment(null, $mask_id);
		}
		
		if($mode == 2)
		{
			$attachment = $this->promember_attachment->fetchAttachment(null,$mask_id);
		}
		
		if($mode == 3)
		{
			$attachment = $this->license_attachment->fetchAttachment(null,$mask_id);
		}
		
		if($mode == 4)
		{
			$attachment = $this->recognition_attachment->fetchAttachment(null,$mask_id);
		}

		if($mode == 5)
		{
			// $attachment = $this->
			die(debug('try to open bank detail attachments'));
		}

		if($mode == 6)
		{
			$attachment = $this->professional_academic_attachment->fetchAttachment(null,$mask_id);
		}

		if($mode == 8)
		{
			$attachment = $this->professional_academic_attachment->fetchAttachment_edu_in_progress(null,$mask_id);
		}

		if(($_SESSION['user']['id'] == $attachment[0]->user_id) || ($_SESSION['module_data']['role'] == 'admin'))
		{
			$this->load->library('fileaccess');
			$file_extension = $attachment[0]->file_ext;
			// debug($attachment);
			// die();
			switch ($file_extension) {
			 	case 'image/gif':
			 		$this->fileaccess->gif(str_replace('application', '', $attachment[0]->location));
			 		break;
			 	case 'image/jpeg':
			 		$this->fileaccess->jpeg(str_replace('application', '', $attachment[0]->location));
			 		break;
			 	case 'image/png':
					$this->fileaccess->png(str_replace('application', '', $attachment[0]->location));
			 		break;
			 	case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
					$this->fileaccess->doc(str_replace('application', '', $attachment[0]->location));
			 		break;
			 	case 'application/pdf':
			 		$this->fileaccess->pdf(str_replace('application', '', $attachment[0]->location));
			 		break;
			 	case 'pdf':
			 		$this->fileaccess->pdf(str_replace('application', '', $attachment[0]->location));
			 		break;
			 	case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
			 		$this->fileaccess->xls(str_replace('application', '', $attachment[0]->location));
			 		break;
			 	default:
			 		$this->load->view('hr/staff-profiling/page/error/loader',array('loader' => $file_extension));
			 		break;
			 }
		}else{
			$this->load->view('hr/staff-profiling/page/error/permission');
		}
	}

	//------------------------------------
	// private helper
	//------------------------------------
	private function ObjToArray($obj,$single=false) 
	{
		return (!empty($obj)) ? json_decode(json_encode(($single)?$obj[0]:$obj),true) : NULL;
	}

	private function uploadToStorage($path,$file_name)
	{
		$config['upload_path']          = $path;
		$config['allowed_types']        = 'gif|jpg|jpeg|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($file_name))
        {
			$error = array('error' => $this->upload->display_errors());
        }
        else
        {
        	$uploaded = $this->upload->data();
        	return $uploaded;
        }
	}

	function get_workflow()
	{
		$input 		= $this->input->post();
		
		$workflowID = $input['workflowID'];

		$dataWorkflow = $this->action->fetch_works($workflowID);

		if($dataWorkflow)
		{
			$data = array
			(
				'status' 		=> 'success',
				'msg'			=> 'Successfully retrieved data workflow',
				'workflowID'	=> $workflowID,
				'workflowName'	=> $dataWorkflow[0]->name,
			);
		}else{
			$data = array
			(
				'status' 		=> 'failed',
				'msg' 			=> 'failed to retrieved data workflow'
			);
		}

		echo json_encode($data);
	}

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

		$data['role'] = $this->logged_module['role'];

		if($data['role'] != 'admin'){
			redirect(base_url('/hr/staffprofile/staffDetail/'.$_SESSION['user']['id']));
		}
		$data['page_setup'] 		= $this->template->pageSetup('Staff Profiling', '', 'Incomplete List');
		$data['company'] 			= $this->model_company->getCompanies(1);
		$data['staff']				= $this->model_user->getUsers(null,null);
		$data['staff_detail']		= $this->model_profiling->getIncompleteDetailList('incomplete');
		$data['total_incomplete']	= $this->model_profiling->countIncompleteDetailList('incomplete')[0];
		$data['total_complete']		= $this->model_profiling->countIncompleteDetailList('complete')[0];

		$this->template->view('hr/staff-profiling/page/list/incompleteList', $data);
	}

	public function completeList()
	{
		$this->load->model('hr/model_profiling');
		$data['role'] = $this->logged_module['role'];

		if($data['role'] != 'admin'){
			redirect(base_url('/hr/staffprofile/staffDetail/'.$_SESSION['user']['id']));
		}
		$data['page_setup'] 		= $this->template->pageSetup('Staff Profiling', '', 'Complete List');
		$data['staff']				= $this->model_user->getUsers(null,null);
		$data['staff_detail']		= $this->model_profiling->getIncompleteDetailList('complete');
		$data['total_incomplete']	= $this->model_profiling->countIncompleteDetailList('incomplete')[0];
		$data['total_complete']		= $this->model_profiling->countIncompleteDetailList('complete')[0];
		$data['company'] 			= $this->model_company->getCompanies(1);

		$this->template->view('hr/staff-profiling/page/list/completeList', $data);
	}

	public function updateProfileIncompleteList()
	{
		$data['role'] = $this->logged_module['role'];
		if($data['role'] != 'admin'){
			redirect(base_url('/hr/staffprofile/staffDetail/'.$_SESSION['user']['id']));
		}
		
		$this->load->model('hr/model_profiling');

		$status_id = (!empty($this->input->post('status_id')))?$this->input->post('status_id'):0;

		$data['title'] 				= ($status_id == 0)?'Incomplete':'Complete';
		$data['page_setup'] 		= $this->template->pageSetup('Staff Profiling', '', 'Personal Data Update '.$data['title'].' List');
		$data['staff']				= $this->model_user->getUsers(null,null);
		$data['staff_detail']		= $this->model_profiling->update_profile_list($status_id, '2021-06-01');
		$data['company'] 			= $this->model_company->getCompanies(1);

		$this->template->view('hr/staff-profiling/page/list/updateProfileIncompleteList', $data);
	}

	function getWorkingExperience()
	{
		$workingExperience_id  	= $this->input->post('workingExperience_id');
		$profiling_id   		= $this->input->post('profiling_id');

		$WorkingExperienceData 	= $this->working_experience->find($workingExperience_id);

		$query = $this->db->last_query();

		if($WorkingExperienceData)
        {
          	print json_encode(array(
                "status" 				=> "success",
                "WorkingExperience"		=> $WorkingExperienceData,
                "query"					=> $query
            ));

        }
        else
        {
        	print json_encode(array(
                "status" 	=> "failed",
                "msg" 	=> "failed",
                "query"		=> $query
            ));
        }
	}
	
	function save_editWorkingExperience()
	{
		// $working_experience_id  = $this->input->post('id');
		// $profiling_id = $this->input->post('profiling_id');

		// $deleteOldWorkingExperience = $this->working_experience->removeWorkingExperience($working_experience_id);

		$updateData = array(
			'date_from'		=> $this->input->post('date_from'),
			'date_to'		=> $this->input->post('date_to'),
			'experience' 	=> $this->input->post('working_experience'),
			'updated_by'	=> $this->session->userdata('user')['id'],
			'updated_at'	=> date('Y-m-d H:i:s'),
		);

		// $where = array
		// (
		// 	'id'			=> $this->input->post('id'),
		// 	'profiling_id' 	=> $this->get_profiling_id($profiling_id),
		// 	'user_id'		=> $this->session->userdata('user')['id'],
		// );
        
		$updateWorkingExperience = $this->working_experience->editWorkingExperience($updateData, $this->input->post('id'));

        if($updateWorkingExperience)
        {
			print json_encode(array(
			    "status"    			 	=> "success",
			    "msg"						=> "successfully update Experience In SALIHIN",
			    "updateWorkingExperience" 	=> $updateWorkingExperience,
			    "redirect"	 				=> base_url('hr/staffprofile/staffDetail/'.$this->session->userdata('user')['id'])
			));

        } else {
			print json_encode(array(
				"status" 	=> "failed",
				"msg" 		=>  "failed",
				"redirect"	=> base_url('hr/staffprofile/staffDetail/'.$this->session->userdata('user')['id'])
			));
        }
	}

	function deleteWorkingExperience()
	{
		$working_experience_id  = $this->input->post('id');
		$profiling_id 			= $this->input->post('profiling_id');

		$deleteWorkingExperience = $this->working_experience->removeWorkingExperience($working_experience_id);

        if($deleteWorkingExperience)
        {
			print json_encode(array(
			    "status"    			 	=> "success",
			    "msg"						=> "Experience In SALIHIN deleted",
			    "deleteWorkingExperience" 	=> $deleteWorkingExperience,
			    "redirect"	 				=> base_url('hr/staffprofile/staffDetail/'.$this->session->userdata('user')['id'])
			));

        } else {
			print json_encode(array(
				"status" 	=> "failed",
				"msg" 		=>  "failed",
				"redirect"	=> base_url('hr/staffprofile/staffDetail/'.$this->session->userdata('user')['id'])
			));
        }
	}

	function getProfessionalAcademic()
	{
		$professional_academic_id  	= $this->input->post('professional_academic_id');
		$profiling_id   			= $this->input->post('profiling_id');

		$professional_academicData 	= $this->professional_academic->fetchProfessionalAcademic(null,false,$profiling_id,$professional_academic_id);

		$query = $this->db->last_query();

		if($professional_academicData)
        {
          	print json_encode(array(
                "status" 					=> "success",
                "professional_academic"		=> $professional_academicData,
                "query"						=> $query
            ));

        }
        else
        {
        	print json_encode(array(
                "status" 	=> "failed",
                "msg" 		=> "failed",
                "query"		=> $query
            ));
        }
	}

	function save_editProfessionalAcademic()
	{
		$professional_academic_id =  $this->input->post('id');

		$query_attachment = $this->db->select('*')
									->where('is_delete',0)
									->where('professional_academic_id',$professional_academic_id)
									->get('user__professional_academic_attachment')
									->result_array()[0];

		$type = $this->input->post('type');
		$professional_type = ($type == 0)?'education':'certificate'; 
		

		$updateData = array(
	        'level' 			=> ($type == 0)?$this->input->post('level'):'',
	        'associate_name'  	=> $this->input->post('associate_name'),
	        'program'  			=> $this->input->post('program'),
	        'date_finish'  		=> $this->input->post('date_finish'),
	        'result'			=> $this->input->post('result'),
	        'updated_by'		=> $this->session->userdata('user')['id'],
			'updated_at'		=> date('Y-m-d H:i:s')
		);
        
		$updateProfessionalAcademic = $this->professional_academic->editProfessionalAcademic($updateData,$professional_academic_id);

        if($updateProfessionalAcademic)
        {	
        	if(isset($_FILES['attachment_file']))
        	{
        		$uploaded = '';
        		if($query_attachment)
				{
					if($this->input->post('attachment_name') != $query_attachment['attachment_name'])
					{
						$updateoldattachment = array
			        	(
			        		'is_delete'		=> 1,
			        		'updated_by'	=> $this->session->userdata('user')['id'],
			        		'updated_at'	=> date('Y-m-d H:i:s')
			        	);

						$deleteOldProfessionalAcademicAttachment = $this->professional_academic_attachment->editAttachment($updateoldattachment,$query_attachment['id'],$professional_academic_id);
	
						$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$this->input->post('staff_id').'/professional_academic'.'/'.$professional_type.'/','attachment_file');
					}else
					{
						$uploaded = '';
					}
				}else{

					$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$this->input->post('staff_id').'/professional_academic'.'/'.$professional_type.'/','attachment_file');
				}

				if($uploaded)
				{
					$attachment = array
					(
	        			'user_id'						=> $this->input->post('staff_id'),
	        			'professional_academic_id'		=> $professional_academic_id,
	        			'location'						=> 'storage/hr/profiling/'.$this->input->post('staff_id').'/professional_academic'.'/'.$professional_type.'/'.$uploaded['file_name'],
						'attachment_name' 				=> $uploaded['client_name'], 
						'file_type' 					=> $uploaded['file_type'],
						'file_ext' 						=> $uploaded['file_type'],
	        			'mask_id' 						=> '6'.$updateProfessionalAcademic.''.date('Ymd').''.uniqid(),
		        		'created_by'					=> $this->session->userdata('user')['id']
					);

					$save_attachment = $this->professional_academic_attachment->createAttachment($attachment);

					// echo $this->db->last_query();
					// debug($attachment);
					// die();
				}
			}else{
				// if($query_attachment)
				// {
				// 	$updateoldattachment = array
				//       	(
				//       		'is_delete'		=> 1,
				//       		'updated_by'	=> $this->session->userdata('user')['id'],
				//       		'updated_at'	=> date('Y-m-d H:i:s')
				//       	);

				// 	$deleteProfessionalAcademicAttachment = $this->professional_academic_attachment->editAttachment($updateoldattachment,$query_attachment['id'],$professional_academic_id);
				// }
			}

			print json_encode(array(
			    "status"     					=> "success",
				"msg" 							=> "successfully update professional ".$professional_type,
			    "updateProfessionalAcademic" 	=> $updateProfessionalAcademic,
			    "redirect"						=> base_url('hr/staffprofile/staffDetail/'.$this->input->post('staff_id'))
			));

        } else {
			print json_encode(array(
				"status" 		=> "failed",
				"msg" 			=> "failed",
				"redirect"		=> base_url('hr/staffprofile/staffDetail/'.$this->input->post('staff_id'))
			));
        }
	}

	function deleteProfessionalAcademic()
	{
		$professional_academic_id =  $this->input->post('id');
		$profiling_id =  $this->input->post('profiling_id');
		$type = $this->input->post('type');
		$professional_type = ($type == 0)?'education':'certificate'; 

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

		$deleteProfessionalAcademic = $this->professional_academic->editProfessionalAcademic($updateData,$professional_academic_id);

		$deleteProfessionalAcademicAttachment = $this->professional_academic_attachment->editAttachment($updateData,null,$professional_academic_id);

		if($deleteProfessionalAcademic)
        {
          print json_encode(array(
                "status"     					=> "success",
                "deleteProfessionalAcademic" 	=> $deleteProfessionalAcademic,
                "msg" 		    				=> "professional  ".$professional_type." deleted.",
                "redirect"						=> base_url('hr/staffprofile/staffDetail/'.$this->session->userdata('user')['id'])
            ));

        }
        else
        {
        	 print json_encode(array(
                "status" 	=> "failed",
                "msg" 		=> "failed",
                "redirect"	=> base_url('hr/staffprofile/staffDetail/'.$this->session->userdata('user')['id'])
            ));
        }
	}

	function getStudy()
	{
		$study_id  		= $this->input->post('study_id');
		$study_data 	= $this->user_pursuing_study->get_pursuing_study(null, false, null, $study_id);

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

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

	function save_editStudy()
	{
		$study_id  		= $this->input->post('study_id');

		$updateData = array(
	        'date_start' 		=> ($this->input->post('study_date_start'))?date('Y-m-d',strtotime($this->input->post('study_date_start'))):'0000-00-00',
	        'date_end'  		=> ($this->input->post('study_date_end'))?date('Y-m-d',strtotime($this->input->post('study_date_end'))):'0000-00-00',
	        'institution'  		=> $this->input->post('study_institution'),
	        'program'  			=> $this->input->post('study_program'),
			'progress_paper' 	=> $this->input->post('progress_paper'),
	        'status'			=> $this->input->post('study_status'),
		);
        
		$updateStudy = $this->user_pursuing_study->editPursuingStudy($updateData,$study_id);

        if($updateStudy){
			print json_encode(array(
			    "status"     	=> "success",
				"msg" 			=> "successfully update education in progress",
			    "updateStudy" 	=> $updateStudy,
			));

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

	function deleteStudy()
	{
		$study_id  		= $this->input->post('study_id');
		$profiling_id 	= $this->input->post('profiling_id');

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

		$deleteStudy = $this->user_pursuing_study->editPursuingStudy($updateData,$study_id,$profiling_id);

        if($deleteStudy){
			print json_encode(array(
			    "status"     	=> "success",
				"msg" 			=> "education in progress deleted",
			    "deleteStudy" 	=> $deleteStudy,
				"redirect"		=> base_url('hr/StaffProfile/staffDetail/'.$this->session->userdata('user')['id'])
			));

        } else {
			print json_encode(array(
				"status" 	=> "failed",
				"msg" 		=>  "failed",
				"redirect"	=> base_url('hr/StaffProfile/staffDetail/'.$this->session->userdata('user')['id'])
			));
        }
	}
	
	function getEmergency()
	{
		$emergency_id  		= $this->input->post('emergency_id');
		$case_emergency_data 	= $this->user_emergency->get_case_of_emergency(null, false, null, $emergency_id);

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

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

	function save_editEmergency()
	{
		$emergency_id  		= $this->input->post('emergency_id');


		$updateData = array(
	        'name' 			=> $this->input->post('name'),
	        'relation'  	=> $this->input->post('relation'),
	        'phone_no'  	=> $this->input->post('phone'),
	        'email'  		=> $this->input->post('email'),
	        'address'		=> $this->input->post('address'),
		);
        
		$updateEmergencyContact = $this->user_emergency->editCaseEmergency($updateData,$emergency_id);

        if($updateEmergencyContact)
        {
			print json_encode(array(
			    "status"     				=> "success",
				"msg" 						=> "successfully update emergency contact",
			    "updateEmergencyContact"	=> $updateEmergencyContact,
			));

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

	function deleteEmergency()
	{
		$emergency_id  		= $this->input->post('emergency_id');
		$profiling_id 		= $this->input->post('profiling_id');

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

		$deleteEmergency = $this->user_emergency->editCaseEmergency($updateData,$emergency_id,$profiling_id);

        if($deleteEmergency){
			print json_encode(array(
			    "status"     		=> "success",
				"msg" 				=> "emergency contact deleted",
			    "deleteEmergency" 	=> $deleteEmergency,
			));

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

	function save_phone()
	{
		$profiling_id 		= $this->input->post('profiling_id');
		$user_id 			= $this->input->post('user_id');
		$data['phone'] 		= $this->input->post('phone');

		$updatePhone = $this->db->set($data)
								->where('id',$profiling_id)
								->update('user__profiling ');

		if($updatePhone)
        {
          	print json_encode(array(
                "status"     		  	=> "success",
                "updatePhone" 			=> $updatePhone,
                "msg" 		    	  	=> "Mobile number updated.",
                "redirect"				=> base_url('hr/StaffProfile/staffDetail/'.$user_id)
            ));

        }
        else
        {
        	print json_encode(array(
                "status" 	=> "failed",
                "msg" 		=> "failed",
                "redirect"	=> base_url('hr/StaffProfile/staffDetail/'.$user_id)
            ));
        }
	}

	function save_ext_no()
	{
		$profiling_id 			= $this->input->post('profiling_id');
		$user_id 				= $this->input->post('user_id');
		$staff_dept_id 			= $this->input->post('department_id');

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

		$data['ext_no'] = $ext_no_front.''.$this->input->post('ext_no');

		$updateExtNo = $this->db->set($data)
								->where('id',$profiling_id)
								->update('user__profiling');

		if($updateExtNo)
        {
          	print json_encode(array(
                "status"     		  	=> "success",
                "updateExtNo" 			=> $updateExtNo,
                "msg" 		    	  	=> "Extension number updated.",
                "redirect"				=> base_url('hr/StaffProfile/staffDetail/'.$user_id)
            ));

        }
        else
        {
        	print json_encode(array(
                "status" 	=> "failed",
                "msg" 		=> "failed",
                "redirect"	=> base_url('hr/StaffProfile/staffDetail/'.$user_id)
            ));
        }
	}

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

		$main_id 		= $this->input->post('main_id');
		$data_category 	= $this->model_profiling->get_attachment_category($main_id); 

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

	function uploadAttachment()
	{
		if(isset($_FILES['attachment'])){
			$data = $this->input->post();

			$data_attachment 			    = $this->upload("attachment", "attachment", 'hr/staff_profiling/'.$data['staff_id'].'/'.'attachments/');
			$data_attachment['description'] = $data['description'];
			$data_attachment['staff_id'] 	= $data['staff_id'];
			$data_attachment['category_id']	= $data['category_id'];
			$data_attachment['created_by']  = $this->logged_user['id'];

			$id = $this->model_general->insert("hr__profile_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."
				));
			}
		}
	}

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

		if(isset($data['id']))
		{
			$data['updated_by'] = $this->logged_user['id'];

			$ok = $this->model_general->update('hr__profile_attachment', array('is_delete'=>1), array('id'=>$data['id']));

			if($ok)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Attachment deleted successfully."
				));
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "Failed to delete attachment."
				));
			}
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "Data is missing."
			));
		}
	}

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

		if(isset($data['id']))
		{
			$id = $data['id'];

			$data['updated_by'] = $this->logged_user['id'];

			$ok = $this->model_general->update('hr__profile_attachment', $data, array('id'=>$id));

			if($ok)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Attachment updated successfully."
				));
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "Failed to updated attachment."
				));
			}
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "Data is missing."
			));
		}
	}

	private function upload($type, $file, $file_location){
		$fcpath = str_replace('\\','/',FCPATH);
		$dir = str_replace('\\','/',$fcpath.'assets/uploads/'.$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';
			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['file_name'] 	   = $upload_data['file_name'];
					$data['file_location'] = 'assets/uploads/'.$file_location;
				}
				else
				{
					if($type=="image")
					{
						$data['file_name'] 	   = 'default.png';
						$data['file_location'] = 'assets/uploads/defaults';
					}
				}
			}
			else
			{
				if($type=="image")
				{
					$data['file_name'] 	   = 'default.png';
					$data['file_location'] = 'assets/uploads/defaults';
				}
			}
		}

		return $data;
	}

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

		if(!$this->input->post()){
			redirect(base_url('/hr/StaffProfile/staffDetail/'.$staff_id));
		}

		$staff_id = $input['staff_id'];
		$academic_id = $input['academic_id'];
		
		if($mode == 'new')
		{
			$uploaded = $this->uploadToStorage('./application/storage/hr/profiling/'.$staff_id.'/qualifications'.'/','attachment');
			if ($uploaded){
	        	$temp = explode('/', $uploaded['file_type']); 
	        	$attachment = array
	        	(
	        		'user_id' => $staff_id,
	        		'academic_qualification_id' => $academic_id,
	        		'attachment_name' => $uploaded['file_name'], 
	        		'location' => '/storage/hr/profiling/'.$staff_id.'/qualifications'.'/'.$uploaded['file_name'],
	        		'file_type' => $uploaded['file_type'],
	        		'file_ext' => $temp[1],
	        		'mask_id' => time().uniqid(),
	        		'is_delete' => 0
	        	);
				$query = $this->academic_attachment->createAttachment($attachment);
			}

			$type = 'upload';
		}elseif($mode == 'delete')
		{
			$attachmentID = $input['attachmentID'];
			$attachment['is_delete'] = 1;
			$query = $this->academic_attachment->editAttachment($attachment, $attachmentID);
			$type = 'delete';
		}

		if($query)
		{
			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Attachment ".$type."ed successfully."
			));
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to ".$type." attachment."
			));
		}
	}
}


?>