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

class Myprofile extends MY_Controller
{
	function __construct()
	{
		parent::__construct();
		if(empty($this->session->userdata('user')['id'])) redirect(base_url());
		else 
			$this->logged_user = $this->session->userdata('user');
		
		$this->load->model('admin/model_company');
		$this->load->model('admin/Model_user');
		
		$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');

		/* newly add */
		$this->load->model('hr/model_user_pursuing_study','pursuing_study');
		$this->load->model('hr/model_user_case_emergency','case_emergency');
		$this->load->model('staff_directory/model_user_list');
		/* end of newly add */

		/* latest add 20210630 */
		$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');
		/* end of latest add 20210630 */

		/* Farid 220129 */
		$this->load->model('hr/model_exam');
		
		//Fakru add 20220128
		$this->load->model('hr/model_user_professional_experiencemgs','professional_experiencemgs');
		//end#

		//akmal : check balik kenapa perlu check module access. semua user boleh update myprofile. 
		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($profiling_id_new = 0, $mode = null)
	{
		$data['btn_hidden'] = ($mode == 'view')?'d-none':'';

		$this->load->model('hr/model_profiling');
		$data['user_profile'] = $this->model_profiling->update_profile_list(null,null,$this->logged_user['id']);

		$user_id =  $this->session->userdata('user')['id'];
		$rs_employment_detail = $this->Model_user->getEmploymentDetail($user_id);
		$profiling_id = (!empty($rs_employment_detail)) ? $rs_employment_detail['profiling_id']:0;
		
		$data['profiling_id_new'] = $profiling_id_new;
		$data['date'] 						= date("d-m-Y"); 
		$data['action_type']				= $this->staff_action->getActionByUserID($profiling_id,$user_id);

		if(!empty($data['action_type'])) 
		{
			$data['join_group'] 				= ($this->join_group->fetchJoiningGroup(null,null,0,$user_id))?$this->join_group->fetchJoiningGroup(null,null,0,$user_id)[0]:null;
			$data['addresses']					= $this->address->fetchAddress($user_id,false,null);
			$data['family_info']				= $this->family->fetchFamilyInfo($user_id, false, null);
			$data['academic_qualification'] 	= $this->academic->fetchQualification($user_id,false,null);
			$data['qualifications']				= $this->general_model->get_all('_ref__academic');
			$data['additional_personal_data']	= $this->attachment->fetchPersonalAttachment($user_id,null,false,null);
			$data['professional_membership']	= $this->promember->fetchMembership($user_id,false,null);
			$data['professional_license']		= $this->license->fetchLicense(null,$user_id,null,false,null);
			$data['recognition']				= $this->recognition->fetchRecognition($user_id,false,null);
			$data['statutory_details']			= ($this->stats->fetchStatutory($user_id,false,null))?$this->stats->fetchStatutory($user_id,false,null)[0]:null;
			$data['third_party_payments']		= $this->thirdParty->fetchPayment($user_id,false, null);
			$data['pcb_consideration']			= $this->pcb->fetchPCB($user_id,false,null);
			$data['rs_pursuing_study']			= $this->pursuing_study->get_pursuing_study($user_id,false,null);
			$data['rs_case_or_emergency']		= $this->case_emergency->get_case_of_emergency($user_id,false,null);
			$data['residenceType']				= $this->general_model->get_all('_ref__residence_type');
			$data['states']						= $this->general_model->get_all('_ref__state');
			$data['countries']					= $this->country->country_all();
			$data['relations']					= $this->general_model->get_all('_ref__relationship');
			$data['professional_academic']		= $this->professional_academic->fetchProfessionalAcademic($user_id,false);
			$data['working_experience']			= $this->working_experience->fetchWorkingExperience($user_id, false, null);

			$this->load->view('hr/myprofile/mymainprofile.php', $data);
		} else {
			echo '<h1>Your Registration is incomplete. Please contact HR for assistant.</h1>';
		}
		$this->load->view('hr/report/footer.php');
	}

	public function view_profile($mode = null)
	{
		$this->index(0,$mode);
	}

	private function get_profiling_id($profiling_id=0)
	{
		if($profiling_id ==0) {
			$this->db->query('insert into  user__profiling (user_id, staff_id, title_id, gender_id, ic_no, passport_expired_date, working_expired_date, place_issue, birth_date, birth_place, hobby, citizen_id, religion_id, race_id, residential_id, marital_status, married_date, primary_email, secondary_email, action_type_id, action_efective_date, phone, ext_no, created_by)  select user_id, staff_id, title_id, gender_id, ic_no, passport_expired_date, working_expired_date, place_issue, birth_date, birth_place, hobby, citizen_id, religion_id, race_id, residential_id, marital_status, married_date, if(primary_email = "","'.$this->session->userdata('user')['email'].'",primary_email) as primary_email, secondary_email, 10000, now(), phone, ext_no, user_id from user__profiling where user_id = '.$this->session->userdata('user')['id'].' order by id desc limit 1',false);
			$new_profiling_id = $this->db->insert_id();
			return($new_profiling_id);
		}else return $profiling_id; 
	}

	function getAddress()
	{
		$address_id  	= $this->input->post('address_id');
		$profiling_id   = $this->input->post('profiling_id');
		$addressData 	= $this->address->getAddress($address_id);

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

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

	function saveAddress()
	{
		$insertData = array(
			'profiling_id' 	=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'		=> $this->session->userdata('user')['id'],
			'type'   		=> $this->input->post('type'),
	        'address' 		=> $this->input->post('address'),
	        'postcode'  	=> $this->input->post('postcode'),
	        'city'  		=> $this->input->post('city'),
	        'state_id'  	=> $this->input->post('state_id'),
	        'country_id'	=> $this->input->post('country_id'),
	        'contact_no'	=> $this->input->post('contact_no'),

		);
        
		$newAddress = $this->address->createAddress($insertData);

        if($newAddress)
        {
        	$type 		= ($this->input->post('type') == 1)?"PERMANENT RESIDENCE":((($this->input->post('type') == 2))?"TEMPORARY RESIDENCE":"CORRESPONDENCE RESIDENCE");
        	$country 	= $this->db->where('id',$this->input->post('country_id'))->get('_ref__country')->result_array()[0]['country'];
        	$state  	= $this->db->where('id',$this->input->post('state_id'))->get('_ref__state')->result_array()[0]['state'];

			$update_detail = array 
			(
				'item_change' 		=> "Addresses",
				'detail'			=> "Type - ".$type."<br> Address - ".$this->input->post('address')."<br> Country - ".$country."<br> State - ".$state."<br> City - ".$this->input->post('city')."<br> Postcode - ".$this->input->post('postcode')."<br> Contact - ".$this->input->post('contact_no'),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     => "success",
				"msg" 		 =>  "Successfully add new address",
			    "newAddress" => $newAddress,
			    "redirect"	 => base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function save_editAddress()
	{
		$address_id = $this->input->post('id');

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

		$deleteAddress = $this->address->editAddress($updateData,$address_id);

		$insertData = array(
			'profiling_id' 	=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'		=> $this->session->userdata('user')['id'],
			'type'   		=> $this->input->post('type'),
	        'address' 		=> $this->input->post('address'),
	        'postcode'  	=> $this->input->post('postcode'),
	        'city'  		=> $this->input->post('city'),
	        'state_id'  	=> $this->input->post('state_id'),
	        'country_id'	=> $this->input->post('country_id'),
	        'contact_no'	=> $this->input->post('contact_no'),

		);
        
		$newAddress = $this->address->createAddress($insertData);

        if($newAddress)
        {
        	$type 		= ($this->input->post('type') == 1)?"PERMANENT RESIDENCE":((($this->input->post('type') == 2))?"TEMPORARY RESIDENCE":"CORRESPONDENCE RESIDENCE");
        	$country 	= $this->db->where('id',$this->input->post('country_id'))->get('_ref__country')->result_array()[0]['country'];
        	$state  	= $this->db->where('id',$this->input->post('state_id'))->get('_ref__state')->result_array()[0]['state'];

			$update_detail = array 
			(
				'item_change' 		=> "Addresses",
				'detail'			=> "Type - ".$type."<br> Address - ".$this->input->post('address')."<br> Country - ".$country."<br> State - ".$state."<br> City - ".$this->input->post('city')."<br> Postcode - ".$this->input->post('postcode')."<br> Contact - ".$this->input->post('contact_no'),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     	=> "success",
				"msg" 			=>  "Successfully update address",
			    "updateAddress" => $newAddress,
			    "redirect"		=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function deleteAddress()
	{
		$address_id     =  $this->input->post('id');
		$profiling_id 	= $this->get_profiling_id($this->input->post('profiling_id'));

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

		$deleteAddress = $this->address->editAddress($updateData,$address_id);

		if($deleteAddress)
        {
        	$update_detail = array 
			(
				'item_change' 		=> "Addresses",
				'detail'			=> "Delete Addresses",
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

         	print json_encode(array(
                "status"     	=> "success",
                "deleteAddress" => $deleteAddress,
                "msg" 		    => "Address deleted.",
                "redirect"	=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
            ));

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

	function getQualification()
	{
		$qualification_id  	= $this->input->post('qualification_id');
		$profiling_id   	= $this->input->post('profiling_id');

		$qualificationData 	= $this->academic->fetchQualification(null,false,null,$qualification_id);
		// echo $this->db->last_query();
		$query = $this->db->last_query();

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

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

	function saveQualification()
	{
		$upload_path = 'hr/profiling/'.$this->session->userdata('user')['id'].'/qualifications';

		$insertData = array(
			'profiling_id' 	=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'		=> $this->session->userdata('user')['id'],
			'level_id'   	=> $this->input->post('level_id'),
	        'program' 		=> $this->input->post('program'),
	        'institution'  	=> $this->input->post('institution'),
	        'year'  		=> $this->input->post('year'),
	        'cgpa'  		=> $this->input->post('cgpa')
		);
        
		$newQualification = $this->academic->createQualification($insertData);

        if($newQualification)
        {
        	if(isset($_FILES['attachment_file']))
        	{
				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);

        		$data_attachment = array
        		(
        			'user_id'						=> $this->session->userdata('user')['id'],
        			'academic_qualification_id'		=> $newQualification,
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '3'.$newQualification.''.date('Ymd').''.uniqid(),
        		);

        		$save_attachment = $this->academic_attachment->createAttachment($data_attachment);
			}

			$education 		= $this->db->where('id',$this->input->post('level_id'))->get('_ref__academic')->result_array()[0]['level'];
			$update_detail = array 
			(
				'item_change' 		=> "Academic Education",
				'detail'			=> "Level - ".$education."<br> Program - ".$this->input->post('program')."<br> University/Institution - ".$this->input->post('institution')."<br> Year Graduated - ".$this->input->post('year')."<br> Final Result/CGPA - ".$this->input->post('cgpa'),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     		=> "success",
				"msg" 				=> "successfully add academic education",
			    "newQualification" 	=> $newQualification,
			    "redirect"			=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function save_editQualification()
	{
		$qualification_id =  $this->input->post('id');

		$updateData = array(
			'is_delete' 	=> 1,
			'deleted_at'	=> date('Y-m-d')
		);

		$deleteQualification = $this->academic->editQualification($updateData,$qualification_id);
		$deleteQualificationAttachment = $this->academic_attachment->editAttachment(array('is_delete' => 1),null,$qualification_id);

		$upload_path = 'hr/profiling/'.$this->session->userdata('user')['id'].'/qualifications';

		$insertData = array(
			'profiling_id' 	=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'		=> $this->session->userdata('user')['id'],
			'level_id'   	=> $this->input->post('level_id'),
	        'program' 		=> $this->input->post('program'),
	        'institution'  	=> $this->input->post('institution'),
	        'year'  		=> $this->input->post('year'),
	        'cgpa'  		=> $this->input->post('cgpa')
		);
        
		$newQualification = $this->academic->createQualification($insertData);

        if($newQualification)
        {
        	if(isset($_FILES['attachment_file']))
        	{
				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);

        		$data_attachment = array
        		(
        			'user_id'						=> $this->session->userdata('user')['id'],
        			'academic_qualification_id'		=> $newQualification,
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '3'.$newQualification.''.date('Ymd').''.uniqid(),
        		);

        		$save_attachment = $this->academic_attachment->createAttachment($data_attachment);
			}

			$education 		= $this->db->where('id',$this->input->post('level_id'))->get('_ref__academic')->result_array()[0]['level'];
			$update_detail = array 
			(
				'item_change' 		=> "Academic Education",
				'detail'			=> "Level - ".$education."<br> Program - ".$this->input->post('program')."<br> University/Institution - ".$this->input->post('institution')."<br> Year Graduated - ".$this->input->post('year')."<br> Final Result/CGPA - ".$this->input->post('cgpa'),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     			=> "success",
				"msg" 					=> "successfully update academic education",
			    "updateQualification" 	=> $newQualification,
			    "redirect"				=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function deleteQualification()
	{
		$qualification_id =  $this->input->post('id');
		$profiling_id =  $this->input->post('profiling_id');

		$updateData = array(
			'is_delete' 	=> 1,
			'deleted_at'	=> date('Y-m-d')
		);

		$deleteQualification = $this->academic->editQualification($updateData,$qualification_id);
		$deleteQualificationAttachment = $this->academic_attachment->editAttachment(array(
			'is_delete' => 1),null,$qualification_id);

		if($deleteQualification)
        {
        	$update_detail = array 
			(
				'item_change' 		=> "Academic Education",
				'detail'			=> "Delete Academic Education",
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

          	print json_encode(array(
                "status"     			=> "success",
                "deleteQualification" 	=> $deleteQualification,
                "msg" 		    		=> "Academic education deleted.",
                "redirect"				=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
            ));

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

	function getMaritalStatus()
	{
		$profiling_id   	= $this->input->post('profiling_id');
		$maritalStatusData 	= $this->staff_action->fetchAction($profiling_id,null,null);

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

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

	function save_marital_status()
	{
		$profiling_id 			= $this->get_profiling_id($this->input->post('profiling_id'));
		$data['marital_status'] = $this->input->post('marital_status');
		$data['married_date'] 	= date('Y-m-d',strtotime($this->input->post('married_date')));


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

		if($updateMaritalStatus)
        {
        	$status = ($this->input->post('marital_status') == 1)?"Single":(($this->input->post('marital_status') == 2)?"Married":"Divorce");
        	$date 	= ($this->input->post('marital_status') == 2)?$this->input->post('married_date'):""; 
        	$update_detail = array 
			(
				'item_change' 		=> "Marital Status",
				'detail'			=> "Marital Status - ".$status."<br> Married Date - ".$date,
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

          	print json_encode(array(
                "status"     		  	=> "success",
                "updateMaritalStatus" 	=> $updateMaritalStatus,
                "msg" 		    	  	=> "Marital Status updated.",
                "redirect"				=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
            ));

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

	function getSecondaryEmail()
	{
		$profiling_id   	= $this->input->post('profiling_id');
		$secondaryEmailData = $this->staff_action->fetchAction($profiling_id,null,null);

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

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

	function save_secondary_email()
	{

		$profiling_id 			 = $this->get_profiling_id($this->input->post('profiling_id'));
		$data['secondary_email'] = $this->input->post('secondary_email');

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

		if($updateSecondaryEmail)
        {
        	$update_detail = array 
			(
				'item_change' 		=> "Secondary Email",
				'detail'			=> $this->input->post('secondary_email'),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

          	print json_encode(array(
                "status"     		  	=> "success",
                "updateSecondaryEmail" 	=> $updateSecondaryEmail,
                "msg" 		    	  	=> "Secondary Email updated.",
                "redirect"			  	=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
            ));

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

	private function get_statutory_id($pcb_id, $profiling_id)
	{
		$this->db->query('insert into user__statutory_detail 
			(user_id, ee_epf_no, er_rate, er_percent, ee_rate, ee_percent, ee_socso, ee_income_tax, ee_pcb_deduction, ee_zakat_deduction, ee_pcb_deduction_percent, ee_zakat_deduction_percent, year, status)  
			select user_id, ee_epf_no, er_rate, er_percent, ee_rate, ee_percent, ee_socso, ee_income_tax, ee_pcb_deduction, ee_zakat_deduction, ee_pcb_deduction_percent, ee_zakat_deduction_percent, year, status 
			from user__statutory_detail 
			where id = '.$pcb_id.' and user_id = '.$this->session->userdata('user')['id'].' and is_deleted = 0 order by id desc limit 1',false);

		$new_statutory_id     = $this->db->insert_id();

		$delete_old_statutory = $this->db->set('is_deleted', 1)
									->where('id', $pcb_id)
									->update('user__statutory_detail');

		$updateProfiling_id   = $this->db->set('profiling_id', $profiling_id)
									->where('id', $new_statutory_id)
									->update('user__statutory_detail');

		return($new_statutory_id);	
	}

	function save_statutory()
	{
		$profiling_id 	  							= $this->get_profiling_id($this->input->post('profiling_id'));
		$user_id 									= $this->session->userdata('user')['id'];
		$data['ee_percent'] 						= $this->input->post('ee_percent');
		$data['ee_pcb_deduction_percent'] 			= $this->input->post('pcb');
		$data['ee_zakat_deduction_percent'] 		= $this->input->post('zakat');
		$data['year'] 								= $this->input->post('year');

		$statutory_id = $this->db->select('id, DATE_FORMAT(created_at, "%m-%Y") as created_at')
							->where('is_deleted', 0)
							->where('user_id', $user_id)
							->order_by('id DESC')
							->limit(1)
							->get('user__statutory_detail')
							->result();

		$updateStatutory = 0;


		if(!empty($statutory_id) && ($statutory_id[0]->created_at == date('m-Y'))){
			$pcb_ids  	 		= $this->get_statutory_id($statutory_id[0]->id, $profiling_id);

			$updateStatutory = $this->db->set($data)
							->where('id', $pcb_ids)
							->where('is_deleted', 0)
							->update('user__statutory_detail');
		}else{			
			$data['user_id'] 	  	= $user_id;
			$data['profiling_id'] 	= $profiling_id;
			$data['status'] 		= 1;
			$this->db->insert('user__statutory_detail', $data);
			$updateStatutory = $this->db->insert_id();
		}

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

	function save_pcb_deduction()
	{
		$profiling_id 	  	= $this->get_profiling_id($this->input->post('profiling_id'));
		$user_id 			= $this->session->userdata('user')['id'];
		$data['ee_pcb_deduction_percent'] 	= $this->input->post('ee_pcb_deduction_percent');
		$data['ee_zakat_deduction_percent'] = $this->input->post('ee_zakat_deduction_percent');

		$pcb_id = $this->db->select('id')
							->where('is_deleted', 0)
							->where('user_id', $user_id)
							->order_by('id DESC')
							->limit(1)
							->get('user__statutory_detail')
							->result();

		$updatePcb_Deduction = 0;

		if(!empty($pcb_id)){
			$pcb_ids  	 		= $this->get_statutory_id($pcb_id[0]->id, $profiling_id);

			$updatePcb_Deduction     = $this->db->set($data)
										->where('id', $pcb_ids)
										->where('is_deleted', 0)
										->update('user__statutory_detail');
		}else{
			$data['user_id'] 	  = $user_id;
			$data['profiling_id'] = $profiling_id;
			$this->db->insert('user__statutory_detail', $data);
			$updatePcb_Deduction = $this->db->insert_id();
		}

		if($updatePcb_Deduction)
        {
          	print json_encode(array(
                "status"     		  => "success",
                "updatePcb_Deduction" => $updatePcb_Deduction,
                "msg" 		    	  => "PCB Deduction updated.",
                "redirect"			  => base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
            ));

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

	function save_pcb_deduction_year()
	{
		$profiling_id 	  	= $this->get_profiling_id($this->input->post('profiling_id'));
		$user_id 			= $this->session->userdata('user')['id'];
		$data['year'] 		= $this->input->post('year');

		$pcb_id = $this->db->select('id')
							->where('is_deleted', 0)
							->where('user_id', $user_id)
							->order_by('id DESC')
							->limit(1)
							->get('user__statutory_detail')
							->result();

		$updatePcb_Year = 0;

		if(!empty($pcb_id)){
			$pcb_ids  	 		= $this->get_statutory_id($pcb_id[0]->id, $profiling_id);

			$updatePcb_Year     = $this->db->set($data)
										->where('id', $pcb_ids)
										->where('is_deleted', 0)
										->update('user__statutory_detail');
		}else{
			$data['user_id'] 	  = $user_id;
			$data['profiling_id'] = $profiling_id;
			$this->db->insert('user__statutory_detail', $data);
			$updatePcb_Year = $this->db->insert_id();
		}

		if($updatePcb_Year)
        {
          	print json_encode(array(
                "status"     		  => "success",
                "updatePcb_Year" 	  => $updatePcb_Year,
                "msg" 		    	  => "PCB Year updated.",
                "redirect"			  => base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
            ));

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

	}

	function save_employee_rate()
	{
		$profiling_id 	  	= $this->get_profiling_id($this->input->post('profiling_id'));
		$user_id 			= $this->session->userdata('user')['id'];
		$data['ee_rate'] 	= $this->input->post('ee_rate');
		$data['ee_percent'] = $this->input->post('ee_percent');

		$pcb_id = $this->db->select('id')
							->where('is_deleted', 0)
							->where('user_id', $user_id)
							->order_by('id DESC')
							->limit(1)
							->get('user__statutory_detail')
							->result();

		$updateEmployeeRate = 0;

		if(!empty($pcb_id)){
			$pcb_ids  	 		= $this->get_statutory_id($pcb_id[0]->id, $profiling_id);

			$updateEmployeeRate = $this->db->set($data)
										->where('id', $pcb_ids)
										->where('is_deleted', 0)
										->update('user__statutory_detail');
		}else{
			$data['user_id'] 	  = $user_id;
			$data['profiling_id'] = $profiling_id;
			$this->db->insert('user__statutory_detail', $data);
			$updateEmployeeRate = $this->db->insert_id();
		}
		
		if($updateEmployeeRate)
        {
          	print json_encode(array(
                "status"     		  => "success",
                "updateEmployeeRate"  => $updateEmployeeRate,
                "msg" 		    	  => "PCB Year updated.",
                "redirect"			  => base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
            ));

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

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

		return $data;
	}

	function saveThirdPartyPayment()
	{
		$insertData = array(
			'profiling_id' 	=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'		=> $this->session->userdata('user')['id'],
	        'date_start' 	=> ($this->input->post('tpp_date_start'))?date('Y-m-d',strtotime($this->input->post('tpp_date_start'))):'0000-00-00',
	        'date_end'  	=> ($this->input->post('tpp_date_end'))?date('Y-m-d',strtotime($this->input->post('tpp_date_end'))):'0000-00-00',
	        'type'  		=> $this->input->post('tpp_institutions'),
	        'amount'  		=> $this->input->post('tpp_amount'),
	        'account_no'	=> $this->input->post('tpp_account_no'),
	        'status'		=> $this->input->post('tpp_status'),
	        'created_at'	=> date('Y-m-d H:i:s')
		);
        
		$newThirdPartyPayment = $this->thirdParty->createPayment($insertData);

        if($newThirdPartyPayment)
        {
         	//$status = ($this->input->post('tpp_status') == 0)?"On Going":"End";
         	//$amount = "RM".number_format($this->input->post('tpp_amount'),2);
         	//$update_detail = array 
			// (
			// 	'item_change' 		=> "Third Party Payment",
			// 	'detail'			=> "Date From - ".$this->input->post('tpp_date_start')."<br> Date End - ".$this->input->post('tpp_date_end')."<br> Third Party Institution/Organisation - ".$this->input->post('tpp_institutions')."<br> Status - ".$status."<br> Amount - ".$amount,
			// 	'date_change'		=> date('d-m-Y H:i:s')
			// );
        	
			// $staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			// $email_data = array('hr@salihin.com.my');
			// $hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			// if($hr_detail) foreach($hr_detail as $hr_email) 
			// {
			// 	array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			// }

			// if($staffName)
			// {
			// 	$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
			// 	$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
			// 	$emailDetailForm	= $update_detail;

			// 	$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			// }

			print json_encode(array(
			    "status"     				=> "success",
				"msg" 						=> "successfully add new third party payment",
			    "newThirdPartyPayment" 		=> $newThirdPartyPayment,
			    "redirect"					=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function getThirdPartyPayment()
	{
		$payment_id  	= $this->input->post('payment_id');
		$payment_data 	= $this->thirdParty->get_payment($payment_id);

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

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

	function save_editThirdPartyPayment()
	{
		$payment_id  		= $this->input->post('payment_id');

		$updateData = array(
			'is_delete' 	=> 1,
			'deleted_at'	=> date('Y-m-d H:i:s')
		);

		$deleteThirdPartyPayment = $this->thirdParty->editPayment($updateData,$payment_id);

		$insertData = array(
			'profiling_id' 	=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'		=> $this->session->userdata('user')['id'],
	        'date_start' 	=> ($this->input->post('tpp_date_start'))?date('Y-m-d',strtotime($this->input->post('tpp_date_start'))):'0000-00-00',
	        'date_end'  	=> ($this->input->post('tpp_date_end'))?date('Y-m-d',strtotime($this->input->post('tpp_date_end'))):'0000-00-00',
	        'type'  		=> $this->input->post('tpp_institutions'),
	        'amount'  		=> $this->input->post('tpp_amount'),
	        'account_no'	=> $this->input->post('tpp_account_no'),
	        'status'		=> $this->input->post('tpp_status'),
	        'created_at'	=> date('Y-m-d H:i:s')
		);
        
		$newThirdPartyPayment = $this->thirdParty->createPayment($insertData);

        if($newThirdPartyPayment)
        {
         	//$status = ($this->input->post('tpp_status') == 0)?"On Going":"End";
         	//$amount = "RM".number_format($this->input->post('tpp_amount'),2);
         	//$update_detail = array 
			// (
			// 	'item_change' 		=> "Third Party Payment",
			// 	'detail'			=> "Date From - ".$this->input->post('tpp_date_start')."<br> Date End - ".$this->input->post('tpp_date_end')."<br> Third Party Institution/Organisation - ".$this->input->post('tpp_institutions')."<br> Status - ".$status."<br> Amount - ".$amount,
			// 	'date_change'		=> date('d-m-Y H:i:s')
			// );
        	
			// $staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			// $email_data = array('hr@salihin.com.my');
			// $hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			// if($hr_detail) foreach($hr_detail as $hr_email) 
			// {
			// 	array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			// }

			// if($staffName)
			// {
			// 	$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
			// 	$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
			// 	$emailDetailForm	= $update_detail;

			// 	$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			// }

			print json_encode(array(
			    "status"     				=> "success",
				"msg" 						=> "successfully update third party payment",
			    "newThirdPartyPayment" 		=> $newThirdPartyPayment,
				"redirect"					=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function deleteThirdPartyPayment()
	{
		$payment_id  	= $this->input->post('payment_id');
		$profiling_id 	= $this->input->post('profiling_id');

		$updateData = array(
			'is_delete' 	=> 1,
			'deleted_at'	=> date('Y-m-d H:i:s')
		);

		$deleteThirdPartyPayment = $this->thirdParty->editPayment($updateData,$payment_id);

        if($deleteThirdPartyPayment)
        {
         	//$update_detail = array 
			// (
			// 	'item_change' 		=> "Third Party Payment",
			// 	'detail'			=> "Delete Third Party Payment",
			// 	'date_change'		=> date('d-m-Y H:i:s')
			// );
        	
			// $staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			// $email_data = array('hr@salihin.com.my');
			// $hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			// if($hr_detail) foreach($hr_detail as $hr_email) 
			// {
			// 	array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			// }

			// if($staffName)
			// {
			// 	$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
			// 	$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
			// 	$emailDetailForm	= $update_detail;

			// 	$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			// }

			print json_encode(array(
			    "status"     				=> "success",
				"msg" 						=> "third party payment deleted",
			    "deleteThirdPartyPayment" 	=> $deleteThirdPartyPayment,
				"redirect"					=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
			));

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

	function savePersonalData()
	{
		$upload_path = 'hr/profiling/'.$this->session->userdata('user')['id'].'';

		$insertData = array(
			'profiling_id' 			=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'				=> $this->session->userdata('user')['id'],
	        'detail'  				=> $this->input->post('detail'),
	        'description'  			=> $this->input->post('description'),
			'created_at'			=> date('Y-m-d H:i:s')
		);
        
		$newPersonalData = $this->attachment->createPersonalAttachment($insertData);

        if($newPersonalData)
        {
        	if(isset($_FILES['attachment_file']))
        	{
				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);

        		$data_attachment = array
        		(
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '4'.$newPersonalData.''.date('Ymd').''.uniqid(),
        		);

        		$save_attachment = $this->attachment->editPersonalAttachment($data_attachment,$newPersonalData);
			}

			print json_encode(array(
			    "status"     	=> "success",
			    "newPersonalData" 	=> $newPersonalData,
			    "redirect"		=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function getPersonalData()
	{
		$personalData_id  		= $this->input->post('personalData_id');
		$personalData_data 	= $this->attachment->get_personalData($personalData_id);

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

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

	function save_editPersonalData()
	{
		$upload_path = 'hr/profiling/'.$this->session->userdata('user')['id'].'';

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

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

		$deleteStudy = $this->attachment->editPersonalAttachment($updateData,$personalData_id);

		$insertData = array(
			'profiling_id' 			=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'				=> $this->session->userdata('user')['id'],
	        'detail'  				=> $this->input->post('detail'),
	        'description'  			=> $this->input->post('description'),
			'created_at'			=> date('Y-m-d H:i:s')
		);
        
		$newPersonalData = $this->attachment->createPersonalAttachment($insertData);

        if($newPersonalData){

        	if(isset($_FILES['attachment_file']))
        	{
				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);

        		$data_attachment = array
        		(
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '4'.$newPersonalData.''.date('Ymd').''.uniqid(),
        		);

        		$save_attachment = $this->attachment->editPersonalAttachment($data_attachment,$newPersonalData);
			}

			print json_encode(array(
			    "status"     	=> "success",
			    "newPersonalData" 		=> $newPersonalData,
				"redirect"	=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function deletePersonalData()
	{
		$personalData_id  		= $this->input->post('personalData_id');
		$profiling_id 	= $this->input->post('profiling_id');

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

		$deletePersonalData = $this->attachment->editPersonalAttachment($updateData,$personalData_id,$profiling_id);

        if($deletePersonalData){
			print json_encode(array(
			    "status"     	=> "success",
			    "deletePersonalData" 		=> $deletePersonalData,
				"redirect"	=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
			));

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

	function saveStudy()
	{
		$insertData = array(
			'profiling_id' 		=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'			=> $this->session->userdata('user')['id'],
	        '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'),
	        'created_at'		=> date('Y-m-d H:i:s')
		);
        
		$newStudy = $this->pursuing_study->createPursuingStudy($insertData);

        if($newStudy)
        {
        	if(isset($_FILES['attachment_file']))
        	{
        		$upload_path 	= 'hr/profiling/'.$this->session->userdata('user')['id'].'/education_in_progress';
			$upload_image 	= $this->upload("attachment", "attachment_file", $upload_path);
				
        		$data_attachment = array
        		(
        			'user_id'					=> $this->session->userdata('user')['id'],
        			'professional_academic_id'			=> $newStudy,
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'					=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
        			'file_type'					=> $_FILES['attachment_file']['type'],
        			'file_ext'					=> $_FILES['attachment_file']['type'],
        			'mask_id' 					=> '8'.$newStudy.''.date('Ymd').''.uniqid(),
        		);

        		$save_attachment = $this->professional_academic_attachment->createAttachment_edu($data_attachment);
		}

        	$update_detail = array 
			(
				'item_change' 		=> "Education In Progress",
				'detail'			=> "Program - ".$this->input->post('study_program')."<br> University/Institution - ".$this->input->post('study_institution')."<br> Progress Paper In Hand - ".$this->input->post('progress_paper')."<br> Start Date - ".$this->input->post('study_date_start')."<br> Expected Date of Completion - ".$this->input->post('study_date_end')."<br> Status - On Going",
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     	=> "success",
				"msg" 			=> "successfully add new education in progress",
			    "newStudy" 		=> $newStudy,
			    "redirect"		=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function getStudy()
	{
		$study_id  		= $this->input->post('study_id');
		$study_data 	= $this->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(
			'is_delete' 	=> 1,
			'deleted_by'	=> $this->logged_user['user']['id'],
			'deleted_at'	=> date('Y-m-d H:i:s')
		);

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

		$insertData = array(
			'profiling_id' 		=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'			=> $this->session->userdata('user')['id'],
	        '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'),
	        'created_at'		=> date('Y-m-d H:i:s')
		);
        
		$newStudy = $this->pursuing_study->createPursuingStudy($insertData);

        if($newStudy)
        {
        	if(isset($_FILES['attachment_file']))
        	{
				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);
        
        		$data_attachment = array
        		(
        			'user_id'						=> $this->session->userdata('user')['id'],
        			'professional_academic_id'		=> $newStudy,
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '8'.$newStudy.''.date('Ymd').''.uniqid(),
	        		'created_by'		=> $this->session->userdata('user')['id']
        		);

        		$save_attachment = $this->professional_academic_attachment->createAttachment_edu($data_attachment);
			}

        	$update_detail = array 
			(
				'item_change' 		=> "Education In Progress",
				'detail'			=> "Program - ".$this->input->post('study_program')."<br> University/Institution - ".$this->input->post('study_institution')."<br> Progress Paper In Hand - ".$this->input->post('progress_paper')."<br> Start Date - ".$this->input->post('study_date_start')."<br> Expected Date of Completion - ".$this->input->post('study_date_end')."<br> Status - On Going",
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     	=> "success",
				"msg" 			=> "successfully update education in progress",
			    "newStudy" 		=> $newStudy,
				"redirect"		=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

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

		$updateData = array(
			'is_delete' 	=> 1,
			'deleted_at'	=> date('Y-m-d H:i:s')
		);

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

        if($deleteStudy)
        {
        	$update_detail = array 
			(
				'item_change' 		=> "Education In Progress",
				'detail'			=> "Delete Education In Progress",
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

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

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

	function saveEmergencyContact()
	{
		$insertData = array(
			'profiling_id' 	=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'		=> $this->session->userdata('user')['id'],
	        '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'),
	        'created_at'	=> date('Y-m-d H:i:s')
		);
        
		$newEmergencyContact = $this->case_emergency->createCaseEmergency($insertData);

        if($newEmergencyContact)
        {
        	$update_detail = array 
			(
				'item_change' 		=> "Emergency Contact",
				'detail'			=> "Name - ".$this->input->post('name')."<br> Relation - ".$this->input->post('relation')."<br> Contact Number - ".$this->input->post('phone')."<br> Email - ".$this->input->post('email')."<br> Address - ".$this->input->post('address'),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     				=> "success",
				"msg" 						=> "successfully add new emergency contact",
			    "newEmergencyContact" 		=> $newEmergencyContact,
			    "redirect"					=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function getEmergency()
	{
		$emergency_id  		= $this->input->post('emergency_id');
		$case_emergency_data 	= $this->case_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(
			'is_delete' 	=> 1,
			'deleted_at'	=> date('Y-m-d H:i:s')
		);

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

		$insertData = array(
			'profiling_id' 	=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'		=> $this->session->userdata('user')['id'],
	        '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'),
	        'created_at'	=> date('Y-m-d H:i:s')
		);
        
		$newEmergencyContact = $this->case_emergency->createCaseEmergency($insertData);

        if($newEmergencyContact)
        {
			$update_detail = array 
			(
				'item_change' 		=> "Emergency Contact",
				'detail'			=> "Name - ".$this->input->post('name')."<br> Relation - ".$this->input->post('relation')."<br> Contact Number - ".$this->input->post('phone')."<br> Email - ".$this->input->post('email')."<br> Address - ".$this->input->post('address'),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     			=> "success",
				"msg" 					=> "successfully update emergency contact",
			    "newEmergencyContact"	=> $newEmergencyContact,
			    "redirect"				=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

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

		$updateData = array(
			'is_delete' 	=> 1,
			'deleted_at'	=> date('Y-m-d H:i:s')
		);

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

        if($deleteEmergency)
        {
        	$update_detail = array 
			(
				'item_change' 		=> "Emergency Contact",
				'detail'			=> "Delete Emergency Contact",
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     		=> "success",
				"msg" 				=> "emergency contact deleted",
			    "deleteEmergency" 	=> $deleteEmergency,
				"redirect"			=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
			));

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

	function getPcbConsideration($mode = null)
	{
		$user_id = (!empty($this->input->post('user_id')))?$this->input->post('user_id'):$this->session->userdata('user')['id'];
		if($mode == 1) // get family list only
		{
			$pcb_consideration = $this->family->fetchFamilyInfo($user_id, false, null);
			$pcb_consideration['existing_pcb_consideration'] = $this->pcb->fetchPCB($user_id, false, null);
		}else{
			$pcb_consideration['family_list'] = $this->family->fetchFamilyInfo($user_id, false, null);
			$pcb_consideration['pcb_detail'] = $this->pcb->fetchPCB($user_id, false, null, $this->input->post('pcb_id'));
		}


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

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

	function savePcbConsideration()
	{
		$insertData = array(
			'profiling_id' 		=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'			=> $this->session->userdata('user')['id'],
	        'family_id' 		=> $this->input->post('family_id'),
	        'responsible_id'  	=> $this->input->post('responsible_id'),
	        'created_at'		=> date('Y-m-d H:i:s')
		);
        
		$newPcbConsideration = $this->pcb->createPCB($insertData);

        if($newPcbConsideration)
        {
         	//$child_detail	= $this->db->where('id',$this->input->post('family_id'))->get('user__family_member')->result_array()[0];
			// $birthYear 		= date('Y',strtotime($child_detail['birthdate']));
			// $currentYear 	= date('Y');
			// $age 			= $currentYear - $birthYear;
			// $oku_status		= ($child_detail['oku_status'] == 1)?"No":"Yes";
			// $study_status	= ($child_detail['study_status'] == 1)?"No":"Yes";
			
			// $update_detail = array 
			// (
			// 	'item_change' 		=> "PCB Consideration",
			// 	'detail'			=> "Name - ".$child_detail['name']."<br> NRIC No - ".$child_detail['ic_no']."<br> Age - ".$age."<br> OKU Status - ".$oku_status."<br> Student Status - ".$study_status,
			// 	'date_change'		=> date('d-m-Y H:i:s')
			// );
        	
			// $staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			// $email_data = array('hr@salihin.com.my');
			// $hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			// if($hr_detail) foreach($hr_detail as $hr_email) 
			// {
			// 	array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			// }

			// if($staffName)
			// {
			// 	$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
			// 	$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
			// 	$emailDetailForm	= $update_detail;

			// 	$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			// }

			print json_encode(array(
			    "status"     				=> "success",
				"msg" 						=> "successfully add new PCB consideration",
			    "newPcbConsideration" 		=> $newPcbConsideration,
			    "redirect"					=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function save_editPcbConsideration()
	{
		$pcb_id  		= $this->input->post('pcb_id');

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

		$deletePcbConsideration = $this->pcb->editPCB($updateData,$pcb_id);

		$insertData = array(
			'profiling_id' 		=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'			=> $this->session->userdata('user')['id'],
	        'family_id' 		=> $this->input->post('family_id'),
	        'responsible_id'  	=> $this->input->post('responsible_id'),
	        'created_at'		=> date('Y-m-d H:i:s')
		);
        
		$newPcbConsideration = $this->pcb->createPCB($insertData);

        if($newPcbConsideration)
        {
			// $child_detail	= $this->db->where('id',$this->input->post('family_id'))->get('user__family_member')->result_array()[0];
			// $birthYear 		= date('Y',strtotime($child_detail['birthdate']));
			// $currentYear 	= date('Y');
			// $age 			= $currentYear - $birthYear;
			// $oku_status		= ($child_detail['oku_status'] == 1)?"No":"Yes";
			// $study_status	= ($child_detail['study_status'] == 1)?"No":"Yes";
			
			// $update_detail = array 
			// (
			// 	'item_change' 		=> "PCB Consideration",
			// 	'detail'			=> "Name - ".$child_detail['name']."<br> NRIC No - ".$child_detail['ic_no']."<br> Age - ".$age."<br> OKU Status - ".$oku_status."<br> Student Status - ".$study_status,
			// 	'date_change'		=> date('d-m-Y H:i:s')
			// );
        	
			// $staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			// $email_data = array('hr@salihin.com.my');
			// $hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			// if($hr_detail) foreach($hr_detail as $hr_email) 
			// {
			// 	array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			// }

			// if($staffName)
			// {
			// 	$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
			// 	$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
			// 	$emailDetailForm	= $update_detail;

			// 	$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			// }

			print json_encode(array(
			    "status"     			=> "success",
				"msg" 					=> "successfully update PCB consideration",
			    "newPcbConsideration" 	=> $newPcbConsideration,
			    "redirect"				=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function deletePcbConsideration()
	{
		$pcb_id  		= $this->input->post('pcb_id');
		$profiling_id 	= $this->input->post('profiling_id');

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

		$deletePcbConsideration = $this->pcb->editPCB($updateData,$pcb_id,$profiling_id);

        if($deletePcbConsideration)
        {
         	//$update_detail = array 
			// (
			// 	'item_change' 		=> "PCB Consideration",
			// 	'detail'			=> "Delete PCB Consideration",
			// 	'date_change'		=> date('d-m-Y H:i:s')
			// );
        	
			// $staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			// $email_data = array('hr@salihin.com.my');
			// $hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			// if($hr_detail) foreach($hr_detail as $hr_email) 
			// {
			// 	array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			// }

			// if($staffName)
			// {
			// 	$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
			// 	$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
			// 	$emailDetailForm	= $update_detail;

			// 	$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			// }

			print json_encode(array(
			    "status"     				=> "success",
				"msg" 						=> "PCB consideration deleted",
			    "deletePcbConsideration" 	=> $deletePcbConsideration,
				"redirect"					=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
			));

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

	function saveFamilyInfo()
	{
		$insertData = array(
			'profiling_id' 			=> $this->get_profiling_id($this->input->post('profiling_id')),
			'staff_id'				=> $this->session->userdata('user')['id'],
			'name' 					=> $this->input->post('name'),
			'ic_no' 				=> $this->input->post('ic_no'),
			'relation' 				=> $this->input->post('relation'),
			'birthdate' 			=> date("Y-m-d", strtotime($this->input->post('birthdate'))),
			'phone_no' 				=> $this->input->post('phone_no'),
			'email' 				=> $this->input->post('email'),
			'address' 				=> $this->input->post('address'),
			'oku_status' 			=> $this->input->post('oku_status'),
			'study_status' 			=> $this->input->post('study_status'),
			'academic_lavel' 		=> $this->input->post('academic_level'),
			'academic_institution' 	=> $this->input->post('academic_institution'),
			'occupation' 			=> $this->input->post('occupation'),
		);
        
		$newFamilyInfo = $this->family->createFamily($insertData);

        if($newFamilyInfo)
        {
        	$education 		= $this->db->where('id',$this->input->post('academic_level'))->get('_ref__academic')->result_array()[0]['level'];
			$relation 		= $this->db->where('id',$this->input->post('relation'))->get('_ref__relationship')->result_array()[0]['relations'];
			$birthYear 		= date('Y',strtotime($this->input->post('birthdate')));
			$currentYear 	= date('Y');
			$age 			= $currentYear - $birthYear;

        	$update_detail = array 
			(
				'item_change' 		=> "Family Info",
				'detail'			=> "Name - ".$this->input->post('name')."<br> Nric - ".$this->input->post('ic_no')."<br> Relation - ".$relation."<br> Birthdate - ".$this->input->post('birthdate')."<br> Contact Number - ".$this->input->post('phone_no')."<br> Email - ".$this->input->post('email')."<br> Age - ".$age."<br> Occupation - ".$this->input->post('occupation')."<br> Address - ".$this->input->post('address')."<br> Academic Level - ".$education."<br> Academic institution - ".$this->input->post('academic_institution'),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     	=> "success",
				"msg" 			=> "successfully add new family info",
			    "newFamilyInfo" => $newFamilyInfo,
			    "redirect"	 	=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function getFamilyInfo()
	{
		$familyInfo_id  = $this->input->post('familyInfo_id');
		$profiling_id   = $this->input->post('profiling_id');
		$familyInfoData = $this->family->find($familyInfo_id);

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

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

	function save_editFamilyInfo()
	{
		$familyInfo_id  = $this->input->post('id');

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

		$deleteFamilyInfo = $this->family->removeFamily($updateData,$familyInfo_id);

		$insertData = array(
			'profiling_id' 			=> $this->get_profiling_id($this->input->post('profiling_id')),
			'staff_id'				=> $this->session->userdata('user')['id'],
			'name' 					=> $this->input->post('name'),
			'ic_no' 				=> $this->input->post('ic_no'),
			'relation' 				=> $this->input->post('relation'),
			'birthdate' 			=> date("Y-m-d", strtotime($this->input->post('birthdate'))),
			'phone_no' 				=> $this->input->post('phone_no'),
			'email' 				=> $this->input->post('email'),
			'address' 				=> $this->input->post('address'),
			'oku_status' 			=> $this->input->post('oku_status'),
			'study_status' 			=> $this->input->post('study_status'),
			'academic_lavel' 		=> $this->input->post('academic_level'),
			'academic_institution' 	=> $this->input->post('academic_institution'),
			'occupation' 			=> $this->input->post('occupation'),
		);
        
		$newFamilyInfo = $this->family->createFamily($insertData);

        if($newFamilyInfo)
        {
			$education 		= $this->db->where('id',$this->input->post('academic_level'))->get('_ref__academic')->result_array()[0]['level'];
			$relation 		= $this->db->where('id',$this->input->post('relation'))->get('_ref__relationship')->result_array()[0]['relations'];
			$birthYear 		= date('Y',strtotime($this->input->post('birthdate')));
			$currentYear 	= date('Y');
			$age 			= $currentYear - $birthYear;

        	$update_detail = array 
			(
				'item_change' 		=> "Family Info",
				'detail'			=> "Name - ".$this->input->post('name')."<br> Nric - ".$this->input->post('ic_no')."<br> Relation - ".$relation."<br> Birthdate - ".$this->input->post('birthdate')."<br> Contact Number - ".$this->input->post('phone_no')."<br> Email - ".$this->input->post('email')."<br> Age - ".$age."<br> Occupation - ".$this->input->post('occupation')."<br> Address - ".$this->input->post('address')."<br> Academic Level - ".$education."<br> Academic institution - ".$this->input->post('academic_institution'),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     	  	=> "success",
				"msg" 				=> "successfully update family info",
			    "updateFamilyInfo" 	=> $newFamilyInfo,
			    "redirect"			=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function deleteFamilyInfo()
	{
		$familyInfo_id  = $this->input->post('id');
		$profiling_id 	= $this->get_profiling_id($this->input->post('profiling_id'));

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

		$deleteFamilyInfo = $this->family->removeFamily($updateData,$familyInfo_id);

		if($deleteFamilyInfo)
        {
        	$update_detail = array 
			(
				'item_change' 		=> "Family Info",
				'detail'			=> "Delete Family Info",
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

          	print json_encode(array(
                "status"     		=> "success",
                "deleteFamilyInfo" 	=> $deleteFamilyInfo,
                "msg" 		    	=> "Family Info deleted.",
                "redirect"			=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
            ));

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

	function getMembership()
	{
		$membership_id  	= $this->input->post('membership_id');
		$profiling_id   	= $this->input->post('profiling_id');

		$membershipData 	= $this->promember->fetchMembership(null,false,$profiling_id,$membership_id);

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

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

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

	function saveMembership()
	{
		$upload_path = 'hr/profiling/'.$this->session->userdata('user')['id'].'/membership';

		$insertData = array(
			'profiling_id' 				=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'					=> $this->session->userdata('user')['id'],
			'professional_body'   		=> $this->input->post('membership_bodies'),
	        'certificate' 				=> $this->input->post('membership_certificate'),
	        // 'membership'  				=> $this->input->post('membership'),
	        'membership_type'			=> $this->input->post('membership'),
	        'membership_no'  			=> $this->input->post('membership_no'),
	        // 'year'  					=> $this->input->post('membership_year'),
	        'date_of_admitted'			=> date('Y-m-d',strtotime($this->input->post('membership_year'))),
	        'created_at'				=> date('Y-m-d H:i:s')
		);
        
		$newMembership = $this->promember->createMembership($insertData);

        if($newMembership)
        {
        	if(isset($_FILES['attachment_file']))
        	{
				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);

        		$data_attachment = array
        		(
        			'user_id'						=> $this->session->userdata('user')['id'],
        			'professional_membership_id'	=> $newMembership,
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '6'.$newMembership.''.date('Ymd').''.uniqid(),
        		);

        		$save_attachment = $this->promember_attachment->createAttachment($data_attachment);
			}

			$update_detail = array 
			(
				'item_change' 		=> "Professional Membership",
				'detail'			=> "Professional Bodies - ".$this->input->post('membership_bodies')."<br> Name of Membership - ".$this->input->post('membership_certificate')."<br> Type of Membership - ".$this->input->post('membership')."<br> Membership Number - ".$this->input->post('membership_no')."<br> Date of Admitted to Membership - ".date('Y-m-d',strtotime($this->input->post('membership_year'))),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     	=> "success",
				"msg" 			=> "successfully add professional membership",
			    "newMembership" => $newMembership,
			    "redirect"		=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function save_editMembership()
	{
		$membership_id =  $this->input->post('id');

		$updateData = array(
			'is_delete' 	=> 1,
			'deleted_at'	=> date('Y-m-d H:i:s')
		);

		$deleteMembership = $this->promember->editMembership($updateData,$membership_id);
		$deleteMembershipAttachment = $this->promember_attachment->editAttachment(array(
			'is_delete' => 1),null,$membership_id);

		$upload_path = 'hr/profiling/'.$this->session->userdata('user')['id'].'/membership';

		$insertData = array(
			'profiling_id' 				=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'					=> $this->session->userdata('user')['id'],
			'professional_body'   		=> $this->input->post('membership_bodies'),
	        'certificate' 				=> $this->input->post('membership_certificate'),
	        // 'membership'  				=> $this->input->post('membership'),
	        'membership_type'			=> $this->input->post('membership'),
	        'membership_no'  			=> $this->input->post('membership_no'),
	        // 'year'  					=> $this->input->post('membership_year'),
			'date_of_admitted'			=> date('Y-m-d',strtotime($this->input->post('membership_year'))),
	        'created_at'				=> date('Y-m-d H:i:s')
		);
        
		$newMembership = $this->promember->createMembership($insertData);

        if($newMembership)
        {
        	if(isset($_FILES['attachment_file']))
        	{
				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);
				
        		$data_attachment = array
        		(
        			'user_id'						=> $this->session->userdata('user')['id'],
        			'professional_membership_id'	=> $newMembership,
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '6'.$newMembership.''.date('Ymd').''.uniqid(),
        		);

        		$save_attachment = $this->promember_attachment->createAttachment($data_attachment);
			}

			$update_detail = array 
			(
				'item_change' 		=> "Professional Membership",
				'detail'			=> "Professional Bodies - ".$this->input->post('membership_bodies')."<br> Name of Membership - ".$this->input->post('membership_certificate')."<br> Type of Membership - ".$this->input->post('membership')."<br> Membership Number - ".$this->input->post('membership_no')."<br> Date of Admitted to Membership - ".date('Y-m-d',strtotime($this->input->post('membership_year'))),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     		=> "success",
				"msg" 				=> "successfully update professional membership",
			    "updateMembership" 	=> $newMembership,
			    "redirect"			=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function deleteMembership()
	{
		$membership_id =  $this->input->post('id');
		$profiling_id =  $this->input->post('profiling_id');

		$updateData = array(
			'is_delete' 	=> 1,
			'deleted_at'	=> date('Y-m-d H:i:s')
		);

		$deleteMembership = $this->promember->editMembership($updateData,$membership_id);
		$deleteMembershipAttachment = $this->promember_attachment->editAttachment(array(
			'is_delete' => 1),null,$membership_id);

		if($deleteMembership)
	        {
	        	$update_detail = array 
				(
					'item_change' 		=> "Professional Membership",
					'detail'			=> "Delete Professional Membership",
					'date_change'		=> date('d-m-Y H:i:s')
				);
	        	
				$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
				
				$email_data = array('hr@salihin.com.my');
				$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

				if($hr_detail) foreach($hr_detail as $hr_email) 
				{
					array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
				}

				if($staffName)
				{
					$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
					$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
					$emailDetailForm	= $update_detail;

					$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
				}

	          	print json_encode(array(
	                "status"     			=> "success",
	                "deleteMembership" 		=> $deleteMembership,
	                "msg" 		    		=> "professional membership deleted.",
	                "redirect"				=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
	            ));

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

	function getLicense()
	{
		$license_id  	= $this->input->post('license_id');
		$profiling_id   	= $this->input->post('profiling_id');

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

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

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

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

	function saveLicense()
	{
		$upload_path = 'hr/profiling/'.$this->session->userdata('user')['id'].'/license';

		$insertData = array(
			'profiling_id' 				=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'					=> $this->session->userdata('user')['id'],
			'profession'   				=> $this->input->post('license_profession'),
	        'license_no' 				=> $this->input->post('license_no'),
	        'license_body_authority' 	=> $this->input->post('license_body_authority'),
	        'register_date'  			=> ($this->input->post('license_registration_date'))?date('Y-m-d',strtotime($this->input->post('license_registration_date'))):'0000-00-00',
	        'renewal_date'  			=> ($this->input->post('license_renewal_date'))?date('Y-m-d',strtotime($this->input->post('license_renewal_date'))):'0000-00-00',
	        'next_renewal_date'  		=> ($this->input->post('license_next_renewal_date'))?date('Y-m-d',strtotime($this->input->post('license_next_renewal_date'))):'0000-00-00',
	        'created_at'				=> date('Y-m-d H:i:s')
		);
        
		$newLicense = $this->license->createLicense($insertData);

        if($newLicense)
        {
        	if(isset($_FILES['attachment_file']))
        	{
				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);
				
        		$data_attachment = array
        		(
        			'user_id'						=> $this->session->userdata('user')['id'],
        			'license_id'					=> $newLicense,
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '7'.$newLicense.''.date('Ymd').''.uniqid(),
        		);

        		$save_attachment = $this->license_attachment->createAttachment($data_attachment);
			}

			$update_detail = array 
			(
				'item_change' 		=> "Professional License",
				'detail'			=> "Name of License - ".$this->input->post('license_profession')."<br> License No - ".$this->input->post('license_no')."<br> Licensing Body/Authority - ".$this->input->post('license_body_authority')."<br> Register Date - ".$this->input->post('license_registration_date')."<br> Latest Renewed Date - ".$this->input->post('license_renewal_date')."<br> Next Renewal Date - ".$this->input->post('license_next_renewal_date'),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     	=> "success",
				"msg" 			=> "successfully add professional license",
			    "newLicense" 	=> $newLicense,
			    "redirect"		=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function save_editLicense()
	{
		$license_id =  $this->input->post('id');

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

		$deleteLicense = $this->license->editLicense($updateData,$license_id);
		$deleteLicenseAttachment = $this->license_attachment->editAttachment(array(
			'is_delete' => 1),null,$license_id);

		$upload_path = 'hr/profiling/'.$this->session->userdata('user')['id'].'/license';

		$insertData = array(
			'profiling_id' 				=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'					=> $this->session->userdata('user')['id'],
			'profession'   				=> $this->input->post('license_profession'),
	        'license_no' 				=> $this->input->post('license_no'),
	        'license_body_authority' 	=> $this->input->post('license_body_authority'),
	        'register_date'  			=> ($this->input->post('license_registration_date'))?date('Y-m-d',strtotime($this->input->post('license_registration_date'))):'0000-00-00',
	        'renewal_date'  			=> ($this->input->post('license_renewal_date'))?date('Y-m-d',strtotime($this->input->post('license_renewal_date'))):'0000-00-00',
	        'next_renewal_date'  		=> ($this->input->post('license_next_renewal_date'))?date('Y-m-d',strtotime($this->input->post('license_next_renewal_date'))):'0000-00-00',
	        'created_at'				=> date('Y-m-d H:i:s')
		);
        
		$newLicense = $this->license->createLicense($insertData);

        if($newLicense)
        {
        	if(isset($_FILES['attachment_file']))
        	{
				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);

        		$data_attachment = array
        		(
        			'user_id'						=> $this->session->userdata('user')['id'],
        			'license_id'					=> $newLicense,
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '7'.$newLicense.''.date('Ymd').''.uniqid(),
        		);

        		$save_attachment = $this->license_attachment->createAttachment($data_attachment);
			}

			$update_detail = array 
			(
				'item_change' 		=> "Professional License",
				'detail'			=> "Name of License - ".$this->input->post('license_profession')."<br> License No - ".$this->input->post('license_no')."<br> Licensing Body/Authority - ".$this->input->post('license_body_authority')."<br> Register Date - ".$this->input->post('license_registration_date')."<br> Latest Renewed Date - ".$this->input->post('license_renewal_date')."<br> Next Renewal Date - ".$this->input->post('license_next_renewal_date'),
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     	=> "success",
				"msg" 			=> "successfully update professional license",
			    "updateLicense" => $newLicense,
			    "redirect"		=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

	function deleteLicense()
	{
		$license_id =  $this->input->post('id');
		$profiling_id =  $this->input->post('profiling_id');

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

		$deleteLicense = $this->license->editLicense($updateData,$license_id);
		$deleteLicenseAttachment = $this->license_attachment->editAttachment(array(
			'is_delete' => 1),null,$license_id);

		if($deleteLicense)
        {
			$update_detail = array 
			(
				'item_change' 		=> "Professional License",
				'detail'			=> "Delete Professional License",
				'date_change'		=> date('d-m-Y H:i:s')
			);
        	
			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

        	print json_encode(array(
                "status"     		=> "success",
                "deleteLicense" 	=> $deleteLicense,
                "msg" 		    	=> "professional license deleted.",
                "redirect"			=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
            ));

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

	function staffDetail($staff_id = 0, $profiling_id_new = 0)
	{
		$this->load->model('hr/model_profiling');
		// if(!$staff_id) $staff_id = $this->logged_user['id'];
		if(!$staff_id) $staff_id = redirect(base_url('hr/Myprofile/staffDetail/'.$this->logged_user['id']));
		

		$filter = array
		(
			'action_type_id'		=> 10000,
			'YEAR(date_submit)'		=> date('Y'),
			'MONTH(date_submit)'	=> date('m'),
		);

		$current_date 	= strtotime(date('d-m-Y'));
		$live_date 		= strtotime('01-01-2022');
		$end_date 		= strtotime('10-01-2022');
		$page_title 	= ($current_date < $live_date)?'Personal Details':'Personal Data Update - '.date('M Y',$live_date);

		if(($staff_id == $_SESSION['user']['id']))
		{
			$data['page_setup'] 					= $this->template->pageSetup('HR', 'Dashboard', $page_title);
			$data['live_date']						= $live_date;
			$data['end_date']						= $end_date;
			$data['btn_hidden'] 					= ($current_date < $live_date && $current_date > $end_date)?'d-none':'';
			$data['submit_status']					= $this->general_model->get_byFilter('user__profiling_status',array(),$filter);
			$data['user_profile'] 					= $this->model_profiling->update_profile_list(null,date('Y-m-d',$live_date),$staff_id);
			$data['profiling_id_new'] 				= $profiling_id_new;
			$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));
			$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['attachments'] 					= $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['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->case_emergency->get_case_of_emergency($staff_id,false);
			$data['pursuing_study']					= $this->pursuing_study->get_pursuing_study($staff_id,false);
			$data['professional_academic']			= $this->professional_academic->fetchProfessionalAcademic($staff_id,false);
			$data['working_experience']				= $this->working_experience->fetchWorkingExperience($staff_id, false, null);
			$data['staff_list']					= $this->model_user_list->getUsers($staff_id);
			/* added 31/12/2021 */
			$data['membership_type']				= $this->promember->fetchMembershipType();

			/* 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 20220128
			$data['professional_experiencemgs']	= $this->professional_experiencemgs->getExpMgs($staff_id);
			//end#

			// debug($this->db->last_query());
			// die();
			$this->template->view('hr/myprofile/list/list', $data);
		}
		else{
			redirect(base_url('/hr'));
		}
	}

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

		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($mode == 9)
		{
			$attachment = $this->model_exam->fetchAttachment(null,$mask_id);
		}

		if(($_SESSION['user']['id'] == $attachment[0]->user_id))
		{
			$this->load->library('fileaccess');
			$file_extension = $attachment[0]->file_ext;
			// die(debug($attachment));
			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');
		}
	}

	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 saveWorkingExperience()
	{
		$insertData = array(
			'profiling_id' 				=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'					=> $this->session->userdata('user')['id'],
			'date_from'					=> $this->input->post('date_from'),
			'date_to'					=> $this->input->post('date_to'),
			'experience' 				=> $this->input->post('working_experience'),
			'nature_engagement' 		=> $this->input->post('nature_engagement'),
			'engagement_period_from' 	=> $this->input->post('engagement_period_from'),
			'engagement_period_to' 		=> $this->input->post('engagement_period_to'),
			'created_by'				=> $this->session->userdata('user')['id']
		);
        
		$newWorkingExperience = $this->working_experience->createWorkingExperience($insertData);

        if($newWorkingExperience)
        {
			print json_encode(array(
			    "status"    			=> "success",
			    "msg"					=> "successfully add New Experience In SALIHIN",
			    "newWorkingExperience" 	=> $newWorkingExperience,
			    "redirect"	 			=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

        } else {
			print json_encode(array(
				"status" 	=> "failed",
				"msg" 		=>  "failed",
				"redirect"	=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));
        }
	}
	
	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);

		$insertData = array(
			'profiling_id' 				=> $this->get_profiling_id($profiling_id),
			'user_id'					=> $this->session->userdata('user')['id'],
			'date_from'					=> $this->input->post('date_from'),
			'date_to'					=> $this->input->post('date_to'),
			'experience' 				=> $this->input->post('working_experience'),
			'nature_engagement' 		=> $this->input->post('nature_engagement'),
			'engagement_period_from' 	=> $this->input->post('engagement_period_from'),
			'engagement_period_to' 		=> $this->input->post('engagement_period_to'),
			'created_by'				=> $this->session->userdata('user')['id'],
		);
        
		$newWorkingExperience = $this->working_experience->createWorkingExperience($insertData);

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

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

	function deleteWorkingExperience()
	{
		$working_experience_id  = $this->input->post('id');
		$profiling_id 			= $this->get_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/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
			));

        } else {
			print json_encode(array(
				"status" 	=> "failed",
				"msg" 		=>  "failed",
				"redirect"	=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_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 saveProfessionalAcademic()
	{
		$type = $this->input->post('type');
		$professional_type = ($type == 0)?'education':'certificate'; 

		$upload_path = 'hr/profiling/'.$this->session->userdata('user')['id'].'/professional_academic/'.$professional_type.'';

		$insertData = array(
			'profiling_id' 		=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'			=> $this->session->userdata('user')['id'],
			'type'   			=> $type,
	        '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'),
	        'created_by'		=> $this->session->userdata('user')['id']
		);
        
		$newProfessionalAcademic = $this->professional_academic->createProfessionalAcademic($insertData);

        if($newProfessionalAcademic)
        {
        	if(isset($_FILES['attachment_file']))
        	{
				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);

        		$data_attachment = array
        		(
        			'user_id'						=> $this->session->userdata('user')['id'],
        			'professional_academic_id'		=> $newProfessionalAcademic,
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '6'.$newProfessionalAcademic.''.date('Ymd').''.uniqid(),
	        		'created_by'					=> $this->session->userdata('user')['id']
        		);
        		
				$save_attachment = $this->professional_academic_attachment->createAttachment($data_attachment);
			}

			if($type == 0)
			{
				$update_detail = array 
				(
					'item_change' 		=> "Professional Education",
					'detail'			=> "Name of Professional Association - ".$this->input->post('associate_name')."<br> Name of Course Study - ".$this->input->post('program')."<br> Date Graduated - ".$this->input->post('date_finish')."<br> Final Result - ".$this->input->post('result'),
					'date_change'		=> date('d-m-Y H:i:s')
				);
			}else{
				$update_detail = array 
				(
					'item_change' 		=> "Professional Certificate",
					'detail'			=> "Name of Certification Body - ".$this->input->post('associate_name')."<br> Name of Certification Programme - ".$this->input->post('program')."<br> Date Finish - ".$this->input->post('date_finish')."<br> Result - ".$this->input->post('result'),
					'date_change'		=> date('d-m-Y H:i:s')
				);
			}

			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     				=> "success",
				"msg" 						=> "successfully add professional ".$professional_type,
			    "newProfessionalAcademic" 	=> $newProfessionalAcademic,
			    "redirect"					=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

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

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

		$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);
		$type = $this->input->post('type');
		$professional_type = ($type == 0)?'education':'certificate'; 

		$upload_path = 'hr/profiling/'.$this->session->userdata('user')['id'].'/professional_academic/'.$professional_type.'';

		$insertData = array(
			'profiling_id' 		=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'			=> $this->session->userdata('user')['id'],
			'type'   			=> $type,
	        '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'),
	        'created_by'		=> $this->session->userdata('user')['id']
		);
        
		$newProfessionalAcademic = $this->professional_academic->createProfessionalAcademic($insertData);

        if($newProfessionalAcademic)
        {
        	if(isset($_FILES['attachment_file']))
        	{
				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);
        
        		$data_attachment = array
        		(
        			'user_id'						=> $this->session->userdata('user')['id'],
        			'professional_academic_id'		=> $newProfessionalAcademic,
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '6'.$newProfessionalAcademic.''.date('Ymd').''.uniqid(),
	        		'created_by'		=> $this->session->userdata('user')['id']
        		);

        		$save_attachment = $this->professional_academic_attachment->createAttachment($data_attachment);
			}

			if($type == 0)
			{
				$update_detail = array 
				(
					'item_change' 		=> "Professional Education",
					'detail'			=> "Name of Professional Association - ".$this->input->post('associate_name')."<br> Name of Course Study - ".$this->input->post('program')."<br> Date Graduated - ".$this->input->post('date_finish')."<br> Final Result - ".$this->input->post('result'),
					'date_change'		=> date('d-m-Y H:i:s')
				);
			}else{
				$update_detail = array 
				(
					'item_change' 		=> "Professional Certificate",
					'detail'			=> "Name of Certification Body - ".$this->input->post('associate_name')."<br> Name of Certification Programme - ".$this->input->post('program')."<br> Date Finish - ".$this->input->post('date_finish')."<br> Result - ".$this->input->post('result'),
					'date_change'		=> date('d-m-Y H:i:s')
				);
			}

			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

			print json_encode(array(
			    "status"     					=> "success",
				"msg" 							=> "successfully update professional ".$professional_type,
			    "updateProfessionalAcademic" 	=> $newProfessionalAcademic,
			    "redirect"						=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_id'])
			));

        } else {
			print json_encode(array(
				"status" 		=> "failed",
				"msg" 			=> "failed",
				"redirect"		=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$insertData['profiling_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)
        {
        	if($type == 0)
			{
				$update_detail = array 
				(
					'item_change' 		=> "Professional Education",
					'detail'			=> "Delete Professional Education",
					'date_change'		=> date('d-m-Y H:i:s')
				);
			}else{
				$update_detail = array 
				(
					'item_change' 		=> "Professional Certificate",
					'detail'			=> "Delete Professional Certificate",
					'date_change'		=> date('d-m-Y H:i:s')
				);
			}

			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

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

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

	function getState()
	{
		$country_id  	= $this->input->post('country_id');
		$states			= $this->general_model->get_byFilter('_ref__state', '', array('country_id' => $country_id));

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

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

	function submit_update_profile()
	{
		$input 		= $this->input->post();
		$staff_id 	= $input['staff_id'];
		$date 		= $input['date'];

		if($this->logged_user['id'] == $staff_id)
		{
			$filter = array
			(
				'action_type_id'		=> 10000,
				'YEAR(date_submit)'		=> date('Y'),
				'MONTH(date_submit)'	=> date('m'),
			);

			$existing_data = $this->general_model->get_byFilter('user__profiling_status',array(),$filter);

			if(!$existing_data)
			{
				$insert = array
				(
					'user_id'			=> $staff_id,
					'status'			=> 1,
					'action_type_id'	=> $filter['action_type_id'],
					'date_submit'		=> $date,
					'created_by'		=> $staff_id
				);

				$submit_status = $this->model_general->insert('user__profiling_status',$insert);
				$query = $this->db->last_query();

				if($submit_status)
		        {
		        	print json_encode(array(
		                "status"     	=> "success",
		                "query" 		=> $query,
		                "msg" 		    => "Successfully submit your profile update.",
		                "redirect"		=> base_url('hr/Myprofile/staffDetail/'.$staff_id)
		            ));
		        }
		        else
		        {
		        	print json_encode(array(
		                "status" 	=> "failed",
		                "query"		=> $query,
		                "msg" 		=> "Failed to submit your profile update.",
		                "redirect"	=> base_url('hr/Myprofile/staffDetail/'.$staff_id)
		            ));
		        }
			}else
			{
				print json_encode(array(
	                "status"     	=> "success",
	                "msg" 		    => "Successfully submit your profile update.",
	                "redirect"		=> base_url('hr/Myprofile/staffDetail/'.$staff_id)
	            ));
			}
		}
	}

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

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

		if($updatePhone)
        {
        	$update_detail = array 
			(
				'item_change' 		=> "Mobile Number",
				'detail'			=> $this->input->post('phone'),
				'date_change'		=> date('d-m-Y H:i:s')
			);

			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];
			
			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}

          	print json_encode(array(
                "status"     		  	=> "success",
                "updatePhone" 			=> $updatePhone,
                "msg" 		    	  	=> "Phone number updated.",
                "redirect"				=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
            ));

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

	function save_hobby()
	{
		$profiling_id 		= $this->get_profiling_id($this->input->post('profiling_id'));
		$data['hobby']		= $this->input->post('hobby');

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

		if($updateHobby)
        {
        	$update_detail = array 
			(
				'item_change' 		=> "Hobby",
				'detail'			=> $this->input->post('hobby'),
				'date_change'		=> date('d-m-Y H:i:s')
			);

			$staffName 		= $this->model_user->getUserDetail($this->logged_user['id'])['name'];

			$email_data = array('hr@salihin.com.my');
			$hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

			if($hr_detail) foreach($hr_detail as $hr_email) 
			{
				array_push($email_data, ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
			}

			if($staffName)
			{
				$emailSubject 		= 'Personal Data Update by '.$staffName.' On '.date('d-m-Y H:i:s');
				$emailMessage 		= $staffName.' has update personal detail. Below is the detail:-';
				$emailDetailForm	= $update_detail;

				$emailSend = $this->send_email($emailSubject, $emailMessage, $emailDetailForm, $email_data);
			}


          	print json_encode(array(
                "status"     		  	=> "success",
                "updateHobby" 			=> $updateHobby,
                "msg" 		    	  	=> "Hobby updated.",
                "redirect"				=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'].'/'.$profiling_id)
            ));

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

	private function send_email($subject = '', $message = '', $detail_form = array(), $user_email = array())
	{
		$email_data['subject'] = $subject;
		$email_data['message'] = $message;
		$email_data['emailDetailForm'] = $detail_form;
		$email_data['emails']  = $user_email;

		// $hr_detail 	= $this->model_user->getUsersEmails(array('d.division_id = 5'));

		// if($hr_detail) foreach($hr_detail as $hr_email) 
		// {
		// 	array_push($email_data['emails'], ($hr_email['primary_email']) ? $hr_email['primary_email'] : (($hr_email['secondary_email']) ? $hr_email['secondary_email'] : $hr_email['email']));
		// }
		
		$this->load->library('email');
		$this->load->library('parser');
		$this->load->library('encrypt');

		$email_template = $this->load->view("template/email/header", "", true);
		$email_template .= $this->load->view("template/email/body/serviceForm", $email_data, true);
		$email_template .= $this->load->view("template/email/footer", "", true);

		$this->email->from('noreply@salihin.com.my')
					->to($email_data['emails'])
					->subject($subject)
					->message($email_template)
					->set_mailtype("html");
		
		// $send = $this->email->send();
		$send = 1;

		// $logEmail['userID']=$this->session->userdata('user')['id'];
		// $logEmail['to']= implode(' ',$email_data['emails']);
		// $logEmail['result']= $send;
		// $logEmail['text']= print_r($this->email,true);
		// $this->db->insert('_log__email',$logEmail);

		if($send)
		{
			$this->session->set_flashdata('success',"Successfully Send Email. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to Send Email. Please try again.");
		}

		return $send;
	}

	/* Farid 220129 */
	public function save_exams()
	{
		if(!empty($this->input->post('exam_result'))){ 
			$result = $this->input->post('exam_result');
		} else {
		 	$result = NULL; 
		}

		$paper_code = $this->input->post('exam_papercode');
		$staff_id   = $this->session->userdata('user')['id'];

		$count_paper_code = $this->model_exam->get_count_paper_code($paper_code, $staff_id);

		if($count_paper_code[0]->count >= 2){ //check repeat papercode

			$this->session->set_flashdata('error',"System failed to save Professional Exam / Courses. This Paper Code already registered 2 times.");
			
			redirect(base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id']));

		} else {

			$insert_data = array(
				'staff_id' 	=> $staff_id, 
				'tab_id'	=> $this->input->post('exam_tab_id'),
				'programme_id'	=> $this->input->post('exam_programme'),
				'paper_code' 	=> $paper_code,
				'title' 	=> $this->input->post('exam_papertitle'),
				'exam_date' 	=> date("Y-m-d", strtotime($this->input->post('exam_date'))),
				'status' 	=> $this->input->post('exam_status'),
				'result' 	=> $result,
				'created_by' 	=> $_SESSION['user']['id'],
			);

			$insert_exam = $this->model_exam->save_exam($insert_data);

			if(isset($_FILES['exam_attachment']))
	        	{
	        		$upload_path 	= 'hr/profiling/'.$this->session->userdata('user')['id'].'/education_in_progress/paper';
				$upload_image 	= $this->upload("attachment", "exam_attachment", $upload_path);
					
	        		$data_attachment = array
	        		(
	        			'user_id'		=> $this->session->userdata('user')['id'],
	        			'exam_id'		=> $insert_exam,
	        			'attachment_name'	=> $_FILES['exam_attachment']['name'],
	        			'location'		=> 'storage/'.$upload_path.'/'.$upload_image['file_name'],
	        			'file_type'		=> $_FILES['exam_attachment']['type'],
	        			'file_ext'		=> $_FILES['exam_attachment']['type'],
	        			'mask_id' 		=> '9'.$newStudy.''.date('Ymd').''.uniqid(),
	        		);

	        		$save_attachment = $this->model_exam->createAttachment_exam($data_attachment);
			}

			if($insert_exam){
				// $this->examEmail('new_exam', $insert_exam);
				$this->session->set_flashdata('success',"Successfully save Professional Exam / Courses.");
			}else{
				$this->session->set_flashdata('error',"System failed to save Professional Exam / Courses.");
			}

			redirect(base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id']));
		}
	}

	public function request_study_leave()
	{
		$paper_id = $this->input->post('paper_id');

		$check_paper_date = $this->model_exam->get_paper_date($paper_id);

		if(empty($check_paper_date[0]->exam_date) || $check_paper_date[0]->exam_date == "1970-01-01" || $check_paper_date[0]->exam_date == null){

			print json_encode(array(
		                "status"     	=> "failed",
		                "msg" 		=> "System failed to request for Study Leave. Your EXAM DATE is EMPTY.",
		        ));

		}else{
			$set = array
		        (
		            'request_sl_status' => 1,
		            'updated_by' 	=> $_SESSION['user']['id'],
		        );

		        $where = array
		        (
		            'id' => $paper_id,
		        );

		        $update_exam = $this->model_exam->update_exam($set, $where);

			if($update_exam){

				$this->examEmail('request_study_leave', $paper_id);

				print json_encode(array(
			                "status"     	=> "success",
			                "update_exam"	=> $update_exam,
			                "msg" 		=> "Successfully request for Study Leave.",
			        ));
			}else{
				print json_encode(array(
			                "status"     	=> "failed",
			                "update_exam" 	=> $update_exam,
			                "msg" 		=> "System failed to request for Study Leave.",
			        ));
			}
		}
	}

	public function edit_exams()
	{

		if(!empty($this->input->post('exam_result_edit')) || $this->input->post('exam_result_edit') != NULL){ 
			$result = $this->input->post('exam_result_edit');
		} else {
		 	$result = NULL; 
		}

		$set = array
		(
			'staff_id' 	=> $this->input->post('exam_staffid_edit'), 
			'programme_id'	=> $this->input->post('exam_programme_edit'),
			'paper_code' 	=> $this->input->post('exam_papercode_edit'),
			'title' 	=> $this->input->post('exam_papertitle_edit'),
			'exam_date' 	=> date("Y-m-d", strtotime($this->input->post('exam_date_edit'))),
			'status' 	=> $this->input->post('exam_status_edit'),
			'result' 	=> $result,
			'updated_by' 	=> $_SESSION['user']['id'],
		);

		$where = array
		(
		    'id' => $this->input->post('exam_examid_edit'),
		);

		$update_exam = $this->model_exam->update_exam($set, $where);

		// echo $this->db->last_query();
		// exit();

		if($update_exam){
			print json_encode(array(
			    "status"     		=> "success",
			    "msg" 			=> "Successfully edit Professional Exam / Courses.",
			    "redirect"			=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'])
			));
		}else{
			print json_encode(array(
			    "status"     		=> "error",
			    "msg" 			=> "System failed to edit Professional Exam / Courses.",
			    "redirect"			=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'])
			));
		}
	}

    	public function clone_exams()
	{
		if(!empty($this->input->post('exam_result_clone')) || $this->input->post('exam_result_clone') != NULL){ 
			$result = $this->input->post('exam_result_clone');
		} else {
		 	$result = NULL; 
		}

		$paper_code 	= $this->input->post('exam_papercode_clone_hidden');
		$staff_id 	= $this->input->post('exam_staffid_clone_hidden');

		$count_paper_code = $this->model_exam->get_count_paper_code($paper_code, $staff_id);

		if($count_paper_code[0]->count >= 2){ //check repeat papercode

			$this->session->set_flashdata('error',"System failed to clone Professional Exam / Courses. This Paper Code already registered 2 times.");

			redirect(base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id']));
			
		} else {
			$insert_data = array(
				'staff_id' 	=> $staff_id, 
				'tab_id'	=> $this->input->post('exam_tab_id_clone'),
				'programme_id'	=> $this->input->post('exam_programme_clone_hidden'),
				'paper_code' 	=> $paper_code,
				'title' 	=> $this->input->post('exam_papertitle_clone_hidden'),
				'exam_date' 	=> date("Y-m-d", strtotime($this->input->post('exam_date_clone'))),
				'status' 	=> $this->input->post('exam_status_clone'),
				'result' 	=> $result,
				'created_by' 	=> $_SESSION['user']['id'],
			);

			$insert_exam = $this->model_exam->save_exam($insert_data);

			if($insert_exam){
				print json_encode(array(
				    "status"     		=> "success",
				    "msg" 			=> "Successfully clone Professional Exam / Courses.",
				    "redirect"			=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'])
				));
			}else{
				print json_encode(array(
				    "status"     		=> "error",
				    "msg" 			=> "System failed to clone Professional Exam / Courses.",
				    "redirect"			=> base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id'])
				));
			}
		}

		redirect(base_url('hr/Myprofile/staffDetail/'.$this->session->userdata('user')['id']));
	}

	public function check_study_leave()
	{
		$exam_id = $this->input->post('exam_id');

		$contain_study_leave = $this->model_exam->get_study_leave($exam_id);

		if($contain_study_leave){
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "This Professional Exam / Courses contain study leave recorded."
			)); 
		}else{
			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Success"
			)); 
		}
	}

	public function delete_exam()
	{
		$set = array
		(
		    'is_delete'  => 1,
		    'updated_by' => $_SESSION['user']['id'],
		);

		$where = array
		(
		    'id' => $this->input->post('exam_id'),
		);

		$delete_exam = $this->model_exam->update_exam($set, $where);

		if($delete_exam){
			print json_encode(array(
					"status" => "Success",
					"msg"  	 => "Successfully delete Professional Exam / Courses."
				)); 
		} else {
			print json_encode(array(
					"status" => "Error",
					"msg"    => "System failed to delete Professional Exam / Courses."
				));
		}
	}

	public function examEmail($mode, $id)
	{
		if($mode == 'new_exam'){

			$form_detail 			= array();
			$data['data_exam']		= $this->model_exam->getExamListByID($id);
			// $form_requestor_detail 	= $this->model_user->getUsersEmails(array('c.module_id IN (4)','c.access_lvl IN ("admin")','c.status = 0','c.is_delete = 0','d.department_id IN (2)','d.is_delete = 0','d.status = 0'));

			$form_requestor_detail = array('0' => array('primary_email' => 'faridfirdaus@salihin.com.my'),
										   '1' => array('primary_email' => 'faridfirdauszukpeli@gmail.com'));
			
			if($form_requestor_detail)
			{
				foreach ($form_requestor_detail as $key => $value) {
					$form_requestor_email 	= ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);

					$emailSubject 			= 'New Professional Exam / Courses Request by '.$data['data_exam'][0]->staff_name;
					$emailMessage 			= 'A new professional exam / courses was received for your reference. Kindly review the details and assign the allocation for the respective request. <br> Paper Code : '.$data['data_exam'][0]->paper_code.' <br> Link : '.base_url('hr/exam/exam_list_admin');
					$emailDetailForm		= $form_detail;

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

			return $id;

		} else if($mode == 'clone_exam'){

			$form_detail 			= array();
			$data['data_exam']		= $this->model_exam->getExamListByID($id);

			// $form_requestor_detail 	= $this->model_user->getUsersEmails(array('c.module_id IN (4)','c.access_lvl IN ("admin")','c.status = 0','c.is_delete = 0','d.department_id IN (2)','d.is_delete = 0','d.status = 0'));

			$form_requestor_detail = array('0' => array('primary_email' => 'faridfirdaus@salihin.com.my'),
										   '1' => array('primary_email' => 'faridfirdauszukpeli@gmail.com'));
			
			if($form_requestor_detail)
			{
				foreach ($form_requestor_detail as $key => $value) {
					$form_requestor_email 	= ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);

					$emailSubject 			= 'Cloned Professional Exam / Courses Request by '.$data['data_exam'][0]->staff_name;
					$emailMessage 			= 'Cloned professional exam / courses was received for your reference. Kindly review the details and assign the allocation for the respective request. <br> Paper Code : '.$data['data_exam'][0]->paper_code.' <br> Link : '.base_url('hr/exam/exam_list_admin');
					$emailDetailForm		= $form_detail;

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

			return $id;
		} else if($mode == 'request_study_leave'){

			$form_detail 			= array();
			$data['data_exam']		= $this->model_exam->getExamListByID($id);
			// $form_requestor_detail 	= $this->model_user->getUsersEmails(array('c.module_id IN (4)','c.access_lvl IN ("admin")','c.status = 0','c.is_delete = 0','d.department_id IN (2)','d.is_delete = 0','d.status = 0'));

			$form_requestor_detail = array('0' => array('primary_email' => 'faridfirdaus@salihin.com.my'),
										   '1' => array('primary_email' => 'faridfirdauszukpeli@gmail.com'));
			
			if($form_requestor_detail)
			{
				foreach ($form_requestor_detail as $key => $value) {
					$form_requestor_email 	= ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);

					$emailSubject 		= '[New Professional Exam / Courses] - Study Leave Request by '.$data['data_exam'][0]->staff_name;
					$emailMessage 		= 'Study Leave Request was received for your reference. Kindly review the Professional Exam / Courses details and assign the allocation for the respective request. <br> Paper Code : '.$data['data_exam'][0]->paper_code.' <br> Link : '.base_url('hr/exam/exam_list_admin');
					$emailDetailForm	= $form_detail;

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

			return $id;

		}
	}

	private function send_copy_email($subject = '', $message = '', $detail_form = array(), $user_email = array())
	{
		$email_data['subject'] = $subject;
		$email_data['message'] = $message;
		$email_data['emailDetailForm'] = $detail_form;
		$email_data['emails']  = [];

		if(!is_array($user_email)) 
		{
			array_push($email_data['emails'], $user_email);
		}else{
			$email_data['emails'] = $user_email;
		}
		
		$this->load->library('email');
		$this->load->library('parser');
		$this->load->library('encrypt');

		$email_template = $this->load->view("template/email/header", "", true);
		$email_template .= $this->load->view("template/email/body/serviceForm", $email_data, true);
		$email_template .= $this->load->view("template/email/footer", "", true);
		
		$this->email->from('noreply@salihin.com.my')
					->to($email_data['emails'])
					->subject($subject)
					->message($email_template)
					->set_mailtype("html");
		
		$send = $this->email->send(); //comment this if dont want to send email 
		// $send = 1;

		if($send)
		{
			$this->session->set_flashdata('success',"Successfully Send Email. Thank you.");
		}else{
			$this->session->set_flashdata('error',"System failed to Send Email. Please try again.");
		}

		return $send;
	}
	/* End Farid 220129 */
}
?>