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

class Claim_v2 extends MY_Controller
{
	
	function __construct()
	{
		parent::__construct();
		$this->load->module('template');
		$models = array
		(
			array('model' => 'Admin/model_company',					'name'	=> 'model_company'),
			array('model' => 'CRM/country',							'name'	=> 'country'),
			array('model' => 'CRM/general_model',					'name'	=> 'general_model'),
			array('model' => 'CRM/model_crm',						'name'	=> 'model_crm'),
			array('model' => 'hr/model_claim',						'name'	=> 'model_claim'),
			array('model' => 'hr/model_dental',						'name'	=> 'dental'),
			array('model' => 'hr/model_claim_meal',					'name'	=> 'meal'),
			array('model' => 'hr/model_user_family',				'name'	=> 'family'),
			array('model' => 'hr/model_claim_others',				'name'	=> 'other'),
			array('model' => 'hr/model_claim_travel',				'name'	=> 'travel'),
			array('model' => 'hr/model_claim_mileage',				'name'	=> 'mileage'),
			array('model' => 'hr/model_medical_screening',			'name'	=> 'medical'),
			array('model' => 'hr/model_claim_allocation',			'name'	=> 'allocation'),
			array('model' => 'hr/model_claim_outpatient',			'name'	=> 'outpatient'),
			array('model' => 'hr/model_hospitalization',			'name'	=> 'hospitalization'),
			array('model' => 'hr/Model_claim_panel',				'name'	=> 'panel'),
			array('model' => 'hr/model_ref_claim_type_detail',		'name'	=> 'ref_claim'),
			array('model' => 'hr/Model_claim_allocation_detail',	'name'	=> 'allocation_detail'),
			array('model' => 'hr/model_zone_claim_type', 			'name'	=> 'zone'),
			array('model' => 'hr/model_claim_accomodation', 		'name'	=> 'accomodation'),
			array('model' => 'hr/model_claim_transportation', 		'name'  => 'transportation'),
			array('model' => 'hr/model_claim_parking', 				'name'  => 'parking'),
			array('model' => 'hr/model_claim_toll', 				'name'  => 'toll'),
			array('model' => 'hr/model_claim_subsistence_allowance','name'  => 'subsistence'),
			array('model' => 'hr/model_claim_trainer', 				'name'	=> 'trainer'),
			array('model' => 'hr/Model_claim_panel',				'name'	=> 'panel_claim'),
			array('model' => 'hr/model_claim_allocation', 			'name' 	=> 'allocation'),
			array('model' => 'hr/model_dressing',					'name'	=> 'dressing'),
			array('model' => 'hr/model_gadget',						'name'	=> 'gadget'),
			array('model' => 'hr/model_job_v2',						'name'	=> 'job_v2'),
		);
		foreach($models as $model)
		{
			$this->load->model($model['model'],$model['name']);
		}

		$this->logged_user = $this->session->userdata('user');

		if($this->logged_user)
		{
			$this->login->checkModuleAccess(4);
			$this->logged_module = $this->session->userdata('module_data');
		}
		else
		{
			redirect(base_url()); 
		}

	}

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

	function dashboard()
	{
	}

	function Rule()
	{
		$data = array(
			'role'				=> $this->logged_module['role'],
			'page_setup'		=> $this->template->pageSetup('HR', 'home', 'Claim')
		);

		$this->template->view('hr/claim/rules', $data);
	}

	function searchPatient()
	{
		$search_field = $this->input->post('search_field');
		$search_information = $this->model_claim->searchPatient($search_field);
		echo json_encode($search_information);return true;
	}

	//---------------------------------------------------------------//
	//           Allocation                                          //
	//---------------------------------------------------------------//
	/**
	 * version 1.0 		: allocation setup
	 * deprecated and will be replace with StaffAllocation()
	 */
	function AllocationList()
	{
		$first_day 	='1-1-'.date('Y'); 
		$last_day 	='31-12-'.date('Y');

		$data = array(
			'role'				=> $this->logged_module['role'],
			'room'				=> $this->ref_claim->getRefClaimType(3),
			'staff'				=> $this->model_user->getUsers(),
			'dental'			=> $this->ref_claim->getRefClaimType(4),
			'department'		=> array(),
			'page_setup'		=> $this->template->pageSetup('HR', 'home', 'Claim'),
			'outpatient'		=> $this->ref_claim->getRefClaimType(1),
			'allocations'		=> $this->allocation->fetchAllocation(null,date('Y').'-m-d',$last_day, 0, 0),
			'hospitalization' 	=> $this->ref_claim->getRefClaimType(2),
		);
				
		$this->template->view('hr/claim/claim_allocation_list', $data);
	}

	function Allocation()
	{
		$data = array(
			'role' 				=> $this->logged_module['role'],
			'room'				=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claimTypeID' => 3)),
			'staff'				=> $this->model_user->getUsers(),
			'page_setup'		=> $this->template->pageSetup('HR', 'home', 'Claim'),
			'outpatient' 		=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claimTypeID' => 1)),
			'dental'			=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claimTypeID' => 4)),
			'hospitalization' 	=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claimTypeID' => 2)),
		);

		$this->template->view('hr/claim/add_claim_allocation', $data);
	}

	/**
	 * version 2.0 		: allocation setup
	 * update at	 	: 20190506
	 * objective 		: simplify the process for allocation setup and update UI
	 * reason 			: 
	 * 					- to replace the functionality of AllocationList()
	 * 					- Allocation list have short value or not precise for month
	 * 					- Possibilities some of the staff will not get allocation
	 */
	function StaffAllocation($year = null)
	{
		if($this->logged_module['role'] !== 'admin')redirect(base_url('hr/claim/myClaimList'));
		if(empty($year))$year = date('Y');

		$allocations 	= 	$this->allocation->get_allocation_for_year($year);
		
		$users			=  	$this->model_user->getUsers();
		$unset_user 	= 	array(); 
		
		/**
		 * find user not have allocations
		 */
		if(!empty($users))foreach ($users as $key => $row) 
		{
			// $not_set = true;
			if(!empty($allocations))foreach ($allocations as $index => $allocate) 
			{
				if($allocate->user_id == $row['id'])
				{
					unset($users[$key]);
				}
			}
		}

		$data = array
		(
			'allocations'			=> $allocations,
			'page_setup'			=> $this->template->pageSetup('HR', 'home', 'Staff Allocation'),
			'disable_allocation'	=> (empty($allocations))?false:true,
			'allocation_types'		=> $this->allocation->get_allocation_type(),
			'users'					=> $users,
			'token'					=> $_SESSION['token'],
			'year'					=> $year,
			'all_users'				=> $this->model_user->getUsers(),
			'dressing_allocation'	=> $this->model_claim->getDressing_allocation($year),
			'gadget_allocation'		=> $this->model_claim->getGadget_allocation($year)
		);

		$this->template->view('hr/claim/page/admin/staff-allocation-chart',$data);
	}

	/**
	 * version 2.0 		: create allocation and schedule to a new date
	 * update at 		: 20190508
	 */
	function createAllocation()
	{
		$input = $this->input->post();
		if(!empty($input['all_staff']))
		{
			//allocate all staff with 
			$this->allocation->create_allocation(date('Y'));
			
			if(!empty($input['schedule']))
			{
				$this->allocation->schedule_for_next_year(date('Y'));	
			}
		}
		redirect(base_url('hr/Claim/StaffAllocation'));
	}

	/**
	 * version 2.0 		: create staff allocation 
	 * updated at 		: 20190514
	 * description 		: create allocation for a unique person
	 */
	function createStaffAllocation()
	{
		$input 	= $this->input->post();

		if(empty($input['name']) || empty($input['start_month']) || empty($input['end_month']))
		{
			redirect(base_url('hr/claim/staffAllocation'));
		}
		
		/**
		 * 1. get claim allocation type amount
		 */
		$allocation_detail = $this->allocation->get_allocation_type();
		
		if(!empty($allocation_detail))foreach ($allocation_detail as $key => $row) 
		{
			if($input['outpatient'] == $row->id)
			{
				$outpatient_amount = $row->amount;
			}

			if($input['hospitalization'] == $row->id)
			{
				$hospitalization_amount = $row->amount;
			}

			if($input['room_package'] == $row->id)
			{
				$room_package_amount = $row->amount;
			}

			if($input['dental_optical'] == $row->id)
			{
				$dental_optical_amount = $row->amount;
			}
		}

		/**
		 *2. set hr__claim_allocation
		 *3. Updated by Farid 2021/02/19
		 	 Add 2 column for 2021 when HR decide to off prorate for outpatient and dental.
		 		ALTER TABLE `hr__claim_allocation` ADD `outpatient` DOUBLE NOT NULL AFTER `room_package`, ADD `dental_optical` DOUBLE NOT NULL AFTER `outpatient`;
		 */
		$hr__claim_allocation = array
		(
			'user_id' 			=> $input['name'],
			'year' 				=> date('Y'),
			'hospitalization'	=> $hospitalization_amount,
			'room_package'		=> $room_package_amount,
			'outpatient'		=> $outpatient_amount,
			'dental_optical'	=> $dental_optical_amount,
			'created_by'		=> $_SESSION['user']['id'],
			'is_delete'			=> 0,
			'deleted_by'		=> 0
		);

		//debug($hr__claim_allocation); die();
		
		$claim_allocation_id = $this->allocation->allocate($hr__claim_allocation);

		/**
		* set hr__claim_allocation_prorate 
		* Comment this prorate part. No prorate for dental optical and outpatient for 2021. Updated by Farid 2021/02/19
		*/

		// if(!empty($claim_allocation_id))
		// {
		// 	$start_month 	= $input['start_month'];
		// 	$end_month 	= $input['end_month'];

		// 	$invalid_outpatient_prorate 	= 0;
		// 	$invalid_dental_prorate 		= 0;

		// 	for ($i=1; $i <= 12; $i++) 
		// 	{ 
		// 		$prorate_outpatient = ($outpatient_amount / 12) * $i;
		// 		$prorate_dental 	= ($dental_optical_amount/12) * $i;

		// 		//when start month is not January
		// 		if($start_month > $i)
		// 		{
		// 			$invalid_outpatient_prorate = ($outpatient_amount / 12) * $i;
		// 			$invalid_dental_prorate 	= ($dental_optical_amount/12) * $i;
		// 		}
		// 		$prorate_outpatient = $prorate_outpatient - $invalid_outpatient_prorate;
		// 		$prorate_dental 	= $prorate_dental - $invalid_dental_prorate;

		// 		//when end month is less than decemeber
		// 		if($end_month < $i)
		// 		{	
		// 			$prorate_outpatient = 0;
		// 			$prorate_dental 	= 0;
		// 		}

		// 		$hr__claim_allocation_prorate = array
		// 		(
		// 			'claim_allocation_id'	=> $claim_allocation_id,
		// 			'user_id'				=> $input['name'],
		// 			'year'					=> date('Y'),
		// 			'month'					=> $i,
		// 			'outpatient'			=> $prorate_outpatient,
		// 			'dental_optical'		=> $prorate_dental,
		// 			'created_by'			=> $_SESSION['user']['id'], 
		// 		);
		// 		$this->allocation->allocateProrate($hr__claim_allocation_prorate);
		// 	}
		// }
		
		redirect(base_url('hr/claim/staffAllocation'));
	}

	function updateStaffAllocation()
	{
		$input = $this->input->post();
		$allocation_detail = $this->allocation->get_allocation_type();
		// die(debug($input));		
		if(!empty($allocation_detail))foreach ($allocation_detail as $key => $row) 
		{
			if($input['outpatient'] == $row->id)
			{
				$outpatient_amount = $row->amount;
			}

			if($input['hospitalization'] == $row->id)
			{
				$hospitalization_amount = $row->amount;
			}

			if($input['room_package'] == $row->id)
			{
				$room_package_amount = $row->amount;
			}

			if($input['dental_optical'] == $row->id)
			{
				$dental_optical_amount = $row->amount;
			}
		}

		/**
		 * update hr__claim_allocation based on id
		 */
		$hr__claim_allocation = array
		(
			'hospitalization'	=> $hospitalization_amount,
			'room_package'		=> $room_package_amount,
			'outpatient'		=> $outpatient_amount,
			'dental_optical'	=> $dental_optical_amount,
		);
		$this->allocation->updateAllocation($input['allocation_id'],$hr__claim_allocation);

		/**
		 * update allocation prorate
		 * off due to No Prorate for 2021 by Farid 20210311
		 */
		// $start_month 									= $input['start_date'];
		// $end_month 										= $input['end_date'];
		
		// $invalid_outpatient_prorate 	= 0;
		// $invalid_dental_prorate 			= 0;
				
		// for ($i=1; $i <= 12; $i++) 
		// { 

		// 		$where = array
		// 		(
		// 			'claim_allocation_id'			=> $input['allocation_id'],
		// 			'year'										=> date('Y'),
		// 			'month'										=> $i,
		// 			'user_id' 								=> $input['user_id'] 
		// 		);

		// 		/**
		// 		 * calculate allocation prorate for every months
		// 		 */

		// 		$prorate_outpatient = ($outpatient_amount / 12) * $i;
		// 		$prorate_dental 	= ($dental_optical_amount/12) * $i;

		// 		//when start month is not January
		// 		if($start_month > $i)
		// 		{
		// 			$invalid_outpatient_prorate = ($outpatient_amount / 12) * $i;
		// 			$invalid_dental_prorate 	= ($dental_optical_amount/12) * $i;
		// 		}
		// 		$prorate_outpatient = $prorate_outpatient - $invalid_outpatient_prorate;
		// 		$prorate_dental 	= $prorate_dental - $invalid_dental_prorate;

		// 		//when end month is less than decemeber
		// 		if($end_month < $i)
		// 		{	
		// 			$prorate_outpatient = 0;
		// 			$prorate_dental 	= 0;
		// 		}


		// 		$hr__claim_allocation_prorate = array
		// 		(
		// 			'outpatient' 			=> $prorate_outpatient,
		// 			'dental_optical' 	=> $prorate_dental
		// 		);
				
		// 		$this->allocation->updateProrate($where,$hr__claim_allocation_prorate);
		// }

		redirect(base_url('hr/Claim/staffAllocation'));
	}

	function myClaimList($year = null)
	{
		if(empty($year))$year = date('Y');

		//own data
		{
			$user_id 	= $_SESSION['user']['id'];
			$first_day 	= '1-1-'.date('Y'); 
			$last_day 	= '31-12-'.date('Y');
			
			$data = array
			(
				'claims'				=> $this->model_claim->fetchClaimRecords($user_id,array('a.year' => $year)), 
				'role'					=> $this->logged_module['role'],
				'staff'					=> $this->model_user->getUsers(),
				'claimType' 			=> $this->model_general->fetchAll('_ref__claim_type', array('*'), array('parent' => 0)),
				'page_setup' 			=> $this->template->pageSetup('HR', 'home', 'Claim : Submission List'),
				'is_manager_and_above'	=> $this->isManagerAndAbove($user_id),
				'is_team_leader'		=> $this->isTeamLeader($user_id),
				'lead_jobs'				=> $this->job_v2->get_lead_jobs($user_id),
				'panel'					=> null,
				'filter_years'			=> $this->model_claim->fetchClaimYear($user_id),
				'filtered_year'			=> $year,
			);
		
			{
				$data['yearList'][1]=date('Y');
				if(date('m') < 5 ) $data['yearList'][0] = $data['yearList'][1] - 1;
			}
		}

		if($this->isManagerAndAbove($user_id))
		{
			$data['department']['claims'] = $this->model_claim->getDepartmentClaim($this->logged_user['department_id']);
		}

		// 1. get the job the we lead 
		// 2. get the team member for the job that we lead 
		// 3. get the claim of the team
		$datateam_member_claim = array();

		if($this->isTeamLeader($user_id)) 
		{
			foreach ($data['lead_jobs'] as $key => $jobs) {
				$team_member_claim = $this->job_v2->get_team_member_claim_submission($jobs->ID); 
				array_push($datateam_member_claim, $team_member_claim);
			}
		}

		$this->template->view('hr/claim/my_claim_list_v2', $data);
	}

	function myClaimDetail($year,$month,$user_id,$claim_id,$hod_approval='')
	{
		$this->claimDetail($year,$month,$user_id,$claim_id,$hod_approval);
	}

	function my_claim_detail($year,$month,$user_id,$claim_id,$hod_approval='')
	{
		$this->claimDetail($year,$month,$user_id,$claim_id,$hod_approval,4);		
	}

	function submitClaim()
	{
		$user = $this->session->userdata('user');
		$prev_url 		= $this->input->server('HTTP_REFERER');
		$id 			= $this->input->post('id');
		$managers		= $this->deptManagers($user['department_id']);
		$this->model_claim->editClaimMonth(array('is_submit' => 1),$id);
		
		if(!empty($managers))
		{
			foreach($managers as $key => $value)
			{
				$email_subject = 'One new claim require your attention';
				$this->createEmail($value['email'],$email_subject,'claimReview');
				$this->createWebNotification($user['id'],$value['user_id'],$prev_url.'/approval-hod','claim',$email_subject,'Claim need to be approved and verified before 7th day of each months');
			}

		}else
		{
			$hr = PHP_EOL.'============================================='.PHP_EOL;
			$content = $hr.'Logging start : '.date('d-m-Y h:i:s').PHP_EOL.$hr.'Claim URL : '.$prev_url.PHP_EOL.$hr.'Logging end :'.date('d-m-Y h:i:s').PHP_EOL.$hr;
			$this->log('./application/storage/log/claim_'.date('Y-m-d').'.txt',$content);
		}
		echo json_encode(array('status' => 'ok'));return true;
		// redirect($prev_url);
	}

	function claimMonthSave()
	{
		$input 				= $this->input->post();
		$input['user_id']	= $_SESSION['user']['id'];
		$input['status'] 	= 0;

		if($this->model_claim->getMyClaimMonth($input['year'],$input['month'])){
			$data = array(
				'status' 	=> 'error',
				'msg'		=> 'You have already create claim for respective month'
			);
		}else{

			$row_id = $this->model_claim->insertNewClaimMonth($input);
			if($row_id){
				$data = array(
					'status' => 'success',
					'msg'=> 'success',
				);
			}else{
				$data = array(
					'status' => 'error',
					'msg'=> 'unable to save',
				);
			}
		}
		
		echo json_encode($data);return true;
	}

	function removeClaimDetail()
	{
		$id = $this->input->post('id');
		$data = array('is_delete' => 1);
		$this->panel->editClaimDetail($data,$id);

		$status = array(
			'status' 	=> 'Success',
			'msg'		=> ''
		);

		echo json_encode($status);
		return true;
	}

	function printClaim()
	{
		$data['claims']		= $this->panel->fetchClaim(array('a.is_delete'=> 0));
		$header = array();
		$header['title'] = 'Panel Clinic Claim Detail';
		$this->load->view('hr/report/header.php', $header);
		$this->load->view('hr/report/claim/panel-claim.php',$data);
		$this->load->view('hr/report/footer.php');
	}

	function printClaimDetail($id)
	{
		$data['claim_details']	= $this->panel->fetchClaimDetail(array('is_delete' => 0,'panel_claim_id' => $id));

		$header = array();
		$header['title'] = 'Panel Clinic Claim Detail';
		$this->load->view('hr/report/header.php', $header);
		$this->load->view('hr/report/claim/panel-claim-detail.php',$data);
		$this->load->view('hr/report/footer.php');
	}

	function hodApprove($id = null)
	{
		$this->load->model('model_claim_petrol','petrol');
		$this->load->model('model_claim_entertainment','entertainment');

		$user = $this->session->userdata('user');
		$msg = '';
		$input = $this->input->post();
		$update = array (
			'is_hod_approved' 	=> (!empty($input['status']))?$input['status']:1,
			'approved_hod_by'	=> (!empty($user['id']))?$user['id']:$user['id'],
		);

		if(!empty($id))
		{
			$where = array('id' => $input['claim_id']);
			switch($input['mode'])
			{
				case 1:  //outpatient claim approve
					$this->outpatient->updateOutpatientJournal($update,$where);
                    $this->outpatient->updateOutpatient($update,array('journal_id' => $input['claim_id']));
                    $msg = 'Successfull update outpatient claim';
					break;
				case 2: //hospitalization claim approve
                    $this->hospitalization->updateHospitalization($update,$where);
                    $msg = 'Successfull update hospitalization claim';
					break;
				case 3: //dental claim approve
					$this->dental->updateDentalJournal($update,$where);
                    $this->dental->updateDental($update,array('journal_id' => $input['claim_id']));
                    $msg = 'Successfull update dental / optical claim';
					break;
				case 4: //medical claim approve
                    $this->medical->updateMedical($update,$where);
                    $msg = 'Successfull update medical claim';
					break;
				case 5: //mileage claim approve
                    $this->mileage->updateMileage($update,$where);
                    $msg = 'Successfull update mileage claim';
					break;
				case 6: //travel claim approve
                    $this->travel->updateTravel($update,$where);
                    $msg = 'Successfull update mileage claim';
					break;
				case 7: //meal claim approve
                    $this->meal->updateMeal($update,$where);
                    $msg = 'Successfull update meal claim';
					break;
				case 8: //other claim approve
                    $this->other->updateOtherClaim($update,$where);
                    $msg = 'Successfull update other claim';
					break;
				case 9://accomodation claim approve
                    $this->accomodation->updateClaim(array('is_hod_approve' => 1),$where);
                    $msg = 'Successfull update accommodation claim';
					break;
				case 10: //subsistence claim approve
                    $this->subsistence->updateSubsistence(array('is_hod_approved' => 1),$where);
                    $msg = 'Successfull update subsistence claim';
					break;
				case 11://trasnportation claim approve
                    $this->transportation->updateTransportation(array('is_hod_approved' => 1),$where);
                    $msg = 'Successfull update transportation claim';
					break;
				case 12: //parking claim approve
                    $this->parking->updateParking(array('is_hod_approve' => 1),$where);
                    $msg = 'Successfull update parking claim';
					break;
				case 13://toll claim approve
                    $this->toll->updateToll(array('is_hod_approve' => 1),$where);
                    $msg = 'Successfull update toll parking';
					break;
				case 14: //trainer claim approve
                    $this->trainer->updateClaim(array('is_hod_approve' => 1),$where);
					$msg = 'Successfull update trainer / facilitator claim';
					break;	
				case 15: //petrol claim approve
					$this->petrol->updatePetrol(array('is_hod_approve' => 1),$where);
					$msg = 'Successfull update petrol claims';
					break;		
				case 16: //entertainment claims
					$this->entertainment->update_entertainment(array('is_hod_approve' => 1),$where);
					$msg = 'Succesfull update entertainment claims';
					break;	
				case 17: //dressing claims
					$this->dressing->updateClaim(array('is_hod_approved' => 1),$where);
					$msg = 'Succesfull update dressing allowance claim';
					break;
				case 18: //gadget claims
					$this->gadget->updateClaim(array('is_hod_approved' => 1),$where);
					$msg = 'Succesfull update gadget allowance claim';
					break;
			}
			// $msg = 'Successfull approve claim';
		}else
		{
			$where = array('claim_id' => $input['claim_id']);
			$this->dental->updateDental($update,$where);
			$this->dental->updateDentalJournal($update,$where);
			$this->hospitalization->updateHospitalization($update,$where);
			$this->meal->updateMeal($update,$where);
			$this->medical->updateMedical($update,$where);
			$this->mileage->updateMileage($update,$where);
			$this->other->updateOtherClaim($update,$where);
			$this->outpatient->updateOutpatient($update,$where);
			$this->travel->updateTravel($update,$where);
			$this->accomodation->updateClaim(array('is_hod_approve' => 1),$where);
			$this->subsistence->updateSubsistence(array('is_hod_approved' => 1),$where);
			$this->transportation->updateTransportation(array('is_hod_approved' => 1),$where);
			$this->parking->updateParking(array('is_hod_approve' => 1),$where);
			$this->toll->updateToll(array('is_hod_approve' => 1),$where);
			$this->trainer->updateClaim(array('is_hod_approve' => 1),$where);
			$this->petrol->updatePetrol(array('is_hod_approve' => 1),$where);
			$this->entertainment->update_entertainment(array('is_hod_approve' => 1),$where);
			$this->dressing->updateClaim(array('is_hod_approved' => 1),$where);
			$this->gadget->updateClaim(array('is_hod_approved' => 1),$where);
		}

		echo json_encode(array('status' => 'success','msg' => $msg));return true;
	}

	function hodReject()
	{
		$this->load->model('model_claim_petrol','petrol');
		$this->load->model('model_claim_entertainment','entertainment');

		$refer = $_SERVER['HTTP_REFERER'];

		$user = $this->session->userdata('user');
		$msg = '';
		$input = $this->input->post();
		$id = $input['mode'];
		
		$update = array (
			'is_hod_approved' 	=> 2,
			'approved_hod_by'	=> (!empty($user['id']))?$user['id']:$user['id'],
			'hod_remarks'		=> (!empty($input['reason']))?$input['reason']:'',
		);

		if(!empty($id))
		{
			$where = array(
				'id'		=> $input['id'], 
				'claim_id' 	=> $input['claim_id']
			);

			switch($input['mode'])
			{
				//need to add id
				case 1:  //outpatient claim rejected
					$this->outpatient->updateOutpatientJournal($update,$where);
                    $this->outpatient->updateOutpatient($update,array('journal_id' => $input['id']));
                    $msg = 'Outpatient claim rejected';
					break;
				case 2: //hospitalization claim rejected
                    $this->hospitalization->updateHospitalization($update,$where);
                    $msg = 'Hospitalization claim rejected';
					break;
				case 3: //dental claim rejected
					$this->dental->updateDentalJournal($update,$where);
                    $this->dental->updateDental($update,array('journal_id' => $input['id']));
                    $msg = 'Dental / Optical claim rejected';
					break;
				case 4: //medical claim rejected
                    $this->medical->updateMedical($update,$where);
                    $msg = 'Medical claim rejected';
					break;
				case 5: //mileage claim rejected
                    $this->mileage->updateMileage($update,$where);
                    $msg = 'Mileage claim rejected';
					break;
				case 6: //travel claim rejected
                    $this->travel->updateTravel($update,$where);
                    $msg = 'Mileage claim rejected';
					break;
				case 7: //meal claim rejected
                    $this->meal->updateMeal($update,$where);
                    $msg = 'Meal claim rejected';
					break;
				case 8: //other claim rejected
                    $this->other->updateOtherClaim($update,$where);
                    $msg = 'Other claim rejected';
					break;
				case 9: //accomodation claim rejected
                    $this->accomodation->updateClaim(array('is_hod_approve' => 2,'hod_remarks' => $input['reason']),$where);
                    $msg = 'Accommodation claim rejected';
					break;
				case 10: //subsistence claim rejected
                    $this->subsistence->updateSubsistence(array('is_hod_approved' => 2,'hod_remarks' => $input['reason']),$where);
                    $msg = 'Subsistence claim rejected';
					break;
				case 11: //transportation claim rejected
                    $this->transportation->updateTransportation(array('is_hod_approved' => 2,'hod_remarks' => $input['reason']),$where);
                    $msg = 'Transportation claim rejected';
					break;
				case 12: //parking claim rejected
                    $this->parking->updateParking(array('is_hod_approve' => 2,'hod_remarks' => $input['reason']),$where);
                    $msg = 'Parking claim rejected';
					break;
				case 13: //toll claim rejected
                    $this->toll->updateToll(array('is_hod_approve' => 2,'hod_remarks' => $input['reason']),$where);
                    $msg = 'Toll claim rejected';
					break;
				case 14: //trainer claim rejected
                    $this->trainer->updateClaim(array('is_hod_approve' => 2,'hod_remarks' => $input['reason']),$where);
                    $msg = 'Trainer / Facilitator claim rejected';
					break;
				case 15: //petrol claim rejected
					$this->petrol->updatePetrol(array('is_hod_approve' => 2,'hod_remarks' => $input['reason']),$where);
					$msg = 'Petrol claim rejected';
					break;		
				case 16://entertainment claim rejected
					$this->entertainment->update_entertainment(array('is_hod_approve' => 2,'hod_remarks' => $input['reason']), $where);
					$msg = 'Entertainment claim rejected';
					break;
				case 17: //dressing claim rejected
                    $this->dressing->updateClaim(array('is_hod_approved' => 2,'hod_remarks' => $input['reason']),$where);
                    $msg = 'Dressing allowance claim rejected';
					break;
				case 18: //gadget claim rejected
                    $this->gadget->updateClaim(array('is_hod_approved' => 2,'hod_remarks' => $input['reason']),$where);
                    $msg = 'Gadget allowance claim rejected';
					break;
            }
            $this->session->set_flashdata('success',$msg);
		}else
		{
			//rejecting all claims 
		}

		if($refer)
		{
			redirect($refer);
		}else{
			redirect(base_url());
		}
	}

	function emApprove($id = null)
	{
		$this->load->model('model_claim_petrol','petrol');
		$this->load->model('model_claim_entertainment','entertainment');

		$user = $this->session->userdata('user');
		$msg = '';
		$input = $this->input->post();
		$update = array (
			'is_em_approved'	=> (!empty($input['status']))?$input['status']:1,
			'approved_em_by'	=> (!empty($user['id']))?$user['id']:$user['id'],
		);

		if(!empty($id))
		{
			$where = array('id' => $input['claim_id']);
			switch($input['mode'])
			{
				case 5: //mileage claim approve
                    $this->mileage->updateMileage($update,$where);
                    $msg = 'Successfull update mileage claim';
					break;
				case 6: //travel claim approve
                    $this->travel->updateTravel($update,$where);
                    $msg = 'Successfull update mileage claim';
					break;
				case 7: //meal claim approve
                    $this->meal->updateMeal($update,$where);
                    $msg = 'Successfull update meal claim';
					break;
				case 8: //other claim approve
                    $this->other->updateOtherClaim($update,$where);
                    $msg = 'Successfull update other claim';
					break;
				case 9://accomodation claim approve
                    $this->accomodation->updateClaim(array('is_em_approved' => 1, 'approved_em_by' => $user['id']),$where);
                    $msg = 'Successfull update accommodation claim';
					break;
				case 10: //subsistence claim approve
                    $this->subsistence->updateSubsistence(array('is_em_approved' => 1, 'approved_em_by' => $user['id']),$where);
                    $msg = 'Successfull update subsistence claim';
					break;
				case 11://trasnportation claim approve
                    $this->transportation->updateTransportation(array('is_em_approved' => 1, 'approved_em_by' => $user['id']),$where);
                    $msg = 'Successfull update transportation claim';
					break;
				case 12: //parking claim approve
                    $this->parking->updateParking(array('is_em_approved' => 1, 'approved_em_by' => $user['id']),$where);
                    $msg = 'Successfull update parking claim';
					break;
				case 13://toll claim approve
                    $this->toll->updateToll(array('is_em_approved' => 1, 'approved_em_by' => $user['id']),$where);
                    $msg = 'Successfull update toll parking';
					break;
				case 14: //trainer claim approve
                    $this->trainer->updateClaim(array('is_em_approved' => 1, 'approved_em_by' => $user['id']),$where);
					$msg = 'Successfull update trainer / facilitator claim';
					break;	
				case 15: //petrol claim approve
					$this->petrol->updatePetrol(array('is_em_approved' => 1, 'approved_em_by' => $user['id']),$where);
					$msg = 'Successfull update petrol claims';
					break;		
				case 16: //entertainment claims
					$this->entertainment->update_entertainment(array('is_em_approved' => 1, 'approved_em_by' => $user['id']),$where);
					$msg = 'Succesfull update entertainment claims';
					break;
			}
			// $msg = 'Successfull approve claim';
		}else{
			$where = array('claim_id' => $input['claim_id']);
			$this->meal->updateMeal($update,$where);
			$this->mileage->updateMileage($update,$where);
			$this->other->updateOtherClaim($update,$where);
			$this->travel->updateTravel($update,$where);
			$this->accomodation->updateClaim(array('is_em_approve' => 1),$where);
			$this->subsistence->updateSubsistence(array('is_em_approved' => 1),$where);
			$this->transportation->updateTransportation(array('is_em_approved' => 1),$where);
			$this->parking->updateParking(array('is_em_approve' => 1),$where);
			$this->toll->updateToll(array('is_em_approve' => 1),$where);
			$this->trainer->updateClaim(array('is_em_approve' => 1),$where);
			$this->petrol->updatePetrol(array('is_em_approve' => 1),$where);
			$this->entertainment->update_entertainment(array('is_em_approve' => 1),$where);
		}

		echo json_encode(array('status' => 'success','msg' => $msg));return true;
	}

	function emReject()
	{
		$this->load->model('model_claim_petrol','petrol');
		$this->load->model('model_claim_entertainment','entertainment');

		$refer = $_SERVER['HTTP_REFERER'];

		$user = $this->session->userdata('user');
		$msg = '';
		$input = $this->input->post();
		$id = $input['em_mode'];
		
		$update = array (
			'is_em_approved' 	=> 2,
			'approved_em_by'	=> (!empty($user['id']))?$user['id']:$user['id'],
			'em_remarks'		=> (!empty($input['em_reason']))?$input['em_reason']:'',
		);

		if(!empty($id))
		{
			$where = array(
				'id'		=> $input['em_id'], 
				'claim_id' 	=> $input['em_claim_id']
			);

			switch($input['em_mode'])
			{
				//need to add id
				case 1:  //outpatient claim rejected
					$this->outpatient->updateOutpatientJournal($update,$where);
                    $this->outpatient->updateOutpatient($update,array('journal_id' => $input['em_id']));
                    $msg = 'Outpatient claim rejected';
					break;
				case 2: //hospitalization claim rejected
                    $this->hospitalization->updateHospitalization($update,$where);
                    $msg = 'Hospitalization claim rejected';
					break;
				case 3: //dental claim rejected
					$this->dental->updateDentalJournal($update,$where);
                    $this->dental->updateDental($update,array('journal_id' => $input['em_id']));
                    $msg = 'Dental / Optical claim rejected';
					break;
				case 4: //medical claim rejected
                    $this->medical->updateMedical($update,$where);
                    $msg = 'Medical claim rejected';
					break;
				case 5: //mileage claim rejected
                    $this->mileage->updateMileage($update,$where);
                    $msg = 'Mileage claim rejected';
					break;
				case 6: //travel claim rejected
                    $this->travel->updateTravel($update,$where);
                    $msg = 'Mileage claim rejected';
					break;
				case 7: //meal claim rejected
                    $this->meal->updateMeal($update,$where);
                    $msg = 'Meal claim rejected';
					break;
				case 8: //other claim rejected
                    $this->other->updateOtherClaim($update,$where);
                    $msg = 'Other claim rejected';
					break;
				case 9: //accomodation claim rejected
                    $this->accomodation->updateClaim(array('is_em_approved' => 2,'em_remarks' => $input['em_reason']),$where);
                    $msg = 'Accommodation claim rejected';
					break;
				case 10: //subsistence claim rejected
                    $this->subsistence->updateSubsistence(array('is_em_approved' => 2,'em_remarks' => $input['em_reason']),$where);
                    $msg = 'Subsistence claim rejected';
					break;
				case 11: //transportation claim rejected
                    $this->transportation->updateTransportation(array('is_em_approved' => 2,'em_remarks' => $input['em_reason']),$where);
                    $msg = 'Transportation claim rejected';
					break;
				case 12: //parking claim rejected
                    $this->parking->updateParking(array('is_em_approved' => 2,'em_remarks' => $input['em_reason']),$where);
                    $msg = 'Parking claim rejected';
					break;
				case 13: //toll claim rejected
                    $this->toll->updateToll(array('is_em_approved' => 2,'em_remarks' => $input['em_reason']),$where);
                    $msg = 'Toll claim rejected';
					break;
				case 14: //trainer claim rejected
                    $this->trainer->updateClaim(array('is_em_approved' => 2,'em_remarks' => $input['em_reason']),$where);
                    $msg = 'Trainer / Facilitator claim rejected';
					break;
				case 15: //petrol claim rejected
					$this->petrol->updatePetrol(array('is_em_approved' => 2,'em_remarks' => $input['em_reason']),$where);
					$msg = 'Petrol claim rejected';
					break;		
				case 16://entertainment claim rejected
					$this->entertainment->update_entertainment(array('is_em_approved' => 2,'em_remarks' => $input['em_reason']), $where);
					$msg = 'Entertainment claim rejected';
					break;
				case 17: //dressing claim rejected
                    $this->dressing->updateClaim(array('is_em_approved' => 2,'em_remarks' => $input['em_reason']),$where);
                    $msg = 'Dressing allowance claim rejected';
					break;
				case 18: //gadget claim rejected
                    $this->gadget->updateClaim(array('is_em_approved' => 2,'em_remarks' => $input['em_reason']),$where);
                    $msg = 'Gadget allowance claim rejected';
					break;
            }
            $this->session->set_flashdata('success',$msg);
		}else
		{
			//rejecting all claims 
		}

		if($refer)
		{
			redirect($refer);
		}else{
			redirect(base_url());
		}
	}

	function unsubmit_claim()
	{
		$claim_id = $this->input->post('claim_id');
		$this->model_claim->unsubmitted_claim($claim_id);


		echo json_encode(array('status' =>'ok'));
	}

	//hod requires to enter remarks for each claim that have been rejected
	// function hodRejectAllClaim()
	// {
		// 	//1. get all hr__claim id 
		// 	$input = $this->input->post();
		// 	//2. for all claim reject 
		// 	echo json_encode(array('status' => 'ok'));return true;
	// }

	function adminClaimList($year = null , $month = null, $dept_id = null, $status = null)
	{
		// if(!empty($dept_id))
		// {
		// 	$dept_result = $this->model_claim->get_department($dept_id);
		// 	if(!empty($dept_result))
		// 	{
		// 		$dept = $dept_result[0]->name.' ('.$dept_result[0]->branch.')';
		// 	}
		// }
        
        $year = (!empty($year))?$year:date('Y');
        $month = (!empty($month))?$month:date('m');
        $dept_id = (!empty($dept_id))?$dept_id:0;
        $status = (!empty($status))?$status:0;

        $data = array
        (
            'year'          => $year,
            'month'         => $month, 
            'dept_id'       => $dept_id,
            'status'        => $status,           
			'dept_name'	    => (!empty($dept))?$dept:'All Department',
			'page_setup'    => $this->template->pageSetup('HR', 'home', 'Claim submission'),
			'claims'	    => $this->model_claim->getSubmittedClaim($dept_id,$year,$month,$status),
            'departments'   => $this->model_company->getDepartments(),
            'unsubmitted_dentals' => $this->dental->get_current_unsubmitted_dental(),
			'unsubmitted_outpatiens' => $this->outpatient->get_current_unsubmitted_outpatient(),
            'show'          => ($this->session->userdata('user')['id'] == 164)?true:false
        );
		$this->template->view('hr/claim/page/claimlist/admin_v2', $data);
	}

	function adminClaimDetail($year,$month,$user_id,$claim_id,$admin_approval='')
	{
		$this->claimDetail($year,$month,$user_id,$claim_id,$admin_approval);
	}

	function adminProcessedClaim($dept_id = null)
	{
		if(!empty($dept_id))
		{
			$dept_result = $this->model_claim->get_department($dept_id);
			if(!empty($dept_result))
			{
				$dept = $dept_result[0]->name.' ('.$dept_result[0]->branch.')';
			}
		}

		$data = array(
			'dept_name'				=> (!empty($dept))?$dept:'All Department',
			'page_setup'			=> $this->template->pageSetup('HR', 'home', 'Claim paid list'),
			'claims'				=> $this->model_claim->getPaidClaim($dept_id),
			'departments'			=> $this->model_claim->count_dept_paid($dept_id),
		);


		$this->template->view('hr/claim/page/claimlist/admin_processed', $data);
	}

	public function sheet($year,$month,$user_id,$claim_id)
	{		
		$this->load->model('model_claim_petrol','petrol');
		$this->load->model('model_claim_entertainment','entertainment');

		if($month == 1) //month january 
		{
			$outpatient_amount_second_month 	= 	$this->outpatient->get_claim_amount(11,$year-1,$user_id); //11
			$outpatient_amount_first_month	 	= 	$this->outpatient->get_claim_amount(12,$year-1,$user_id); //12

			$dental_amount_second_month			= $this->dental->get_dental_amount(11,$year-1,$user_id); //bulan 11 year -1
			$dental_amount_first_month		 	= $this->dental->get_dental_amount(12,$year-1,$user_id); //bulan 12 year -1 

			$allocation 						= $this->allocation->get_allocation_for_year($year-1, $user_id);
			$hospitalization_prorate_second 	= $allocation;
			$hospitalization_prorate_first 		= $allocation;

			$hospitalization_claimed_first 		= $this->hospitalization->get_claimed_amount($year-1,$user_id);
			$hospitalization_claimed_second 	= $this->hospitalization->get_claimed_amount($year,$user_id);

			/** senarai panel claim unutk kedua2 bulan */
			$panel_first_month = $this->panel->fetch_user_claim_by_invoice_date($user_id,12,$year-1);
			$panel_second_month = $this->panel->fetch_user_claim_by_invoice_date($user_id,11,$year-1);

			$view_claim_outpatient_1 = $this->outpatient->fetch_view_claim_outpatient($user_id,12,$year-1);
			$view_claim_outpatient_2 = $this->outpatient->fetch_view_claim_outpatient($user_id,11,$year-1);
		}elseif ($month == 2) { //month februrary
			$outpatient_amount_second_month 	= 	$this->outpatient->get_claim_amount(12,$year-1,$user_id); //12
			$outpatient_amount_first_month 		= 	$this->outpatient->get_claim_amount(1,$year,$user_id); //1

			$dental_amount_second_month 		 	= $this->dental->get_dental_amount(12,$year-1,$user_id); //bulan 12 year - 1
			$dental_amount_first_month    		= $this->dental->get_dental_amount(1,$year,$user_id); //bulan 1 year; 

			$hospitalization_prorate_second		= $this->allocation->get_allocation_for_year($year-1, $user_id);
			$hospitalization_prorate_first 		= $this->allocation->get_allocation_for_year($year, $user_id);

			$hospitalization_claimed_first = $this->hospitalization->get_claimed_amount($year-1,$user_id);
			$hospitalization_claimed_second = $this->hospitalization->get_claimed_amount($year,$user_id);

			$panel_first_month = $this->panel->fetch_user_claim_by_invoice_date($user_id,1,$year);
			$panel_second_month = $this->panel->fetch_user_claim_by_invoice_date($user_id,12,$year-1);

			$view_claim_outpatient_1 = $this->outpatient->fetch_view_claim_outpatient($user_id,1,$year);
			$view_claim_outpatient_2 = $this->outpatient->fetch_view_claim_outpatient($user_id,12,$year-1);
		}else{
			$outpatient_amount_second_month 	= 	$this->outpatient->get_claim_amount($month-2,$year,$user_id); //-2
			$outpatient_amount_first_month 		= 	$this->outpatient->get_claim_amount($month-1,$year,$user_id); //-1

			$dental_amount_second_month  		 	= $this->dental->get_dental_amount($month-2,$year,$user_id); //month - 2 year;
			$dental_amount_first_month 		 		= $this->dental->get_dental_amount($month-1,$year,$user_id); //month -1 year; 

			$allocation 											= $this->allocation->get_allocation_for_year($year, $user_id);
			$hospitalization_prorate_second 	= $allocation;
			$hospitalization_prorate_first 		= $allocation;

			$hospitalization_claimed_first 		= $this->hospitalization->get_claimed_amount($year,$user_id);
			$hospitalization_claimed_second 	= $this->hospitalization->get_claimed_amount($year,$user_id);

			$panel_first_month = $this->panel->fetch_user_claim_by_invoice_date($user_id,$month-1,$year);
			$panel_second_month = $this->panel->fetch_user_claim_by_invoice_date($user_id,$month-2,$year);

			$view_claim_outpatient_1 = $this->outpatient->fetch_view_claim_outpatient($user_id,$month-1,$year);
			$view_claim_outpatient_2 = $this->outpatient->fetch_view_claim_outpatient($user_id,$month-2,$year);
		}	
		
		$day = date('d');
		$submission_claim = date('F Y',strtotime('01-'.$month.'-'.$year));

		$data = array
		(
			'year'								=> $year,
			'month'								=> $month,
			'claims'							=> ($this->model_claim->getUserClaims($year,$month,$user_id))?$this->model_claim->getUserClaims($year,$month,$user_id)[0]:null,
			'staff' 							=> $this->model_user->getUsers(),
			'others'							=> $this->other->fetchOtherClaim($user_id,$claim_id,$year,$month),
			'clients'							=> $this->model_crm->getCustomer(),
			'dentals_journal'					=> $this->dental->fetchDentalJournal($user_id,$claim_id,$year,$month), 
			'dentals'							=> $this->dental->fetchDental($user_id,$claim_id,$year,$month), 
			'mileage'							=> $this->mileage->fetchMileage($user_id,$claim_id,$year,$month),
			'travels'							=> $this->travel->fetchTravelClaim($user_id,$claim_id,$year,$month), //this data actually a mileage data
			'claimType'							=> $this->model_general->fetchAll('_ref__claim_type', array('*'), array('is_display' => 1),array(),array('sequence' => 'ASC')),
			'page_setup'						=> $this->template->pageSetup('HR', 'home', 'Claim Detail : '.$submission_claim),
			'outpatients'						=> $this->outpatient->fetchOutpatient($user_id,$claim_id,$year,$month),
			'outpatients_journal'				=> $this->outpatient->fetchOutpatientJournal($user_id,$claim_id,$year,$month),
			'hospitalizations'					=> $this->hospitalization->fetchHospitalization($user_id,$claim_id,$year,$month),
			'disabled'							=> ($day > 7 && $day <= 15)?true:(date('m') > $month || date('Y') > $year)?true:false, //TODO: on this when live
			// 'disabled'							=> false,
			'role'								=> $this->session->userdata('module_data')['role'],
			'claims_user'						=> $this->model_user->getUsers($user_id),
			'claim_id'							=> $claim_id,
			'accomodation'						=> $this->accomodation->fetchAccomodation($claim_id),
			'transportation'					=> $this->transportation->fetchTransportation($claim_id),
			'parking'							=> $this->parking->fetchParking($claim_id),
			'toll'								=> $this->toll->fetchToll($claim_id),
			'subsistence'						=> $this->subsistence->fetchSubsistence($claim_id),
			'trainers'							=> $this->trainer->fetchTrainer($claim_id),
			'meals'								=> $this->meal->fetchMeals($user_id,$claim_id,$year,$month),
			'panel_clinic'						=> $this->panel_claim->fetchClaimDetail(array('staff_id'=>$user_id)),
			'petrols'							=> $this->petrol->fetchPetrol($user_id,$claim_id,$year,$month),
			'entertainments'					=> $this->entertainment->fetch_entertainment($user_id,$claim_id,$year,$month),
			'second_month'						=> $outpatient_amount_second_month['month'],
			'second_year'						=> $outpatient_amount_second_month['year'],
			// 'second_prorate_outpatient'			=> $outpatient_amount_second_month['prorate_amount'],
			'second_outpatient_balance'			=> $outpatient_amount_second_month['balance'],
			'first_month'						=> $outpatient_amount_first_month['month'],
			'first_year'						=> $outpatient_amount_first_month['year'],
			// 'first_prorate_outpatient'			=> $outpatient_amount_first_month['prorate_amount'],
			'first_outpatient_balance'			=> $outpatient_amount_first_month['balance'],
			// 'second_prorate_dental'  			=> $dental_amount_second_month['prorate_amount'],
			'second_dental_balance'				=> $dental_amount_second_month['balance'],
			// 'first_prorate_dental'				=> $dental_amount_first_month['prorate_amount'],
			'first_dental_balance'				=> $dental_amount_first_month['balance'],
			'second_hospitalization_prorate'	=> (!empty($hospitalization_prorate_second))?$hospitalization_prorate_second[0]->hospitalization:0.00,
			'second_hospitalization_balance'	=> (!empty($hospitalization_prorate_second))?$hospitalization_prorate_second[0]->hospitalization - $hospitalization_claimed_second:0.00,
			'first_hospitalization_prorate'		=> (!empty($hospitalization_prorate_first))?$hospitalization_prorate_first[0]->hospitalization:0.00,
			'first_hospitalization_balance'		=> (!empty($hospitalization_prorate_first))?$hospitalization_prorate_first[0]->hospitalization - $hospitalization_claimed_first:0.00,
			'panel_first_month'					=> $panel_first_month,
			'panel_second_month'				=> $panel_second_month,
			'view_claim_outpatient_1'			=> $view_claim_outpatient_1,
			'view_claim_outpatient_2'			=> $view_claim_outpatient_2,	
			'dressing'							=> $this->dressing->fetchDressing($claim_id),
			'gadget'							=> $this->gadget->fetchGadget($claim_id)	
		);

		// die(debug($data['meals']));
		/** 
		 * start: check if date are in the submission range
		*/
		$range_date_lower 	= date('d-m-Y',strtotime('15-'.$data['first_month'].'-'.$data['first_year']));
		$range_date_upper 	= date('d-m-Y',strtotime('07-'.$month.'-'.$year));
		if(strtotime(date('d-m-Y')) > strtotime($range_date_lower) && strtotime(date('d-m-Y')) <= strtotime($range_date_upper))
		{
			$data['is_in_submission_range'] = true;
		}else{
			$data['is_in_submission_range'] = false;
		}
		/** 
		 * end: check if date are in the submission range
		*/

		if($data['travels']) foreach ($data['travels'] as $key => $travel) 
		{
			$data['travels'][$key]->details 		= $this->travel->fetchTravelDetail($travel->id);
			$data['travels'][$key]->attachments 	= $this->travel->getAttachment($travel->id);
			$data['travels'][$key]->routes 			= $this->travel->getRoute($travel->id);
		}

		if($data['others']) foreach ($data['others'] as $key => $other) 
		{
			$data['others'][$key]->attachments 		= $this->other->getAttachments($other->id);
		}

		if ($data['outpatients']) foreach ($data['outpatients'] as $key => $outpatient) 
		{
			$data['outpatients'][$key]->attachments = $this->outpatient->fetchAttachment($outpatient->journal_id);
		}

		if ($data['outpatients_journal']) foreach ($data['outpatients_journal'] as $key => $outpatient) 
		{
			$data['outpatients_journal'][$key]->attachments = $this->outpatient->fetchAttachment($outpatient->id);
		}

		if($data['hospitalizations']) foreach ($data['hospitalizations'] as $key => $hosp) 
		{
			$data['hospitalizations'][$key]->attachments = $this->hospitalization->fetchAttachment($hosp->id);
		}

		if($data['dentals']) foreach ($data['dentals'] as $key => $dental) 
		{
			$data['dentals'][$key]->attachments 		= $this->dental->getAttachment($dental->journal_id);
		}
		
		if($data['dentals_journal']) foreach ($data['dentals_journal'] as $key => $dental) 
		{
			$data['dentals_journal'][$key]->attachments 	= $this->dental->getAttachment($dental->id);
		}

		debug_in_page_source($data['claims_user']);
		$header = array('rptTitle' => 'Claim submission');
		$this->load->view('hr/report/header.php', $header);
		// $this->load->view('hr/claim/page/claimdetail/3.php');
		$this->load->view('hr/report/claim/report-submission_v2.php',$data);
		$this->load->view('hr/report/footer.php');
	}
	
	/**
	 * TODO:
	 * 1. Create claim sheet as closed as possible with manual claims.
	 */
	// function sheet($year,$month,$user_id,$claim_id)
	// {
	// 	$header = array();
	// 	$header['title'] = 'Claim Sheets';
	// 	$data = array
	// 	(
	// 		'user'					=> $this->model_user->getUsers($user_id),
	// 		'month'					=> $month,
	// 		'year'					=> $year,
	// 		'outpatients'			=> $this->outpatient->fetchOutpatient($user_id,$claim_id,$year,$month),
	// 		'hospitalizations'		=> $this->hospitalization->fetchHospitalization($user_id,$claim_id,$year,$month),
	// 		'dentals'				=> $this->dental->fetchDental($user_id,$claim_id,$year,$month), 
	// 		'mileage'				=> $this->travel->fetchTravelClaim($user_id,$claim_id,$year,$month), //this data actually a mileage data
	// 		'accomodation'			=> $this->accomodation->fetchAccomodation($claim_id),
	// 		'subsistence'			=> $this->subsistence->fetchSubsistence($claim_id),
	// 		'transportation'		=> $this->transportation->fetchTransportation($claim_id),
	// 	);
	// 	// die(debug($data['transportation']));
	// 	$this->load->view('hr/report/header.php', $header);
	// 	$this->load->view('hr/report/claim/monthly-claim-sheet.php',$data);
	// 	$this->load->view('hr/report/footer.php');
	// }

	/**
	 * FIXME:
	 * please confirm where this function have been used
	 */
	function adminPaidClaim()
	{
		$referer 		= $_SERVER['HTTP_REFERER'];
		$claim_id 		= $this->input->post('claim_id');
		$paid_amount 	= $this->input->post('amount');

		$data = array
		(
			'status'		=> 1,
			'paid_amount'	=> $paid_amount,
		);

		echo json_encode($data);
		$this->model_claim->editClaimMonth();
	}

	function claimPaid()
	{
		$referer 		= $_SERVER['HTTP_REFERER'];
		$input 			= $this->input->post();

		$data = array
		(
			'status'		=> 1,
			'paid_amount'	=> $input['amount_paid'],
		);
		$this->model_claim->editClaimMonth($data,$input['claim_id']);
		redirect($referer);
	}

	function traveling($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'page_setup' 		=>	$this->template->pageSetup('HR', 'home', 'Traveling Claim Menu'),
			'year'				=> $year,
			'month'				=> $month,
			'user'				=> $user_id,
			'claim_id'			=> $claim_id
		);
		$this->template->view('hr/claim/page/traveling/type',$data);
	}

	function addTravellingClaim($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'role' 					=> 	$this->logged_module['role'],
			'item'					=> 	$this->model_general->fetchAll('_ref__claim_type_detail',array('*'),array('claim_type_id' => 8)),
			'staff'					=> 	$this->model_user->getUsers(),
			'zones'					=>  $this->model_general->fetchAll('hr__ref_claim_travelling_zone',array('*')),
			'clients'				=> 	$this->model_crm->getCustomer(),
			'vehicles'				=> 	$this->model_general->fetchAll('hr__ref_claim_travelling_vehicle',array('*')),
			'Operation'				=> 	'Add New',
			'page_setup' 			=>	$this->template->pageSetup('HR', 'home', 'Claim'),
			'year'					=> 	$year,
			'month'					=> 	$month,
			'user'					=> 	$user_id,
			'claim_id'				=> 	$claim_id,
			'mgs_job'				=>	$this->job_v2->get_user_mgs_job($user_id),
		);
		$this->template->view('hr/claim/add_claim_travelling_v2', $data);
	}

	function editTravellingClaim()
	{
		$data = array(
			'role'				=> $this->logged_module['role'],
			'item' 				=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8)),
			'staff'				=> $this->model_user->getUsers(),
			'clients'			=> $this->model_crm->getCustomer(),
			'Operation'  		=> "Edit",
			'page_setup' 		=> $this->template->pageSetup('HR', 'home', 'Claim'),
		);

		$this->template->view('hr/claim/add_claim_travelling', $data);
	}

	function addOutpatientClaim($year,$month,$user_id,$claim_id)
	{

		$is_previous_claimable 		= true;
		$is_previous_2_claimable 	= true;

		$current_year_allocation	= $this->allocation->get_allocation_for_year($year, $user_id);
		$prev_year_allocation		= $this->allocation->get_allocation_for_year($year-1, $user_id);

		$current_year_claimed_amount= $this->outpatient->get_claim_amount(null, $year, $user_id);
		$prev_year_claimed_amount 	= $this->outpatient->get_claim_amount(null, $year-1, $user_id);

		//approved 
		$current_year_approved 	= $this->outpatient->get_approved_amount($year,$user_id);
		$prev_year_approved		= $this->outpatient->get_approved_amount($year-1,$user_id);

		//pending
		$current_year_pending 	= $this->outpatient->get_pending_amount($year,$user_id);
		$prev_year_pending 		= $this->outpatient->get_pending_amount($year-1,$user_id);

		if(!$year || !$month || !$user_id || !$claim_id || ($user_id != $_SESSION['user']['id']) || !$claim_id)
		{
			redirect(base_url('/hr/claim'));
		}

		$submission = array
		(
			'year'			=> $year,
			'month'			=> $month,
			'month_full'	=> date('F',mktime(0,0,0,$month,10)),
		);

		if($month == 1) //month january
		{
			$first_year 		= $year-1;
			$second_year 		= $year-1;

			$outpatient_amount_2 	= 	$this->outpatient->get_claim_amount(11,$year-1,$user_id); //11
			$outpatient_amount	 	= 	$this->outpatient->get_claim_amount(12,$year-1,$user_id); //12

			$last_month_allocation_balance = $this->outpatient->get_balance_allocation_for_the_year($user_id,$year-1);
			$last_2_month_allocation_balance = $last_month_allocation_balance;

			$first_prorate 		= (!empty($prev_year_allocation))?$prev_year_allocation[0]->outpatient:0.00;
			$second_prorate 	= (!empty($prev_year_allocation))?$prev_year_allocation[0]->outpatient:0.00;

			$first_balanced 	= $first_prorate - $prev_year_claimed_amount['balance'];
			$second_balanced 	= $second_prorate - $prev_year_claimed_amount['balance'];

			$first_approved 	= $prev_year_approved;
			$second_approved 	= $prev_year_approved;

			$first_pending 		= $prev_year_pending;
			$second_pending 	= $prev_year_pending;

		}elseif ($month == 2) { //month februrary
			$first_year 		= $year-1;
			$second_year 		= $year;

			$outpatient_amount_2 	= 	$this->outpatient->get_claim_amount(12,$year-1,$user_id); //12
			$outpatient_amount 		= 	$this->outpatient->get_claim_amount(1,$year,$user_id); //1

			$last_month_allocation_balance = $this->outpatient->get_balance_allocation_for_the_year($user_id,$year);
			$last_2_month_allocation_balance = $this->outpatient->get_balance_allocation_for_the_year($user_id,$year-1);

			$first_prorate 		= (!empty($prev_year_allocation))?$prev_year_allocation[0]->outpatient:0.00;
			$second_prorate 	= (!empty($current_year_allocation))?$current_year_allocation[0]->outpatient:0.00;

			$first_balanced 	= $first_prorate - $prev_year_claimed_amount['balance'];
			$second_balanced 	= $second_prorate - $current_year_claimed_amount['balance'];

			$first_approved 	= $prev_year_approved;
			$second_approved 	= $current_year_approved;

			$first_pending 		= $prev_year_pending;
			$second_pending 	= $current_year_pending;

		}else{
			$first_year 		= $year;
			$second_year 		= $year;

			$outpatient_amount_2 	= 	$this->outpatient->get_claim_amount($month-2,$year,$user_id); //-2
			$outpatient_amount 		= 	$this->outpatient->get_claim_amount($month-1,$year,$user_id); //-1

			$last_month_allocation_balance = $this->outpatient->get_balance_allocation_for_the_year($user_id,$year);
			$last_2_month_allocation_balance = $last_month_allocation_balance;

			$first_prorate 		= (!empty($current_year_allocation))?$current_year_allocation[0]->outpatient:0.00;
			$second_prorate 	= (!empty($current_year_allocation))?$current_year_allocation[0]->outpatient:0.00;
		
			$first_balanced 	= $first_prorate - $current_year_claimed_amount['balance'];
			$second_balanced 	= $second_prorate - $current_year_claimed_amount['balance'];

			$first_approved 	= $current_year_approved;
			$second_approved 	= $current_year_approved;

			$first_pending 		= $current_year_pending;
			$second_pending 	= $current_year_pending;
		}
        
		if($last_month_allocation_balance 	<= 0)$is_previous_claimable 		= false;
		if($last_2_month_allocation_balance <= 0)$is_previous_2_claimable 		= false;
		
		$data = array
		(
			'month'								=> $month,
			'role'								=> $this->logged_module['role'],
			'staff'								=> $this->model_user->getUsers(),
			'clients'							=> $this->model_crm->getCustomer(),
			'claims' 							=> $this->outpatient->fetchOutpatient($user_id,$claim_id,$year,$month),
			'families'							=> $this->family->fetchFamilyInfo($user_id,false),
			'Operation'  						=> "Add New",
			'approved_claims' 					=> null,
			'draft_claims'						=> null,	
			'page_setup' 						=> $this->template->pageSetup('HR', 'home', 'Claim'),
			'user'								=> $_SESSION['user'],
			'submission'						=> $submission,
			'is_previous_claimable'				=> $is_previous_claimable,
			'is_previous_2_claimable'			=> $is_previous_2_claimable,
			// 'previous_month'					=> $outpatient_amount['month'],
			// 'previous_2_month'					=> $outpatient_amount_2['month'],
			// 'previous_month_prorate'			=> $outpatient_amount['prorate_amount'],
			// 'previous_2_month_prorate'			=> $outpatient_amount_2['prorate_amount'],
			'previous_approved'					=> $outpatient_amount['approved_amount'],
			'previous_approved_2'				=> $outpatient_amount_2['approved_amount'],
			'year_1'							=> $outpatient_amount['year'],
			'year_2'							=> $outpatient_amount_2['year'],
			'previous_pending'					=> $outpatient_amount['pending_amount'],
			'previous_pending_2'				=> $outpatient_amount_2['pending_amount'],
			// 'month_1'							=> $outpatient_amount['month'],
			// 'month_2'							=> $outpatient_amount_2['month'],
			'previous_balanced'					=> $outpatient_amount['balance'],
			'previous_balanced_2'				=> $outpatient_amount_2['balance'],
			'last_month_allocation_balance' 	=> $last_month_allocation_balance,
			'last_2_month_allocation_balance'	=> $last_2_month_allocation_balance,

			'first_col_year'		=> $first_year,
			'second_col_year'		=> $second_year,
			'first_col_prorate'		=> $first_prorate,
			'second_col_prorate'	=> $second_prorate,
			'first_col_balanced'	=> $first_balanced,
			'second_col_balanced'	=> $second_balanced,
			'first_col_approved'	=> $first_approved,
			'second_col_approved'	=> $second_approved,
			'first_col_pending'		=> $first_pending,
			'second_col_pending'	=> $second_pending,
		);

		$data['claim_per_year'] 		= $this->outpatient->fetchOutpatient($user_id,null,$year,null);
		$data['month_claim']			= $this->outpatientClaim($data['claim_per_year']);
		$data['year_claim'] 			= $this->outpatientClaim($data['claims']);

		// $allocation_year_one_array  	= (!empty($allocation = $this->allocation->get_allocation_for_year($outpatient_amount['year'], $user_id)))?$allocation[0]->prorate:null;
		// $allocation_year_two_array 		= (!empty($allocation_2 = $this->allocation->get_allocation_for_year($outpatient_amount_2['year'], $user_id)))?$allocation_2[0]->prorate:null;

		//$this->template->view('hr/claim/outpatient_claim', $data); 

		$this->template->view('hr/claim/outpatient_claim_no_prorate', $data);
	}

	function editOutpatientClaim()
	{
		$data = array(
			'role'				=> $this->logged_module['role'],
			'item' 				=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8)),
			'staff'				=> $this->model_user->getUsers(),
			'clients'			=> $this->model_crm->getCustomer(),
			'Operation'  		=> "Edit",
			'page_setup' 		=> $this->template->pageSetup('HR', 'home', 'Claim'),
		);
		
		$this->template->view('hr/claim/outpatient_claim', $data);
	}

	function addHospitalizationClaim($year,$month,$user_id,$claim_id)
	{

		$current_year_allocation	= $this->allocation->get_allocation_for_year($year, $user_id);
		$prev_year_allocation		= $this->allocation->get_allocation_for_year($year-1, $user_id);
		$current_year_claimed_amount= $this->hospitalization->get_claimed_amount($year,$user_id);
		$prev_year_claimed_amount 	= $this->hospitalization->get_claimed_amount($year-1,$user_id);

		//approved 
		$current_year_approved 	= $this->hospitalization->get_amount_approved($year,$user_id);
		$prev_year_approved		= $this->hospitalization->get_amount_approved($year-1,$user_id);

		//pending
		$current_year_pending 	= $this->hospitalization->get_amount_pending($year,$user_id);
		$prev_year_pending 		= $this->hospitalization->get_amount_pending($year-1,$user_id);

		if($month == 1){ 
			$first_year 		= $year-1;
			$second_year 		= $year-1;

			$first_prorate 		= (!empty($prev_year_allocation))?$prev_year_allocation[0]->hospitalization:0.00;
			$second_prorate 	= (!empty($prev_year_allocation))?$prev_year_allocation[0]->hospitalization:0.00;

			$first_balanced 	= $first_prorate - $prev_year_claimed_amount;
			$second_balanced 	= $second_prorate - $prev_year_claimed_amount;

			$first_approved 	= $prev_year_approved;
			$second_approved 	= $prev_year_approved;

			$first_pending 		= $prev_year_pending;
			$second_pending 	= $prev_year_pending;

		}elseif ($month == 2){ 
			$first_year 		= $year-1;
			$second_year 		= $year;

			$first_prorate 		= (!empty($prev_year_allocation))?$prev_year_allocation[0]->hospitalization:0.00;
			$second_prorate 	= (!empty($current_year_allocation))?$current_year_allocation[0]->hospitalization:0.00;

			$first_balanced 	= $first_prorate - $prev_year_claimed_amount;
			$second_balanced 	= $second_prorate - $current_year_claimed_amount;

			$first_approved 	= $prev_year_approved;
			$second_approved 	= $current_year_approved;

			$first_pending 		= $prev_year_pending;
			$second_pending 	= $current_year_pending;
		}else{
			$first_year 		= $year;
			$second_year 		= $year;
		
			$first_prorate 		= (!empty($current_year_allocation))?$current_year_allocation[0]->hospitalization:0.00;
			$second_prorate 	= (!empty($current_year_allocation))?$current_year_allocation[0]->hospitalization:0.00;

			$first_balanced 	= $first_prorate - $current_year_claimed_amount;
			$second_balanced 	= $second_prorate - $current_year_claimed_amount;

			$first_approved 	= $current_year_approved;
			$second_approved 	= $current_year_approved;

			$first_pending 		= $current_year_pending;
			$second_pending 	= $current_year_pending;

		}	

		

		if(!$year || !$month || !$user_id || !$claim_id || ($user_id != $_SESSION['user']['id']) || !$claim_id)
		{
			redirect(base_url('/hr/claim'));
		}
	
		$data = array
		(
			'role' 					=> $this->logged_module['role'],
			'item' 					=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8)),
			'staff'					=> $this->model_user->getUsers(),
			'clients'				=> $this->model_crm->getCustomer(),
			'families'				=> $this->family->fetchFamilyInfo($user_id),
			'Operation'  			=> "Add New",
			'allocation'			=> null,
			'approved'				=> null,
			'draft'					=> null,
			'allowed'				=> '',
			'page_setup' 			=> $this->template->pageSetup('HR', 'home', 'Claim'),
			'year'					=> $year,
			'month'					=> $month,
			'user'					=> $_SESSION['user'],
			'rooms'					=> $this->ref_claim->getRefClaimType(3),
			'panels'				=> $this->model_crm->getCustomerDetail(array('a.type_id'=> 9)),
			'first_col_year'		=> $first_year,
			'second_col_year'		=> $second_year,
			'first_col_prorate'		=> $first_prorate,
			'second_col_prorate'	=> $second_prorate,
			'first_col_balanced'	=> $first_balanced,
			'second_col_balanced'	=> $second_balanced,
			
			'first_col_approved'	=> $first_approved,
			'second_col_approved'	=> $second_approved,
			'first_col_pending'		=> $first_pending,
			'second_col_pending'	=> $second_pending,
		);

		$this->template->view('hr/claim/hospitalization_claim', $data);
	}

	function editHospitalizationClaim()
	{
		$data = array(
			'role'				=> $this->logged_module['role'],
			'item' 				=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8)),
			'staff'				=> $this->model_user->getUsers(),
			'clients'			=> $this->model_crm->getCustomer(),
			'Operation'  		=> "Edit",
			'page_setup' 		=> $this->template->pageSetup('HR', 'home', 'Claim'),
		);
		
		$this->template->view('hr/claim/hospitalization_claim', $data);
	}

	function addDentalOptical($year,$month,$user_id,$claim_id)
	{
		if(!$year || !$month || !$user_id || !$claim_id || ($user_id != $_SESSION['user']['id']) || !$claim_id)
		{
			redirect(base_url('/hr/claim'));
		}

		$is_previous_claimable 		= true;
		$is_previous_2_claimable 	= true;

		// die(debug($current_year_allocation));
		$current_year_allocation	= $this->allocation->get_allocation_for_year($year, $user_id);
		$prev_year_allocation		= $this->allocation->get_allocation_for_year($year-1, $user_id);
		$current_year_claimed_amount= $this->dental->get_claimed_amount($year,$user_id);
		$prev_year_claimed_amount 	= $this->dental->get_claimed_amount($year-1,$user_id);

		//approved 
		$current_year_approved 	= $this->dental->get_amount_approved($year,$user_id);
		$prev_year_approved		= $this->dental->get_amount_approved($year-1,$user_id);

		//pending
		$current_year_pending 	= $this->dental->get_amount_pending($year,$user_id);
		$prev_year_pending 		= $this->dental->get_amount_pending($year-1,$user_id);

		if($month == 1)
		{//submission january
			$dental_2_amount 	= $this->dental->get_dental_amount(11,$year-1,$user_id); //bulan 11 year -1
			$dental_amount 		= $this->dental->get_dental_amount(12,$year-1,$user_id); //bulan 12 year -1 

			$last_month_allocation_balance = $this->dental->get_balance_allocation_for_the_year($user_id,$year-1);
			$last_2_month_allocation_balance = $last_month_allocation_balance;

			$first_year 		= $year-1;
			$second_year 		= $year-1;

			$first_prorate 		= (!empty($prev_year_allocation))?$prev_year_allocation[0]->dental_optical:0.00;
			$second_prorate 	= (!empty($prev_year_allocation))?$prev_year_allocation[0]->dental_optical:0.00;

			$first_balanced 	= $first_prorate - $prev_year_claimed_amount;
			$second_balanced 	= $second_prorate - $prev_year_claimed_amount;

			$first_approved 	= $prev_year_approved;
			$second_approved 	= $prev_year_approved;

			$first_pending 		= $prev_year_pending;
			$second_pending 	= $prev_year_pending;

		}elseif($month == 2){

			$dental_2_amount 	= $this->dental->get_dental_amount(12,$year-1,$user_id); //bulan 12 year - 1
			$dental_amount 		= $this->dental->get_dental_amount(1,$year,$user_id); //bulan 1 year; 

			$last_month_allocation_balance = $this->outpatient->get_balance_allocation_for_the_year($user_id,$year);
			$last_2_month_allocation_balance = $this->outpatient->get_balance_allocation_for_the_year($user_id,$year-1);

			$first_year 		= $year-1;
			$second_year 		= $year;

			$first_prorate 		= (!empty($prev_year_allocation))?$prev_year_allocation[0]->dental_optical:0.00;
			$second_prorate 	= (!empty($current_year_allocation))?$current_year_allocation[0]->dental_optical:0.00;

			$first_balanced 	= $first_prorate - $prev_year_claimed_amount;
			$second_balanced 	= $second_prorate - $current_year_claimed_amount;

			$first_approved 	= $prev_year_approved;
			$second_approved 	= $current_year_approved;

			$first_pending 		= $prev_year_pending;
			$second_pending 	= $current_year_pending;

		}else{

			$dental_2_amount 	= $this->dental->get_dental_amount($month-2,$year,$user_id); //month - 2 year;
			$dental_amount 		= $this->dental->get_dental_amount($month-1,$year,$user_id); //month -1 year; 

			$last_month_allocation_balance = $this->dental->get_balance_allocation_for_the_year($user_id,$year);
			$last_2_month_allocation_balance = $last_month_allocation_balance;

			$first_year 		= $year;
			$second_year 		= $year;

			$first_prorate 		= (!empty($current_year_allocation))?$current_year_allocation[0]->dental_optical:0.00;
			$second_prorate 	= (!empty($current_year_allocation))?$current_year_allocation[0]->dental_optical:0.00;

			$first_balanced 	= $first_prorate - $current_year_claimed_amount;
			$second_balanced 	= $second_prorate - $current_year_claimed_amount;

			$first_approved 	= $current_year_approved;
			$second_approved 	= $current_year_approved;

			$first_pending 		= $current_year_pending;
			$second_pending 	= $current_year_pending;
		}

		if($last_month_allocation_balance 	<= 0)$is_previous_claimable 		= false;
		if($last_2_month_allocation_balance <= 0)$is_previous_2_claimable 		= false;

		$data = array
		(
			'role' 					=> $this->logged_module['role'],
			'item' 					=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8)),
			'staff'					=> $this->model_user->getUsers(),
			'clients'				=> $this->model_crm->getCustomer(),
			'Operation'  			=> "Add New",
			'page_setup' 			=> $this->template->pageSetup('HR', 'home', 'Claim'),
			'prev_allocation'	 	=> (!empty($dental_amount['prorate_amount']))?$dental_amount['prorate_amount']:0,
			'prev_2_allocation'		=> (!empty($dental_2_amount['prorate_amount']))?$dental_2_amount['prorate_amount']:0,
			'prev_month'			=> (!empty($dental_amount['month']))?$dental_amount['month']:0,
			'prev_2_month'			=> (!empty($dental_2_amount['month']))?$dental_2_amount['month']:0,
			'approved_last_year'	=> $this->dental->get_approve_amount(date('Y')-1,$user_id),
			'approved'				=> $this->dental->get_approve_amount(date('Y'),$user_id),
			'pending_last_year'		=> $this->dental->get_pending_amount(date('Y')-1,$user_id),
			'pending'				=> $this->dental->get_pending_amount(date('Y'),$user_id),
			'prev_balanced'			=> (!empty($dental_amount['balance']))?$dental_amount['balance']:0,
			'prev_2_balanced'		=> (!empty($dental_2_amount['balance']))?$dental_2_amount['balance']:0,
			'year_month'			=> date('F Y',strtotime('01-'.$dental_amount['month'].'-'.$dental_amount['year'])),
			'year_2_month'			=> date('F Y',strtotime('01-'.$dental_2_amount['month'].'-'.$dental_2_amount['year'])),
			'year'					=> $year,
			'month'					=> $month,
			'is_prev_claimable'		=> $is_previous_claimable,
			'is_prev_2_claimable'	=> $is_previous_2_claimable,
			'last_month_allocation_balanced' => $last_month_allocation_balance,
			'last_2_month_allocation_balanced' => $last_2_month_allocation_balance,
			// 'panels'							=> $this->model_crm->getCustomerDetail(array('a.type_id'=> 9)),
			'first_col_year'		=> $first_year,
			'second_col_year'		=> $second_year,
			'first_col_prorate'		=> $first_prorate,
			'second_col_prorate'	=> $second_prorate,
			'first_col_balanced'	=> $first_balanced,
			'second_col_balanced'	=> $second_balanced,
			'first_col_approved'	=> $first_approved,
			'second_col_approved'	=> $second_approved,
			'first_col_pending'		=> $first_pending,
			'second_col_pending'	=> $second_pending,
		);

		$this->template->view('hr/claim/dental_optical_claim_no_prorate', $data);
		// $this->template->view('hr/claim/dental_optical_claim', $data); 
	}

	function editDentalOptical()
	{
		$data = array(
			'role'				=> $this->logged_module['role'],
			'item' 				=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8)),
			'staff'				=> $this->model_user->getUsers(),
			'clients'			=> $this->model_crm->getCustomer(),
			'Operation'  		=> "Edit",
			'page_setup' 		=> $this->template->pageSetup('HR', 'home', 'Claim'),
		);
		
		$this->template->view('hr/claim/dental_optical_claim', $data);
	}

	function addMeal($year,$month,$user_id,$claim_id)
	{
		$data = array(
			'role'				=> $this->logged_module['role'],
			'item'				=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8)),
			'staff'				=> $this->model_user->getUsers(),
			'clients'			=> $this->model_crm->getCustomer(),
			'Operation'  		=> "Add",
			'page_setup'		=> $this->template->pageSetup('HR', 'home', 'Claim'),
			'year'				=> $year,
			'month'				=> $month,
			'mgs_job'			=>	$this->job_v2->get_user_mgs_job($user_id),
		);
		
		$this->template->view('hr/claim/meal_claim_v2', $data);
	}

	/* 
		Changes made by Ariff 29/03/2021
		+ $type = '';
		+ 'Operation'  		=> ($type)?'Add New '.ucwords($type):"Add New Others Claim";
		+ 'type'				=> $type

	*/
	function addOthers($year,$month,$user_id,$claim_id,$type = '')
	{
		$data = array(
			'role' 				=> $this->logged_module['role'],
			'item' 				=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8)),
			'staff'				=> $this->model_user->getUsers(),
			'clients'			=> $this->model_crm->getCustomer(),
			'Operation'  		=> ($type)?'Add New '.ucwords($type):"Add New Others Claim",
			'page_setup' 		=> $this->template->pageSetup('HR', 'home', 'Claim'),
			'year'				=> $year,
			'month'				=> $month,
			'type'				=> $type,
			'mgs_job'			=>	$this->job_v2->get_user_mgs_job($user_id),
		);

		$this->template->view('hr/claim/others_claim_v2', $data);
	}

	function editOthers()
	{
		$data = array(
			'role'				=> $this->logged_module['role'],
			'item' 				=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8)),
			'staff'				=> $this->model_user->getUsers(),
			'clients'			=> $this->model_crm->getCustomer(),
			'Operation'  		=> "Edit",
			'page_setup' 		=> $this->template->pageSetup('HR', 'home', 'Claim'),
		);

		$this->template->view('hr/claim/others_claim', $data);
	}

	function peakSeason()
	{
		$data = array('page_setup' => $this->template->pageSetup('HR','home','Peak Season Allowance'));
		$this->template->view('hr/claim/page/peak_season/claim',$data);
	}

	function actingAllowances()
	{
		$data = array('page_setup' => $this->template->pageSetup('HR','home','Acting Allowance'));
		$this->template->view('hr/claim/page/acting_allowance/claim',$data);
	}

	function taxiFare($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'			=> $year,
			'month'			=> $month,
			'user_id'		=> $user_id,
			'claim_id'		=>  $claim_id,
			'token'			=> $this->session->userdata('token'),
			'page_setup' 	=> $this->template->pageSetup('HR','home','Taxi Fare')
		);
		$this->template->view('hr/claim/page/taxi_fare/claim',$data);
	}
	
	function petrol($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'			=> $year,
			'month'			=> $month,
			'user_id'		=> $user_id,
			'claim_id'		=> $claim_id,
			'token'			=> $this->session->userdata('token'), 				//token ini banyak masalah dan cara implementation nya salah
			'page_setup' 	=> $this->template->pageSetup('HR','home','Petrol'),
			'mgs_job'		=>	$this->job_v2->get_user_mgs_job($user_id),
		);

		$this->template->view('hr/claim/page/petrol/petrol_v2',$data);
	}

	function add_petrol()
	{
		$this->load->model('model_claim_petrol','petrol');
		
		$attachments 	 = $this->input->post('attachment');
		$staff_movements = $this->input->post('staff_movement');
		$amount 		 = $this->input->post('amount');
		$date_from 		 = $this->input->post('date_from');
		$date_to		 = $this->input->post('date_to'); 

		$input = array
		(
			'claim_id' 			=> $this->input->post('claim_id'),
			'job_id'			=> $this->input->post('job_id'),
			'date_from' 		=> date('Y-m-d',strtotime($this->input->post('date_from'))),
			'date_to'			=> date('Y-m-d',strtotime($this->input->post('date_to'))),
			'amount'        	=> $this->input->post('amount'),
			'amount_approved'	=> 0,
			'is_admin_approve'	=> 0,
			'is_hod_approve'	=> 0,
			'hod_remarks'		=> '',
			'admin_remarks'		=> '',
			'is_delete'			=> 0
		);

		$claim_petrol_id = $this->petrol->create($input);

		if(!empty($claim_petrol_id))
		{
			$movements = json_decode($staff_movements);
			$movements_input = array();
			foreach($movements as $key => $move)
			{
				$staff_movement_temp = array
				(
					'claim_petrol_id'	=> $claim_petrol_id,
					'movement_id'		=> $move->group_id,
					'is_delete'			=> 0,
				); 

				array_push($movements_input,$staff_movement_temp);
			}
			$this->petrol->create_movements($movements_input);

			$attachment_array = json_decode($attachments);
			$attachment_input = array();
			foreach($attachment_array as $key => $attachment)
			{
				$attachment_temp = array
				(
					'claim_petrol_id' 	=> $claim_petrol_id,
					'attachment_name'	=> $attachment->orig_name,
					'file_type'			=> $attachment->file_type,
					'file_ext'			=> str_replace(',','',$attachment->file_ext),
					'description'		=> $attachment->description,
					'location'			=> 'application/storage/claim/traveling/petrol/'.$attachment->file_name,
					'unique_id'			=> $attachment->raw_name,
					'type'				=> 0,
					'is_delete'			=> 0,
					'created_at'		=> date('Y-m-d H:i:s'),
					'deleted_at'		=> '0000-00-00',
				);
				array_push($attachment_input,$attachment_temp);
			}

			// die(debug($attachment_input));
			$this->petrol->create_attachments($attachment_input);
		}
		echo json_encode(array('status' => 'ok'));
	}

	function entertainment($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'			=> $year,
			'month'			=> $month,
			'user_id'		=> $user_id,
			'claim_id'		=> $claim_id,
			'page_setup' 	=> $this->template->pageSetup('HR','home','Entertainment'), 
			'mgs_job'		=>	$this->job_v2->get_user_mgs_job($user_id),
		);
		$this->template->view('hr/claim/page/entertainment/entertainment_v2',$data);
	}

	public function add_entertainment()
	{
		$this->load->model('model_claim_entertainment','entertainment');
		$attachments = json_decode($this->input->post('attachments'));
		// die(debug($attachments));

		$data = array
		(
			'claim_id' 			=> $this->input->post('claim_id'),
			'job_id'			=> $this->input->post('job_id'),
			'amount'			=> $this->input->post('amount'),
			'amount_approved'	=> 0,
			'description'		=> $this->input->post('description'),
			'year'				=> $this->input->post('year'),
			'month'				=> $this->input->post('month'),
			'user_id'			=> $this->input->post('user_id'),
			// 'type'				=> $this->input->post('type'),
			'is_approve'		=> 0,
			'is_hod_approve'	=> 0,
			'hod_remarks'		=> '',
			'admin_remarks'		=> '',
			'is_delete'			=> 0,
			'delete_by'			=> 0
		);
		$claim_entertainment_id = $this->entertainment->create($data);
		if(!empty($claim_entertainment_id) && !empty($attachments))
		{
			foreach ($attachments as $key => $attachment) 
			{
				$attachment_temp = array
				(
					'claim_entertainment_id'	=> $claim_entertainment_id,
					'attachment_name'			=> $attachment->orig_name,
					'file_type'					=> $attachment->file_type,
					'file_ext'					=> $attachment->file_ext,
					'description'				=> $attachment->description,
					'location'					=> 'application/storage/claim/entertainment/'.$attachment->file_name,
					'unique_id'					=> $attachment->raw_name,
					'type'						=> 0,
					'is_delete'					=> 0,
				);
				$this->entertainment->create_attachments($attachment_temp);
			}
		}

		echo json_encode(array('status' => 'ok'));

	}

	function handphoneAllowance()
	{
		$data = array('page_setup' => $this->template->pageSetup('HR','home','Handphone Allowances'));
		$this->template->view('hr/claim/page/handphone_allowance/claim',$data);
	}
	
	function staffEmergencyLoan()
	{
		$data = array('page_setup' => $this->template->pageSetup('HR','home','Staff Emergency Loan'));
		$this->template->view('hr/claim/page/staff_emergency_loan/claim',$data);
	}
	
	function entertainmentAllowance()
	{
		$data = array('page_setup' => $this->template->pageSetup('HR','home','Entertainment Allowance'));
		$this->template->view('hr/claim/page/entertainment_allowance/claim',$data);
	}

	function trainerFacilitator($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'				=> $year,
			'month'				=> $month,
			'user_id'			=> $user_id,
			'claim_id'			=> $claim_id,
			'token'				=> $this->session->userdata('token'),
			'page_setup' 		=> $this->template->pageSetup('HR','home','Trainer / Facilitator'),
			'mgs_job'			=> $this->job_v2->get_user_mgs_job($user_id),
		);
		$this->template->view('hr/claim/page/trainer_facilitator/claim_v2',$data);
	}

	function firmEventBenefit($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'				=> $year,
			'month'				=> $month,
			'user_id'			=> $user_id,
			'claim_id'			=> $claim_id,
			'page_setup'	 	=> $this->template->pageSetup('HR','home','Firm Event Benefit')
		);
		$this->template->view('hr/claim/page/firm_event/claim',$data);
	}

	function professionalAffiliation()
	{
		$data = array('page_setup' => $this->template->pageSetup('HR','home','Professional Affiliation / Membership Fee'));
		$this->template->view('hr/claim/page/professional_affiliation/claim',$data);
	}

	function travelingPurchase($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'				=> $year,
			'month'				=> $month,
			'user_id'			=> $user_id,
			'claim_id'			=> $claim_id,
			'token'				=> $this->session->userdata('token'),
			'page_setup' 		=> $this->template->pageSetup('HR','home','Purchase While Travelling')
		);
		$this->template->view('hr/claim/page/travel_purchase/claim',$data);
	}

	function outstationAdvance()
	{
		$data = array('page_setup' => $this->template->pageSetup('HR','home','Advances For Outstation / Overseas Travel'));
		$this->template->view('hr/claim/page/travel_purchase/claim',$data);
	}

	function travelingTransportation($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'				=> $year,
			'month'				=> $month,
			'user_id'			=> $user_id,
			'claim_id'			=> $claim_id,
			'token'				=> $this->session->userdata('token'),
			'vehicles'			=> $this->model_general->fetchAll('hr__ref_claim_travelling_vehicle',array('*')), //fetch only flight,public transport and car rental
			'page_setup' 		=> $this->template->pageSetup('HR','home','Transportation'),
			'mgs_job'			=> $this->job_v2->get_user_mgs_job($user_id),
		);

		$this->template->view('hr/claim/page/travel_transportation/claim_v2',$data);
	}

	function subsistanceAllowance($year,$month,$user_id,$claim_id)
	{
		$this->load->model('hr/model_usd_to_myr','usd_to_myr');
		$user =$this->model_general->fetchAll('user__employment_detail',array('*') , array('user_id' => $user_id))[0];
		
		
		$usd_myr = $this->usd_to_myr->getTodayRate();

		$zone = $this->zone->fetchZoneByType(13);
		$local_zone = [];
		$international_zone = [];
		foreach($zone as $key => $value)
		{
			$param = unserialize($value->param);
			$zone[$key]->param_array = $param;

			if($param['travel_type_id'] == 0)
			{
				array_push($local_zone,$zone[$key]);
			}else{
				array_push($international_zone,$zone[$key]);
			}

		}

		$data = array
		(
			'year'							=> $year,
			'month'							=> $month,
			'user_id'						=> $user_id,
			'claim_id'						=> $claim_id,
			'token'							=> $this->session->userdata('token'),
			'local_zone'					=> $local_zone,
			'international_zone'			=> $international_zone,
			'page_setup' 					=> $this->template->pageSetup('HR','home','Subsistance Allowance'),
			'emp_grade'						=> 0,
			'usd_to_myr'					=> $usd_myr,
			'employee_grade'				=> $user['employee_grade'],
			'grade_higher_than_seventeen'	=> ($user['employee_grade'] >= 17)?true:false,	
			'divide' 						=> ($this->logged_user['position_id'] == 51)?2:1, //trainee = 51
			'mgs_job'						=>	$this->job_v2->get_user_mgs_job($user_id),
		);
		
		// die(debug($data));
		$this->template->view('hr/claim/page/subsistance_allowance/claim_v2',$data);
	}
	
	function travelingCall($year,$month,$user_id,$claim_id)
	{
		$customer = $this->model_crm->getCustomer();

		$data = array
		(
			'year'				=>	$year,
			'month'				=>	$month,
			'user_id'			=> 	$user_id,
			'claim_id'			=> 	$claim_id,
			'token'				=> 	$this->session->userdata('token'),
			'customers'			=> 	$customer,
			'page_setup' 		=> 	$this->template->pageSetup('HR','home','Business and Personal Call')
		);

		$this->template->view('hr/claim/page/traveling_call/claim',$data);
	}

	function accomodation($year,$month,$user_id,$claim_id)
	{
		$accomodation_entitlement = $this->travel->fetchAccomodationEntitlement($user_id);

		$data = array
		(
			'user'						=> $this->model_user->getUsers($user_id),
			'year'						=> $year,
			'month'						=> $month,
			'user_id'					=> $user_id,
			'accomodation_entitlements'	=> $accomodation_entitlement,
			'claim_id'					=> $claim_id,
			'token'						=> $this->session->userdata('token'),
			'page_setup' 				=> $this->template->pageSetup('HR','home','Accomodation'),
			'mgs_job'					=>	$this->job_v2->get_user_mgs_job($user_id),
		);
		
		$this->template->view('hr/claim/page/accomodation/claim_v2',$data);
	}

	function incidentalExpenses($expense,$year,$month,$user_id,$claim_id)
	{
		switch ($expense) 
		{
			case '0':
			case 'parking_charges':
					$this->parking_charges($year,$month,$user_id,$claim_id);	
				break;
			case '1':
			case 'toll_charges':
					$this->toll_charges($year,$month,$user_id,$claim_id);
				break;
			
			case '2':
			case 'airport_taxes':
					$this->airport_taxes($year,$month,$user_id,$claim_id);
				break;

			case '3':
			case 'service_taxes':
					$this->service_taxes($year,$month,$user_id,$claim_id);
				break;
			
			case '4':
			case 'tips_and_portage':
					$this->tips_portage($year,$month,$user_id,$claim_id);
				break;
			
			case '5':
			case 'laundry_expenses':
					$this->laundry($year,$month,$user_id,$claim_id);
				break;
			
			case '6':
			case 'excess_baggage':
					$this->excess_baggage($year,$month,$user_id,$claim_id);
				break;
			
			case '7':
			case 'loss_in_foreign_exchange':
					$this->loss_forex($year,$month,$user_id,$claim_id);
				break;

			case '8':
			case 'taxi_fare':
				$this->taxiFare($year,$month,$user_id,$claim_id);
				break;

			default:
				redirect(base_url('/hr/claim/myclaimlist'));
				break;
		}
	}

	function illness()
	{
		$data = array('page_setup' => $this->template->pageSetup('HR','home','Illness'));
		$this->template->view('hr/claim/page/illness/claim',$data);
	}

	function businessTripReport()
	{
		$data = array('page_setup' => $this->template->pageSetup('HR','home','Business Trip Report'));
		$this->template->view('hr/claim/page/business_trip_report/claim',$data);
	}

	function panelClinic()
	{
		$data = array(
			'role' 				=> $this->logged_module['role'],
			'item' 				=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8)),
			'staff'				=> $this->model_user->getUsers(),
			'panels'			=> $this->model_crm->getCustomerDetail(array('a.type_id'=> 9)),
			'page_setup' 		=> $this->template->pageSetup('HR', 'home', 'Claim'),
		);

		$this->template->view('hr/claim/panel_clinic', $data);
	}

	function panelClinicClaim()
	{
		$data['role'] 		= $this->logged_module['role'];
		$data['page_setup'] = $this->template->pageSetup('HR', 'home', 'Claim');
		$data['staff']		= $this->model_user->getUsers();
		$data['panels']		= $this->model_crm->getCustomerDetail(array('a.type_id'=> 9));
		$data['claims']		= $this->panel->fetchClaim(array('a.is_delete'=> 0));
		$data['month']		= $this->model_crm->getMonth();
		$data['item'] 		= $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8));

		$this->template->view('hr/claim/panel_clinic_claim', $data);
	}

	function addPanelClinic()
	{
		$input = $this->input->post();
		list($month,$year) = explode('-',$input['date_inovice']);

		$data = array(
			'panel_id' 		=> (!empty($input['clinic_name']))?$input['clinic_name']:null,
			'invoice_chit' 	=> (!empty($input['inovice_chit']))?$input['inovice_chit']:null,
			'invoice_month' => $month,
			'invoice_year' 	=> $year,
			'status'		=> 0,
			'is_delete'		=> 0,
		);

		$claim_id = $this->panel->createClaim($data);

		//upload claim invoice
		$upload_result = $this->uploadToStorage('./application/storage/panel_clinic/','files');
	
		if(!empty($upload_result['status'][0]['error']))
		{
			//faoruq 
			//set error message
		}else{
			//set successful message
			//insert into 
			$attachment = array
			(
				
				'claim_panel_id' 	=> $claim_id,
				'attachment_name' 	=> $upload_result['file_name'],
				'file_type' 		=> $upload_result['file_type'],
				'file_ext' 			=> $upload_result['file_ext'],
				'description' 		=> 'panel clinic claim',
				'location' 			=> 'application/storage/panel_clinic/'.$upload_result['file_name'],
				'unique_id' 		=> uniqid(), 
				'type' 				=> str_replace('.','', $upload_result['file_ext']),
				'is_delete' 		=> 0 
			);	
			$attaachment_id = $this->panel->createAttachment($attachment);
		}

		redirect(base_url('hr/claim/panelClinicClaim/'));
	}

	function panel_attachment($attachment_id)
	{
	}

	function editPanelClaimDetail()
	{
		$input = $this->input->post();
		$data = array(
			'panel_claim_id' 	=> $input['panel_claim_id'],
			'date'				=> date('Y-m-d',strtotime($input['date'])),
			'claim_type_id'		=> $input['claim_type'],
			'staff_id'			=> $input['employee_id'],
			'employee_name'		=> $input['employee_name'],
			'patient_name'		=> $input['patient_name'],
			'relation'			=> ($input['relation'])?$input['relation']:null,
			'employee_ic_no'	=> $input['employee_ic'],
			'patient_ic_no'		=> $input['patient_ic_no'],
			'treatment'			=> $input['treatment'],
			'amount'			=> $input['amount'],
			'is_delete'			=> 0,  
		);

		$id = $this->panel->editClaimDetail($data,$input['detail_id']);
		redirect(base_url('/hr/claim/panelClaimDetail/'.$data['panel_claim_id']));
	}

	function panelClaimDetail($id)
	{
		if(empty($id)){
			redirect(base_url('hr/claim/panelClinicClaim/'));
		}

		$data['role'] 			= $this->logged_module['role'];
		$data['page_setup']		= $this->template->pageSetup('HR', 'home', 'Claim');
		$data['staff']			= $this->model_user->getUsers();
		$data['clients']		= $this->model_crm->getCustomer();
		$data['item'] 			= $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8));
		$data['claim_types']	= $this->panel->fetchClaimTypeMedical();
		$data['relations']		= $this->general_model->model_general->fetchAll('_ref__relationship',array('*'));
		$data['claim_details']	= $this->panel->fetchClaimDetail(array('is_delete' => 0,'panel_claim_id' => $id));
		array_splice($data['claim_types'],2,1); //remove array['claim_types][2] = room package(array)
	
		$this->template->view('hr/claim/panel_claim_detail', $data);
	}

	function addPanelClaimDetail()
	{
		$input = $this->input->post();
		$data = array
		(
			'panel_claim_id' 	=> $input['panel_claim_id'],
			'date'				=> date('Y-m-d',strtotime($input['date'])),
			'claim_type_id'		=> $input['claim_type'],
			'staff_id'			=> $input['employee_id'],
			'employee_name'		=> $input['employee_name'],
			'patient_name'		=> $input['patient_name'],
			'relation'			=> ($input['relation'])?$input['relation']:0,
			'employee_ic_no'	=> $input['employee_ic'],
			'patient_ic_no'		=> $input['patient_ic'],
			'treatment'			=> $input['treatment'],
			'amount'			=> $input['amount'],
			'is_delete'			=> 0,  
		);

		$panel = $this->panel->fetchClaim(array('a.id' => $data['panel_claim_id']));
		$month = $panel[0]->invoice_month;
		$year = $panel[0]->invoice_year;

		if($month != 11 && $month != 12)
		{	
			$submission_month = $month+1;
			$submission_year = $year;
		}elseif($month == 11){
			$submission_month = $month+1;
			$submission_year = $year;
		}elseif($month == 12){
			$submission_month = 1;
			$submission_year = $year+1;
		}

		//check dah ada claim ker tak, kalau takde create satu claim supaya staff tak pening
		//1. check ada submission tak bulan tu...kalau takde create satu
		$is_claim_created = $this->model_claim->is_claim_created($data['staff_id'],$submission_month,$submission_year);
		if(!$is_claim_created)
		{
			//created hr__claim
			$hr_claim_data = array
			(
				'user_id'		=> $data['staff_id'],
				'year'			=> $submission_year,
				'month'			=> $submission_month,
				'status' 		=> 0,
				'is_submit' 	=> 0,
				'is_delete' 	=> 0, 
				'paid_amount' 	=> 0,
			);
			$this->model_claim->insertNewClaimMonth($hr_claim_data);
		}

		$id = $this->panel->createClaimDetail($data);
		if(!empty($id))
		{
			//2. buat adjustment untuk claim outpatient / dental kalau 
			if($data['claim_type_id'] == 1)
			{
				$this->_outpatientAdjustment($data['staff_id'],$submission_year);
			}elseif($data['claim_type_id'] == 4)
			{
				$this->_dental_optical_adjustment($data['staff_id'],$submission_year);
			}
		}
		
		redirect(base_url('/hr/claim/panelClaimDetail/'.$data['panel_claim_id']));
	}

	function medicalClaimHistory() 
	{
		$data['role'] 		= $this->logged_module['role'];
		$data['page_setup'] = $this->template->pageSetup('HR', 'home', 'Claim');
		$data['staff']		= $this->model_user->getUsers();
		$data['clients']	= $this->model_crm->getCustomer();
		$data['item'] 		= $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8));

		$this->template->view('hr/claim/medical_claim_history', $data);
	}

	/**
	 * Apa yang kau pikirkan ni farouq..source code macam harem
	 */
	function addAttachment($mode)
	{
		switch ($mode) {
			case 0:
				$folder = 'outpatient';
				break;
			case 1:
				$folder = 'hospitalization';
				break;
			case 2:
				$folder = 'dental';
				break;
			case 3:
				$folder = 'medical_screening';
				break;
			case 4:
				$folder = 'mileage';
				break;
			case 5:
				$folder = 'others';
				break;
			case 6:
				$folder = 'meal';
				break;
			case 7:
				$folder = 'traveling/mileage';
				break;
			case 711:
				$folder = 'traveling/petrol';
				break;
			case 71:
				$folder = 'traveling/accomodation';
				break;
			case 712:
				$folder = 'traveling/accomodation';
				break;
			case 72:
				$folder ='traveling/transportation';
				break;
			case 73:
				$folder = 'traveling/purchase';
				break;
			case 74:
				$folder = 'traveling/calls';
				break;
			case 75:
				$folder = 'traveling/parking_charges';
				break;
			case 76:
				$folder = 'traveling/toll_charges';
				break;
			case 77:
				$folder = 'traveling/airport_taxes';
				break;
			case 78:
				$folder = 'traveling/service_taxes';
				break;
			case 79:
				$folder = 'traveling/tips_portage';
				break;
			case 80:
				$folder = 'traveling/laundry';
				break;
			case 81:
				$folder = 'traveling/excess_baggage';
				break;
			case 82:
				$folder = 'traveling/loss_forex';
				break;
			case 83:
				$folder = 'trainer';
				break;
			case 84:
				$folder = 'firm_event';
				break;
			case 9:
				$folder = 'entertainment';
				break;
			case 90:
				$folder = 'dressing';
				break;
			case 91:
				$folder = 'gadget';
				break;
			default:
				$folder = 'claims';
				break;
		}
		$data 					= $this->uploadToStorage('./application/storage/claim/'.$folder.'/','files');
		$data['description']	= $this->input->post('description');
		echo json_encode($data);
		return true;
	}

	function openAttachment($unique_id,$mode = null)
	{
		if($mode == 'OUTPATIENT')
		{
			$attachment = $this->outpatient->fetchAttachmentByUniqueId($unique_id);
		}

		if($mode == 'HOSPITALIZATION')
		{
			$attachment = $this->hospitalization->fetchAttachmentByUniqueid($unique_id);
		}

		if($mode == 'DENTAL')
		{
			$attachment = $this->dental->fetchAttachmentbyUniqueid($unique_id);
		}

		if($mode == 'MILEAGE')
		{
			$attachment = $this->travel->fetchAttachmentbyUniqueid($unique_id);
		}

		if($mode == 'ACCOMODATION')
		{
			$attachment = $this->accomodation->fetchAttachmentAccomodation($unique_id);
		}	

		if($mode == 'TRANSPORTATION')
		{
			$attachment = $this->transportation->fetchAttachmentbyUniqueid($unique_id);
		}

		if($mode == 'PARKING')
		{
			$attachment = $this->parking->fetchAttachmentParking($unique_id);
		}

		if($mode == 'TOLL')
		{
			$attachment = $this->toll->fetchAttachmentbyUniqueid($unique_id);
		}

		if($mode == 'TRAINER')
		{
			$attachment = $this->trainer->fetchAttachmentbyUniqueid($unique_id);
		}

		if($mode == 'OTHERS')
		{
			$attachment = $this->other->getAttachmentByUniqueid($unique_id);
		}

		if($mode == 'PANEL_CLINIC')
		{
			$attachment = $this->panel->getAttachmentByUniqueid($unique_id);
		}

        if($mode == 'ENTERTAINMENT')
        {
    		$this->load->model('model_claim_entertainment','entertainment');

            $attachment = $this->entertainment->getAttachmentByUniqueid($unique_id);
        }

        if($mode == 'PETROL')
        {
    		$this->load->model('model_claim_petrol','petrol');
            $attachment = $this->petrol->fetchAttachmentbyUniqueid($unique_id);
        }

        if($mode == 'DRESSING')
		{
			$attachment = $this->dressing->fetchAttachmentbyUniqueid($unique_id);
		}

		if($mode == 'GADGET')
		{
			$attachment = $this->gadget->fetchAttachmentbyUniqueid($unique_id);
		}

		if(!empty($attachment))
		{
			$this->load->library('fileaccess');
			$file_extension = $attachment[0]->file_type;
			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 '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;
			}
		}


	}

	public function total_claim_by_business_entities()
	{
		$this->load->model('Model_claim_report','report');
		$business_entities = array();						

		if((!empty($this->input->post('month'))) && (!empty($this->input->post('year'))))
		{
			$reports = $this->report->get_claim($this->input->post('month'),$this->input->post('year'));
			foreach($reports as $key => $report)
			{
				if(!empty($business_entities)){
					foreach ($business_entities as $inner_key => $business_entity) 
					{
						if($business_entity['business_entity_id'] == $report['business_entity_id'])
						{
							array_push($business_entities[$inner_key]['claims'],$report);
						}else{
							if($inner_key+1 == sizeof($business_entities))
							{
								$temp = array
								(
									'business_entity_id' 	=> $report['business_entity_id'],
									'business_entity_name'	=> $report['business_entity_name'],
									'claims'				=> array(
										$report
									)
								);
								array_push($business_entities,$temp);
							}
						}
					}
				}else{
					$temp = array
					(
						'business_entity_id' 	=> $report['business_entity_id'],
						'business_entity_name'	=> $report['business_entity_name'],
						'claims'				=> array(
							$report
						)
					);
					array_push($business_entities,$temp);
				}
			}
		}

		$data = array
		(
			'month'				=> (!empty($this->input->post('month')))?$this->input->post('month'):'',
			'year'				=> (!empty($this->input->post('year')))?$this->input->post('year'):'',
			'reports'			=> $business_entities,
			'submisson_month'	=> ((!empty($this->input->post('month'))) && (!empty($this->input->post('year'))))?date('F/Y',strtotime('01-'.$this->input->post('month').'-'.$this->input->post('year'))):'',
			'page_setup' 		=> $this->template->pageSetup('HR','home','Total Claim')
		);
		$this->template->view('hr/report/claim_finance_report/total_claim_by_business_entities',$data);
	}

	public function claim_summary_by_business_entities()
	{
		$this->load->model('Model_claim_report','report');
		$data = array
		(
			'business_entities_id'	=> '',
			'month'					=> '',
			'year'					=> '',
			'page_setup'			=> $this->template->pageSetup('HR','home','Claim Summary By Business Entities'),
			'business_entities'		=> $this->model_company->getBusinesses()
		);

		if(!empty($this->input->post()))
		{
			$data['reports'] = $this->report->get_business_entity_summary($this->input->post('business_entity_id'),$this->input->post('month'),$this->input->post('year'));
			foreach ($data['business_entities'] as $key => $business_entity) 
			{
				if($business_entity['id'] == $this->input->post('business_entity_id'))
				{
					$data['submission_business_entity'] = $business_entity['name'];
				}	
			}
			$data['submission_month'] 		= date('F Y',strtotime('01-'.$this->input->post('month').'-'.$this->input->post('year'))); 
			$data['business_entities_id'] 	= $this->input->post('business_entity_id');
			$data['month']					= $this->input->post('month');
			$data['year'] 					= $this->input->post('year'); 

			$not_in = array();
			if(!empty($data['reports']))
			{
				foreach($data['reports'] as $key => $report)
				{
					array_push($not_in,$report['user_id']);
				}
			}
			// debug($data['reports']);
			$data['otlist'] = $this->report->get_user_ot_by_business_entity_id($this->input->post('month'),$this->input->post('year'),$this->input->post('business_entity_id'),$not_in);
		}

		$this->template->view('hr/report/claim_finance_report/claim_summary_by_business_entities',$data);
	}

	public function report_summary_by_business_entities($business_entity_id = null, $month = null, $year = null)
	{
		$this->load->model('Model_claim_report','report');
		$data = array
		(
			'reports'				=> array(),
			'otlist'				=> array(),
			'business_entities_id'	=> '',
			'month'					=> '',
			'year'					=> '',
			'business_entities'		=> $this->model_company->getBusinesses()
		);

		if(!empty($business_entity_id) && !empty($month) && !empty($year))
		{
			$data['reports'] = $this->report->get_business_entity_summary($business_entity_id,$month,$year);
			foreach ($data['business_entities'] as $key => $business_entity) 
			{
				if($business_entity['id'] == $business_entity_id)
				{
					$data['submission_business_entity'] = $business_entity['name'];
				}	
			}
			$data['submission_month'] = date('F Y',strtotime('01-'.$month.'-'.$year)); 
			$data['business_entities_id'] = $business_entity_id;
			$data['month']	= $month;
			$data['year'] = $year; 

			$not_in = array();
			if(!empty($data['reports']))
			{
				foreach($data['reports'] as $key => $report)
				{
					array_push($not_in,$report['user_id']);
				}
			}
			
			$data['otlist'] = $this->report->get_user_ot_by_business_entity_id($month,$year,$business_entity_id,$not_in);
		}

		$header = array('rptTitle' => 'Report claim summary by business entities');
		$this->load->view('hr/report/header.php', $header);
		$this->load->view('hr/report/claim_finance_report/report_claim_summary_by_business_entities',$data);
		$this->load->view('hr/report/footer.php');
	}

	public function claim_summary_by_departments()
	{
		$this->load->model('Model_claim_report','report');
		$data = array
		(
			'department_id'	=> '',
			'month'			=> '',
			'year'			=> '',
			'page_setup' 	=> $this->template->pageSetup('HR','home','Claim Summary By Department'),
			'departments'	=> $this->model_company->getDepartments(),
		);
		
		if(!empty($this->input->post()))
		{
			$data['reports'] = $this->report->get_department_summary($this->input->post('department'),$this->input->post('month'),$this->input->post('year'));
			foreach ($data['departments'] as $key => $department) 
			{
				if($department['id'] == $this->input->post('department'))
				{
					$data['submission_department'] = $department['name'].' '.$department['branch_name'];
				}
			}
			$data['submission_month'] = date('F Y',strtotime('01-'.$this->input->post('month').'-'.$this->input->post('year'))); 
			$data['department_id'] = $this->input->post('department');
			$data['month']	= $this->input->post('month');
			$data['year'] = $this->input->post('year'); 

			$not_in = array();
			if(!empty($data['reports']))
			{
				foreach($data['reports'] as $key => $report)
				{
					array_push($not_in,$report['user_id']);
				}
			}
			//var_dump($data['reports']);
			$data['otlist'] = $this->report->get_user_ot_by_department_id($this->input->post('month'),$this->input->post('year'),$this->input->post('department'),$not_in);
			//var_dump($data['otlist']);
		}

		$this->template->view('hr/report/claim_finance_report/claim_summary_by_department',$data);
	}

	public function total_claim_by_type()
	{
		$this->load->model('Model_claim_report','report');

		$data = array
		(
			'department_id'		=> (!empty($this->input->post('department')))?$this->input->post('department'):'',
			'month'				=> (!empty($this->input->post('month')))?$this->input->post('month'):'',
			'year'				=> (!empty($this->input->post('year')))?$this->input->post('year'):'',
			'results'			=> (!empty($this->input->post('month')) && !empty($this->input->post('year')))?$this->report->get_claim_type_total($this->input->post('month'),$this->input->post('year')):null,
			'submission_month'	=> (!empty($this->input->post('month')) && !empty($this->input->post('year')))?date('F Y',strtotime('01-'.$this->input->post('month').'-'.$this->input->post('year'))):'',
			'page_setup' 		=> $this->template->pageSetup('HR','home','Claim ')
		);
		$this->template->view('hr/report/claim_finance_report/total_claim_by_type',$data);
	}

	public function report_total_by_business_entities($month = null, $year = null)
	{
		$this->load->model('Model_claim_report','report');
		$business_entities = array();						

		if((!empty($month)) && (!empty($year)))
		{
			$reports = $this->report->get_claim($month,$year);
			foreach($reports as $key => $report)
			{
				if(!empty($business_entities)){
					foreach ($business_entities as $inner_key => $business_entity) 
					{
						if($business_entity['business_entity_id'] == $report['business_entity_id'])
						{
							array_push($business_entities[$inner_key]['claims'],$report);
						}else{
							if($inner_key+1 == sizeof($business_entities))
							{
								$temp = array
								(
									'business_entity_id' 	=> $report['business_entity_id'],
									'business_entity_name'	=> $report['business_entity_name'],
									'claims'				=> array(
										$report
									)
								);
								array_push($business_entities,$temp);
							}
						}
					}
				}else{
					$temp = array
					(
						'business_entity_id' 	=> $report['business_entity_id'],
						'business_entity_name'	=> $report['business_entity_name'],
						'claims'				=> array(
							$report
						)
					);
					array_push($business_entities,$temp);
				}
			}
		}

		$data = array
		(
			'month'				=> (!empty($month))?$month:'',
			'year'				=> (!empty($year))?$year:'',
			'reports'			=> $business_entities,
			'submisson_month'	=> ((!empty($month)) && (!empty($year)))?date('F/Y',strtotime('01-'.$month.'-'.$year)):'',
			'page_setup' 		=> $this->template->pageSetup('HR','home','Total Claim')
		);

		$header = array('rptTitle' => 'Report Total Claim by Business Entities');
		$this->load->view('hr/report/header.php', $header);
		$this->load->view('hr/report/claim_finance_report/report_total_claim_by_business_entities',$data);
		$this->load->view('hr/report/footer.php');
	}

	public function report_total_claim_by_type($month = null, $year = null)
	{
		$this->load->model('Model_claim_report','report');

		$data = array
		(
			// 'department_id'		=> (!empty($this->input->post('department')))?$this->input->post('department'):'',
			'month'				=> (!empty($month))?$month:'',
			'year'				=> (!empty($year))?$year:'',
			'results'			=> (!empty($month) && !empty($year))?$this->report->get_claim_type_total($month,$year):null,
			'submission_month'	=> (!empty($month) && !empty($year))?date('F Y',strtotime('01-'.$month.'-'.$year)):'',
			'page_setup' 		=> $this->template->pageSetup('HR','home','Claim ')
		);

		$header = array('rptTitle' => 'Report Total Claim by type');
		$this->load->view('hr/report/header.php', $header);
		$this->load->view('hr/report/claim_finance_report/report_total_claim_by_type',$data);
		$this->load->view('hr/report/footer.php');
	}

	public function report_claim_summary_by_departments($department_id = null, $month = null, $year = null)
	{

		$this->load->model('Model_claim_report','report');
		$data = array
		(
			'reports'		=> array(),
			'otlist'		=> array(),
			'department_id'	=> '',
			'month'			=> '',
			'year'			=> '',
			'page_setup' 	=> $this->template->pageSetup('HR','home','Claim Summary'),
			'departments'	=> $this->model_company->getDepartments(),
		);
		
		if(!empty($department_id) && !empty($month) && !empty($year))
		{
			$data['reports'] = $this->report->get_department_summary($department_id,$month,$year);
			foreach ($data['departments'] as $key => $department) 
			{
				if($department['id'] == $department_id)
				{
					$data['submission_department'] = $department['name'].' '.$department['branch_name'];
				}
			}
			$data['submission_month'] = date('F Y',strtotime('01-'.$month.'-'.$year)); 
			$data['department_id'] = $department_id;
			$data['month']	= $month;
			$data['year'] = $year; 

			$not_in = array();
			if(!empty($data['reports']))
			{
				foreach($data['reports'] as $key => $report)
				{
					array_push($not_in,$report['user_id']);
				}
			}
			
			$data['otlist'] = ($otlist = $this->report->get_user_ot_by_department_id($month,$year,$department_id,$not_in))?$otlist:array();
		}

		$header = array('rptTitle' => 'Report claim summary by departments');
		$this->load->view('hr/report/header.php', $header);
		$this->load->view('hr/report/claim_finance_report/report_claim_summary_by_departments',$data);
		$this->load->view('hr/report/footer.php');
	}





	//end: reporting for finance


	/**
	 * start : incidental expenses
	 */
	private function parking_charges($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'			=> $year,
			'month'			=> $month,
			'user_id'		=> $user_id,
			'claim_id'		=> $claim_id,
			'token'			=> $this->session->userdata('token'),
			'page_setup' 	=> $this->template->pageSetup('HR','home','Parking Charges'),
			'mgs_job'		=>	$this->job_v2->get_user_mgs_job($user_id),
		);
		$this->template->view('hr/claim/page/parking_charges/claim_v2',$data);
	}

	private function toll_charges($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'				=> $year,
			'month'				=> $month,
			'user_id'			=> $user_id,
			'claim_id'			=> $claim_id,
			'token'				=> $this->session->userdata('token'),
			'page_setup' 		=> $this->template->pageSetup('HR','home','Toll Charges'),
			'mgs_job'			=> $this->job_v2->get_user_mgs_job($user_id),
		);
		$this->template->view('hr/claim/page/toll_charges/claim_v2',$data);
	}

	private function airport_taxes($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'			=> $year,
			'month'			=> $month,
			'user_id'		=> $user_id,
			'claim_id'		=> $claim_id,
			'token'			=> $this->session->userdata('token'),
			'page_setup' 	=> $this->template->pageSetup('HR','home','Airport Taxes')
		);
		$this->template->view('hr/claim/page/airport_taxes/claim',$data);
	}

	private function service_taxes($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'			=> $year,
			'month'			=> $month,
			'user_id'		=> $user_id,
			'claim_id'		=> $claim_id,
			'token'			=> $this->session->userdata('token'),
			'page_setup' 	=> $this->template->pageSetup('HR','home','Service Taxes')
		);
		$this->template->view('hr/claim/page/service_taxes/claim',$data);
	}

	private function tips_portage($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'				=> $year,
			'month'				=> $month,
			'user_id'			=> $user_id,
			'claim_id'			=> $claim_id,
			'token'				=> $this->session->userdata('token'),
			'page_setup' 		=> $this->template->pageSetup('HR','home','Tips and Portage')
		);
		$this->template->view('hr/claim/page/tips_portage/claim',$data);
	}

	private function laundry($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'				=> $year,
			'month'				=> $month,
			'user_id'			=> $user_id,
			'claim_id'			=> $claim_id,
			'token'				=> $this->session->userdata('token'),
			'page_setup' 		=> $this->template->pageSetup('HR','home','Laundry Expenses')
		);
		$this->template->view('hr/claim/page/laundry_expense/claim',$data);
	}

	private function excess_baggage($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'				=> $year,
			'month'				=> $month,
			'user_id'			=> $user_id,
			'claim_id'			=> $claim_id,
			'token'				=> $this->session->userdata('token'),
			'page_setup' 		=> $this->template->pageSetup('HR','home','Excess Baggage')
		);
		$this->template->view('hr/claim/page/excess_baggage/claim',$data);
	}

	private function loss_forex($year,$month,$user_id,$claim_id)
	{
		$data = array
		(
			'year'			=> $year,
			'month'			=> $month,
			'user_id'		=> $user_id,
			'claim_id'		=> $claim_id,
			'token'			=> $this->session->userdata('token'),
			'page_setup' 	=> $this->template->pageSetup('HR','home','Loss in Foreign Exchange')
		);
		$this->template->view('hr/claim/page/loss_forex/claim',$data);   
	}

	/**
	 * end : incidental expenses
	 */
	private function getPanelClinicClaim($year,$user_id)
	{
		//calculate the prorate for panel clinic claim for the year 
		$bool = $this->panel->fetchClinicDetailByYear($year,$user_id);
		return $bool;
	}
	
	/**
	 * version 2.0 :
	 * new version of allocation setup and table structure change
	 */
	private function claimDetail($year,$month,$user_id,$claim_id,$admin_approval,$view = null)
	{		
		$this->load->model('model_claim_petrol','petrol');
		$this->load->model('model_claim_entertainment','entertainment');

		$current_year_allocation	= $this->allocation->get_allocation_for_year($year, $user_id);
		$prev_year_allocation		= $this->allocation->get_allocation_for_year($year-1, $user_id);

		$current_year_claimed_amount 	= $this->dental->get_claimed_amount($year,$user_id);
		$prev_year_claimed_amount 		= $this->dental->get_claimed_amount($year-1,$user_id);

		$current_year_claimed_amount_dental_panel 	= $this->dental->get_panel_amount_no_prorate($year, $user_id);
		$prev_year_claimed_amount_dental_panel 		= $this->dental->get_panel_amount_no_prorate($year-1, $user_id);

		$current_year_claimed_amount_outpatient = $this->outpatient->get_claim_amount(null, $year, $user_id);
		$prev_year_claimed_amount_outpatient 	= $this->outpatient->get_claim_amount(null, $year-1, $user_id);

		$current_year_claimed_amount_hospitalization_panel 	= $this->hospitalization->get_panel_amount_no_prorate($year, $user_id);
		$prev_year_claimed_amount_hospitalization_panel 	= $this->hospitalization->get_panel_amount_no_prorate($year-1, $user_id);

		if($month == 1) //month january 
		{
			$outpatient_amount_second_month 	= $this->outpatient->get_claim_amount(11,$year-1,$user_id); //11
			$outpatient_amount_first_month	 	= $this->outpatient->get_claim_amount(12,$year-1,$user_id); //12

			$dental_amount_second_month			= $this->dental->get_dental_amount(11,$year-1,$user_id); //bulan 11 year -1
			$dental_amount_first_month		 	= $this->dental->get_dental_amount(12,$year-1,$user_id); //bulan 12 year -1 

			$allocation 						= $this->allocation->get_allocation_for_year($year-1, $user_id);
			$hospitalization_prorate_second 	= $allocation;
			$hospitalization_prorate_first 		= $allocation;

			$hospitalization_claimed_first 		= $this->hospitalization->get_claimed_amount($year-1,$user_id);
			$hospitalization_claimed_second 	= $this->hospitalization->get_claimed_amount($year,$user_id);

			/** senarai panel claim unutk kedua2 bulan */
			$panel_first_month 					= $this->panel->fetch_user_claim_by_invoice_date($user_id,12,$year-1);
			$panel_second_month 				= $this->panel->fetch_user_claim_by_invoice_date($user_id,11,$year-1);

			$view_claim_outpatient_1 			= $this->outpatient->fetch_view_claim_outpatient($user_id,12,$year-1);
			$view_claim_outpatient_2 			= $this->outpatient->fetch_view_claim_outpatient($user_id,11,$year-1);

			$first_prorate 						= (!empty($prev_year_allocation))?$prev_year_allocation[0]->dental_optical:0.00;
			$second_prorate 					= (!empty($prev_year_allocation))?$prev_year_allocation[0]->dental_optical:0.00;

			$first_balanced 					= $first_prorate - $prev_year_claimed_amount;
			$second_balanced 					= $second_prorate - $prev_year_claimed_amount;

			$first_prorate_outpatient 			= (!empty($prev_year_allocation))?$prev_year_allocation[0]->outpatient:0.00;
			$second_prorate_outpatient 			= (!empty($prev_year_allocation))?$prev_year_allocation[0]->outpatient:0.00;

			$first_balanced_outpatient 			= $first_prorate_outpatient - $prev_year_claimed_amount_outpatient['balance'];
			$second_balanced_outpatient 		= $second_prorate_outpatient - $prev_year_claimed_amount_outpatient['balance'];

			$first_dressing_prorate				= $this->dressing->get_balance_allocation_for_the_year_all($user_id,$year-1);
			$second_dressing_prorate			= $first_dressing_prorate;

			$first_gadget_prorate 	 			= $this->gadget->get_balance_allocation_for_the_year_all($user_id,$year-1);
			$second_gadget_prorate 				= $first_gadget_prorate;

		}elseif ($month == 2) { //month februrary
			$outpatient_amount_second_month 	= $this->outpatient->get_claim_amount(12,$year-1,$user_id); //12
			$outpatient_amount_first_month 		= $this->outpatient->get_claim_amount(1,$year,$user_id); //1

			$dental_amount_second_month 		= $this->dental->get_dental_amount(12,$year-1,$user_id); //bulan 12 year - 1
			$dental_amount_first_month    		= $this->dental->get_dental_amount(1,$year,$user_id); //bulan 1 year; 

			$hospitalization_prorate_second		= $this->allocation->get_allocation_for_year($year-1, $user_id);
			$hospitalization_prorate_first 		= $this->allocation->get_allocation_for_year($year, $user_id);

			$hospitalization_claimed_first 		= $this->hospitalization->get_claimed_amount($year,$user_id);
			$hospitalization_claimed_second		= $this->hospitalization->get_claimed_amount($year-1,$user_id);

			$panel_first_month 					= $this->panel->fetch_user_claim_by_invoice_date($user_id,1,$year);
			$panel_second_month 				= $this->panel->fetch_user_claim_by_invoice_date($user_id,12,$year-1);

			$view_claim_outpatient_1 			= $this->outpatient->fetch_view_claim_outpatient($user_id,1,$year);
			$view_claim_outpatient_2 			= $this->outpatient->fetch_view_claim_outpatient($user_id,12,$year-1);

			$first_prorate 						= (!empty($prev_year_allocation))?$prev_year_allocation[0]->dental_optical:0.00;
			$second_prorate 					= (!empty($current_year_allocation))?$current_year_allocation[0]->dental_optical:0.00;

			$first_balanced 					= $first_prorate - $prev_year_claimed_amount;
			$second_balanced 					= $second_prorate - $current_year_claimed_amount;

			$first_prorate_outpatient 			= (!empty($prev_year_allocation))?$prev_year_allocation[0]->outpatient:0.00;
			$second_prorate_outpatient 			= (!empty($current_year_allocation))?$current_year_allocation[0]->outpatient:0.00;

			$first_balanced_outpatient 			= $first_prorate_outpatient - $prev_year_claimed_amount_outpatient['balance'];
			$second_balanced_outpatient 		= $second_prorate_outpatient - $current_year_claimed_amount_outpatient['balance'];

			$first_dressing_prorate				= $this->dressing->get_balance_allocation_for_the_year_all($user_id,$year);
			$second_dressing_prorate			= $this->dressing->get_balance_allocation_for_the_year_all($user_id,$year-1);

			$first_gadget_prorate 	 			= $this->gadget->get_balance_allocation_for_the_year_all($user_id,$year);
			$second_gadget_prorate 				= $this->gadget->get_balance_allocation_for_the_year_all($user_id,$year-1);

		}else{
			$outpatient_amount_second_month 	= $this->outpatient->get_claim_amount($month-2,$year,$user_id); //-2
			$outpatient_amount_first_month 		= $this->outpatient->get_claim_amount($month-1,$year,$user_id); //-1

			$dental_amount_second_month  		= $this->dental->get_dental_amount($month-2,$year,$user_id); //month - 2 year;
			$dental_amount_first_month 		 	= $this->dental->get_dental_amount($month-1,$year,$user_id); //month -1 year; 

			$allocation 						= $this->allocation->get_allocation_for_year($year, $user_id);

			$hospitalization_prorate_second 	= $allocation;
			$hospitalization_prorate_first 		= $allocation;

			$hospitalization_claimed_first 		= $this->hospitalization->get_claimed_amount($year,$user_id);
			$hospitalization_claimed_second 	= $this->hospitalization->get_claimed_amount($year,$user_id);

			$panel_first_month 					= $this->panel->fetch_user_claim_by_invoice_date($user_id,$month-1,$year);
			$panel_second_month 				= $this->panel->fetch_user_claim_by_invoice_date($user_id,$month-2,$year);

			$view_claim_outpatient_1 			= $this->outpatient->fetch_view_claim_outpatient($user_id,$month-1,$year);
			$view_claim_outpatient_2 			= $this->outpatient->fetch_view_claim_outpatient($user_id,$month-2,$year);

			$first_prorate 						= (!empty($current_year_allocation))?$current_year_allocation[0]->dental_optical:0.00;
			$second_prorate 					= (!empty($current_year_allocation))?$current_year_allocation[0]->dental_optical:0.00;

			$first_balanced 					= $first_prorate - $current_year_claimed_amount;
			$second_balanced 					= $second_prorate - $current_year_claimed_amount;

			$first_prorate_outpatient 			= (!empty($current_year_allocation))?$current_year_allocation[0]->outpatient:0.00;
			$second_prorate_outpatient 			= (!empty($current_year_allocation))?$current_year_allocation[0]->outpatient:0.00;

			$first_balanced_outpatient 			= $first_prorate_outpatient - $current_year_claimed_amount_outpatient['balance'];
			$second_balanced_outpatient 		= $second_prorate_outpatient - $current_year_claimed_amount_outpatient['balance'];

			$first_dressing_prorate				= $this->dressing->get_balance_allocation_for_the_year_all($user_id,$year);
			$second_dressing_prorate			= $first_dressing_prorate;

			$first_gadget_prorate 	 			= $this->gadget->get_balance_allocation_for_the_year_all($user_id,$year);
			$second_gadget_prorate 				= $first_gadget_prorate;

		}	
		
		$day = date('d');
		$submission_claim = date('F Y',strtotime('01-'.$month.'-'.$year));

		if($day > 7 && $day <= 15)
		{
			$is_disabled = false;
		}else{
			if((date('m') == 12) && ($month == 1) && ($year - date('Y') == 1)) //current month is 12 and submission month is in january next year
			{
				$is_disabled = false;
			}else{
				// $is_disabled = false;
				if((date('m') > $month || date('Y') > $year) && ($month != 1))
				{
					$is_disabled = true; 
				}else{
					$is_disabled = false;
				}
			}
		}

		$data = array
		(
			'year'								=> $year,
			'month'								=> $month,
			'claims'							=> ($this->model_claim->getUserClaims($year,$month,$user_id))?$this->model_claim->getUserClaims($year,$month,$user_id)[0]:null,
			'staff' 							=> $this->model_user->getUsers(),
			'others'							=> $this->other->fetchOtherClaim($user_id,$claim_id,$year,$month),
			'clients'							=> $this->model_crm->getCustomer(),
			'dentals_journal'					=> $this->dental->fetchDentalJournal($user_id,$claim_id,$year,$month), 
			'dentals'							=> $this->dental->fetchDental($user_id,$claim_id,$year,$month), 
			'mileage'							=> $this->mileage->fetchMileage($user_id,$claim_id,$year,$month),
			'petrol'							=> $this->petrol->fetchPetrol($user_id,$claim_id,$year,$month),
			'entertainments'					=> $this->entertainment->fetch_entertainment($user_id,$claim_id,$year,$month),
			'travels'							=> $this->travel->fetchTravelClaim($user_id,$claim_id,$year,$month), //this data actually a mileage data
			'claimType'							=> $this->model_general->fetchAll('_ref__claim_type', array('*'), array('is_display' => 2),array(),array('sequence' => 'ASC')),
			'page_setup'						=> $this->template->pageSetup('HR', 'home', 'Claim Detail : '.$submission_claim),
			
			'outpatients'						=> $this->outpatient->fetchOutpatient($user_id,$claim_id,$year,$month),
			'outpatients_journal'				=> $this->outpatient->fetchOutpatientJournal($user_id,$claim_id,$year,$month),
			'hospitalizations'					=> $this->hospitalization->fetchHospitalization($user_id,$claim_id,$year,$month),
			'disabled'							=> $is_disabled,
			// 'disabled'							=> ($day > 7 && $day <= 15)?true:(date('m') > $month || date('Y') > $year)?true:false, //TODO: on this when live
		    //  'disabled'							=> false,
			'role'								=> $this->session->userdata('module_data')['role'],
			'claims_user'						=> $this->model_user->getUsers($user_id),
			'claim_id'							=> $claim_id,
			'accomodation'						=> $this->accomodation->fetchAccomodation($claim_id),
			'transportation'					=> $this->transportation->fetchTransportation($claim_id),
			'parking'							=> $this->parking->fetchParking($claim_id),
			'toll'								=> $this->toll->fetchToll($claim_id),
			'subsistence'						=> $this->subsistence->fetchSubsistence($claim_id),
			'trainers'							=> $this->trainer->fetchTrainer($claim_id),
			'meals'								=> $this->meal->fetchMeals($user_id,$claim_id,$year,$month),
			// 'panel_clinic'						=> $this->panel_claim->fetchClaimDetail(array('a.staff_id'=>$user_id)),
			'panel_clinic'						=> $this->panel_claim->fetch_claim_detail($user_id), //kenapa screen panel tak ambil dari sini???query ni untuk apa??
			'second_month'						=> $outpatient_amount_second_month['month'],
			'second_year'						=> $outpatient_amount_second_month['year'],
			// 'second_outpatient_balance'			=> $outpatient_amount_second_month['balance'],
			'first_month'						=> $outpatient_amount_first_month['month'],
			'first_year'						=> $outpatient_amount_first_month['year'],
			// 'first_outpatient_balance'			=> $outpatient_amount_first_month['balance'],

			'second_dental_balance'				=> $dental_amount_second_month['balance'],
			'first_dental_balance'				=> $dental_amount_first_month['balance'],

			'second_hospitalization_prorate'	=> (!empty($hospitalization_prorate_second))?$hospitalization_prorate_second[0]->hospitalization:0.00,
			'second_hospitalization_balance'	=> (!empty($hospitalization_prorate_second))?$hospitalization_prorate_second[0]->hospitalization - $hospitalization_claimed_second - $prev_year_claimed_amount_hospitalization_panel:0.00,
			'first_hospitalization_prorate'		=> (!empty($hospitalization_prorate_first))?$hospitalization_prorate_first[0]->hospitalization:0.00,
			'first_hospitalization_balance'		=> (!empty($hospitalization_prorate_first))?$hospitalization_prorate_first[0]->hospitalization - $hospitalization_claimed_first - $current_year_claimed_amount_hospitalization_panel:0.00,
			'panel_first_month'					=> $panel_first_month,
			'panel_second_month'				=> $panel_second_month,
			'view_claim_outpatient_1'			=> $view_claim_outpatient_1,
			'view_claim_outpatient_2'			=> $view_claim_outpatient_2,	

			'first_col_prorate'					=> $first_prorate,
			'second_col_prorate'				=> $second_prorate,	
			'first_col_balanced'				=> $first_balanced - $prev_year_claimed_amount_dental_panel,
			'second_col_balanced'				=> $second_balanced - $current_year_claimed_amount_dental_panel,

			'second_outpatient_prorate'			=> $second_prorate_outpatient,
			'second_outpatient_balance'			=> $second_balanced_outpatient,
			'first_outpatient_prorate'			=> $first_prorate_outpatient,
			'first_outpatient_balance'			=> $first_balanced_outpatient,

			'dressing'							=> $this->dressing->fetchDressing($claim_id),
			'second_dressing_prorate'			=> (!empty($second_dressing_prorate))?$second_dressing_prorate[0]->allocation:0.00,
			'second_dressing_balance'			=> (!empty($second_dressing_prorate))?$second_dressing_prorate[0]->balance:0.00,
			'first_dressing_prorate'			=> (!empty($first_dressing_prorate))?$first_dressing_prorate[0]->allocation:0.00,
			'first_dressing_balance'			=> (!empty($first_dressing_prorate))?$first_dressing_prorate[0]->balance:0.00,

			'gadget'							=> $this->gadget->fetchGadget($claim_id),
			'second_gadget_prorate'				=> (!empty($second_gadget_prorate))?$second_gadget_prorate[0]->allocation:0.00,
			'second_gadget_balance'				=> (!empty($second_gadget_prorate))?$second_gadget_prorate[0]->balance:0.00,
			'first_gadget_prorate'				=> (!empty($first_gadget_prorate))?$first_gadget_prorate[0]->allocation:0.00,
			'first_gadget_balance'				=> (!empty($first_gadget_prorate))?$first_gadget_prorate[0]->balance:0.00,
			'current_year_gadget'				=> $this->gadget->get_balance_allocation_for_the_year_all($user_id,$year)
		);

		/** 
		 * start: check if date are in the submission range
		*/
		$range_date_lower 	= date('d-m-Y',strtotime('15-'.$data['first_month'].'-'.$data['first_year']));
		$range_date_upper 	= date('d-m-Y',strtotime('07-'.$month.'-'.$year));
		if(strtotime(date('d-m-Y')) > strtotime($range_date_lower) && strtotime(date('d-m-Y')) <= strtotime($range_date_upper))
		{
			$data['is_in_submission_range'] = true;
		}else{
			$data['is_in_submission_range'] = false; //farouq
 		} 

		/** 
		 * end: check if date are in the submission range
		*/

		if($data['travels']) foreach ($data['travels'] as $key => $travel) 
		{
			$data['travels'][$key]->details 		= $this->travel->fetchTravelDetail($travel->id);
			$data['travels'][$key]->attachments 	= $this->travel->getAttachment($travel->id);
			$data['travels'][$key]->routes 			= $this->travel->getRoute($travel->id);
			$data['travels'][$key]->job 			= $this->job_v2->get_mgs_job($travel->job_id);
			$data['travels'][$key]->lead 			= $this->job_v2->is_job_team_leader($travel->job_id, $_SESSION['user']['id']);
			$data['travels'][$key]->user_id 		= $user_id;
		}

		if($data['petrol']) foreach ($data['petrol'] as $key => $petrol) 
		{
			$data['petrol'][$key]->job 		= $this->job_v2->get_mgs_job($petrol->job_id);
			$data['petrol'][$key]->lead 	= $this->job_v2->is_job_team_leader($petrol->job_id, $_SESSION['user']['id']);
			$data['petrol'][$key]->user_id = $user_id;
		}

		if($data['accomodation']) foreach ($data['accomodation'] as $key => $accomodation) 
		{
			$data['accomodation'][$key]->job 	= $this->job_v2->get_mgs_job($accomodation->job_id);
			$data['accomodation'][$key]->lead 	= $this->job_v2->is_job_team_leader($accomodation->job_id, $_SESSION['user']['id']);
			$data['accomodation'][$key]->user_id 	= $user_id;
		}

		if($data['meals']) foreach ($data['meals'] as $key => $meals) 
		{
			$data['meals'][$key]->job 		= $this->job_v2->get_mgs_job($meals->job_id);
			$data['meals'][$key]->lead 		= $this->job_v2->is_job_team_leader($meals->job_id, $_SESSION['user']['id']);
			$data['meals'][$key]->user_id = $user_id;
		}

		if($data['subsistence']) foreach ($data['subsistence'] as $key => $subsistence) 
		{
			$data['subsistence'][$key]->job 	= $this->job_v2->get_mgs_job($subsistence->job_id);
			$data['subsistence'][$key]->lead 	= $this->job_v2->is_job_team_leader($subsistence->job_id, $_SESSION['user']['id']);
			$data['subsistence'][$key]->user_id 	= $user_id;
		}

		if($data['transportation']) foreach ($data['transportation'] as $key => $transportation) 
		{
			$data['transportation'][$key]->job 		= $this->job_v2->get_mgs_job($transportation->job_id);
			$data['transportation'][$key]->lead 	= $this->job_v2->is_job_team_leader($transportation->job_id, $_SESSION['user']['id']);
			$data['transportation'][$key]->user_id 		= $user_id;
		}

		if($data['parking']) foreach ($data['parking'] as $key => $parking) 
		{
			$data['parking'][$key]->job 	= $this->job_v2->get_mgs_job($parking->job_id);
			$data['parking'][$key]->lead 	= $this->job_v2->is_job_team_leader($parking->job_id, $_SESSION['user']['id']);
			$data['parking'][$key]->user_id = $user_id;
		}

		if($data['toll']) foreach ($data['toll'] as $key => $toll) 
		{
			$data['toll'][$key]->job 		= $this->job_v2->get_mgs_job($toll->job_id);
			$data['toll'][$key]->lead 		= $this->job_v2->is_job_team_leader($toll->job_id, $_SESSION['user']['id']);
			$data['toll'][$key]->user_id = $user_id;
		}

		if($data['entertainments']) foreach ($data['entertainments'] as $key => $entertainments) 
		{
			$data['entertainments'][$key]->job 		= $this->job_v2->get_mgs_job($entertainments->job_id);
			$data['entertainments'][$key]->lead 	= $this->job_v2->is_job_team_leader($entertainments->job_id, $_SESSION['user']['id']);
			$data['entertainments'][$key]->user_id 		= $user_id;
		}

		if($data['trainers']) foreach ($data['trainers'] as $key => $trainers) 
		{
			$data['trainers'][$key]->job 	= $this->job_v2->get_mgs_job($trainers->job_id);
			$data['trainers'][$key]->lead 	= $this->job_v2->is_job_team_leader($trainers->job_id, $_SESSION['user']['id']);
			$data['trainers'][$key]->user_id = $user_id;
		}

		if($data['others']) foreach ($data['others'] as $key => $other) 
		{
			$data['others'][$key]->attachments 	= $this->other->getAttachments($other->id);
			$data['others'][$key]->job 			= $this->job_v2->get_mgs_job($other->job_id);
			$data['others'][$key]->lead 		= $this->job_v2->is_job_team_leader($other->job_id, $_SESSION['user']['id']);
			$data['others'][$key]->user_id 	= $user_id;
		}

		if ($data['outpatients']) foreach ($data['outpatients'] as $key => $outpatient) 
		{
			$data['outpatients'][$key]->attachments = $this->outpatient->fetchAttachment($outpatient->journal_id);
		}

		if ($data['outpatients_journal']) foreach ($data['outpatients_journal'] as $key => $outpatient) 
		{
			$data['outpatients_journal'][$key]->attachments = $this->outpatient->fetchAttachment($outpatient->id);
		}

		if($data['hospitalizations']) foreach ($data['hospitalizations'] as $key => $hosp) 
		{
			$data['hospitalizations'][$key]->attachments = $this->hospitalization->fetchAttachment($hosp->id);
		}

		if($data['dentals']) foreach ($data['dentals'] as $key => $dental) 
		{
			$data['dentals'][$key]->attachments = $this->dental->getAttachment($dental->journal_id);
		}
		
		if($data['dentals_journal']) foreach ($data['dentals_journal'] as $key => $dental) 
		{
			$data['dentals_journal'][$key]->attachments = $this->dental->getAttachment($dental->id);
		}

		if($data['dressing']) foreach ($data['dressing'] as $key => $dressing) 
		{
			$data['dressing'][$key]->attachments = $this->dressing->getAttachment($dressing->id);
		}

		if($data['gadget']) foreach ($data['gadget'] as $key => $gadget) 
		{
			$data['gadget'][$key]->attachments 	= $this->gadget->getAttachment($gadget->id);
		}

		$data['screen_mode'] = '';
		
		if(!empty($admin_approval))
		{
			if($admin_approval == 'approval-admin')
			{
				$data['screen_mode'] = 'admin';
			}

			if($admin_approval == 'approval-hod')
			{
				$data['screen_mode'] = 'hod';
			}

			if($admin_approval == 'approval-team-lead')
			{
				$data['screen_mode'] = 'em';
			}
		}

		if($data['screen_mode'] == 'admin' && $this->logged_module['role'] != 'admin')
		{
			redirect(base_url('hr/claim_v2/myClaimList'));
		}

		if($data['screen_mode'] == 'hod' && !$this->isManagerAndAbove($this->session->userdata('user')['id'])) 
		{
			redirect(base_url('hr/claim_v2/myClaimList'));
		}

		debug_in_page_source($data['panel_clinic']);
		$this->template->view('hr/claim/my_claim_detail_v2', $data);
	}

	private function currentAllocation($user_id)
	{
		$allocations 		= $this->allocation->fetchAllocation($user_id,null,null, 0, 0);
		if($allocations) foreach ($allocations as $key => $allocate) 
		{
			if((date('Y-m-d') >= $allocate->start_date) && (date('Y-m-d') <= $allocate->end_date))
			{
				return $allocate;
			}else{
				return null;
			}
		}else{
			return null;
		}
	}

	private function outpatientClaim($claims)
	{
		$data['pending_claim'] 		= 0;
		$data['approved_claim']		= 0;
		$data['rejected_claim']		= 0;

		if(!empty($claims)) foreach ($claims as $key => $claim) {
			if ($claim->is_approve == 0)$data['pending_claim']  += $claim->amount_claim;
			if ($claim->is_approve == 1)$data['approved_claim'] += $claim->amount_approved;
			if ($claim->is_approve == 2)$data['rejected_claim'] += $claim->amount_approved;
		}

		return $data;
	}

	private function uploadToStorage($path,$file_name)
	{
		$config['upload_path']          = $path;
		$config['allowed_types']        = 'gif|jpg|png|doc|docx|pdf|xlsx|jpeg';
		$config['encrypt_name'] 		= TRUE;

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

        $data = array();

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

        if (!$this->upload->do_upload($file_name))
        {
        	$data['status'] = false;
            $error = array('error' => $this->upload->display_errors());
            array_push($data, $error);
        }
        else
        {
        	$uploaded = $this->upload->data();
        	$uploaded['status'] = true;
        	return $uploaded;
        }
        return $data;
	}

	
	private function isManagerAndAbove($user_id)
	{
		if($user_id == 22) return true; //bypassed kak lin consider as manager
		if($user_id == 28) return true; //bypassed kak suhizawati
		if($user_id == 486) return true; //bypassed Fatin Zatalini

		$result = $this->db
				->where('b.parent_id',1)
				->or_where('b.parent_id',2)
				->join('user__employment_detail a','b.id = a.position_id and a.user_id = '.$user_id)
				->get('company__position b')->result();

		if(empty($result)){
			return false;
		}else{
			return true;
		}
	}

	private function isTeamLeader($user_id)
	{

		$result = $this->job_v2->is_team_leader($user_id);

		// debug($result);

		if(empty($result)){
			return false;
		}else{
			return true;
		}
	}
	
	/**
	 * todo: baiki query ni
	 * ni salah sebab prof ahcene akan jadi bukan manager adan keatas
	 */
	private function deptManagers($dept_id)
	{
		$where = array
		(
			'a.department_id' 	=> $dept_id,
			'a.position_id <=' 	=> 12,
			'a.status' 			=> 0,
			'a.is_delete' 		=> 0
		);

		$join = array
		(
			array('user b','b.id = a.user_id','left')
		);

		$managers = $this->model_general->fetchAll('user__employment_detail a',array('a.*,b.email'), $where,$join);
		return $managers;
	}

	private function createEmail($to, $email_subject, $email_body)
	{
		if(!empty($to))
		{
			$email_data = array
			(
				'email'   		=> $to, //managers email
				'subject' 		=> $email_subject,
			);
			// $mail = $this->template->sendMail($email_data, $email_body);
		}	
	}

	private function createWebNotification($from,$to,$link,$type,$heading,$message)
	{
		$this->load->model('hr/model_notification','notification');
		$id = $this->notification->setFrom($from)
						->setTo($to)
						->setType($type)
						->setHeading($heading)
						->setMessage($message)
						->setIcon('fas fa-money-bill-alt')
						->setImage('fas fa-money-bill-alt')
						->setLink($link)
						->notify()
						->getInsertId();
		return (!empty($id))?$id:null;
	}

	private function log($file,$content)
	{
		$this->load->helper('file');
		$string = read_file($file);
		$string .= PHP_EOL.$content;
		if(!write_file($file,$string))
		{
			die(debug('unable to write log content'));
		}
	}

	private function addMileage($year,$month,$user_id,$claim_id)
	{
		$data = array(
			'role'				=> $this->logged_module['role'],
			'item'				=> $this->model_general->fetchAll('_ref__claim_type_detail',array('*') , array('claim_type_id' => 8)),
			'staff'				=> $this->model_user->getUsers(),
			'clients'			=> $this->model_crm->getCustomer(),
			'Operation'  		=> "Add",
			'page_setup'		=> $this->template->pageSetup('HR', 'home', 'Claim'),
			'vehicles'			=> 	$this->model_general->fetchAll('hr__ref_claim_travelling_vehicle',array('*')),
			'year'				=> $year,
			'month'				=> $month,
		);
		$this->template->view('hr/claim/mileage_claim', $data);
	}

	/**
	 * Original : _outpatientAdjustment
	 *  
	 */
	// private function _outpatientAdjustment($user_id,$year)
	// {
	// 	$claims = array();
	// 	$pending_claims  = array();
	// 	$approved_claims = array();
	// 	$rejected_claims = array();

	// 	//1. get all journal for the year where is_delete is 0
	// 	$journal_collections = $this->outpatient->get_all_claim_by_prorated_year($user_id,$year);
	// 	//2. foreach journal cari claim yang masih lagi pending
	// 	if(!empty($journal_collections))
	// 	{
	// 		foreach ($journal_collections as $outer_key => $collections) 
	// 		{
	// 			if(!empty($collections))
	// 			{
	// 				foreach ($collections as $key => $collection) 
	// 				{
	// 					$claim = array
	// 					(
	// 						'id' 				=> $collection->id,
	// 						'user_id'			=> $collection->user_id,
	// 						'date'				=> $collection->date,
	// 						'year'				=> $collection->year,			//submission year
	// 						'month'				=> $collection->month,			//submission month
	// 						'claim_id'			=> $collection->claim_id,
	// 						'invoice_chit'		=> $collection->invoice_chit,
	// 						'clinic_name'		=> $collection->clinic_name,
	// 						'treatment'			=> $collection->treatment,
	// 						'patient_name'		=> $collection->patient_name,
	// 						'relation'			=> $collection->relation,
	// 						'amount_claim'		=> $collection->amount_claim,
	// 						'amount_charge'		=> $collection->amount_charge,
	// 						'is_delete'			=> $collection->is_delete,
	// 						'is_approve'		=> $collection->is_approve,
	// 						'is_hod_approved'	=> $collection->is_hod_approved,
	// 						'hod_remarks'		=> $collection->hod_remarks,
	// 						'admin_remarks'		=> $collection->admin_remarks,
	// 						'approved_hod_by'	=> $collection->approved_hod_by,
	// 						'prorated_month'	=> date('m',strtotime($collection->date)),
	// 						'prorated_year'		=> date('Y',strtotime($collection->date))
	// 					);
	// 					array_push($claims,$claim);
	// 					if(!empty(!empty($collection->outpatients)))	
	// 					{
	// 						foreach ($collection->outpatients as $inner_key => $outpatient) 
	// 						{
	// 							if($outpatient->is_approve == 0)
	// 							{
	// 								$pending = array
	// 								(
	// 									'id'				=> $outpatient->id,
	// 									'journal_id' 		=> $outpatient->journal_id,
	// 									'journal_amount'	=> $outpatient->amount_charge,
	// 									'claim_amount'		=> $outpatient->amount_claim,
	// 									'claim_approve'		=> $outpatient->amount_approved
	// 								);
	// 								array_push($pending_claims,$pending);
	// 							}

	// 							if($outpatient->is_approve == 1)
	// 							{
	// 								$approve = array
	// 								(
	// 									'id'				=> $outpatient->id,
	// 									'journal_id' 		=> $outpatient->journal_id,
	// 									'journal_amount'	=> $outpatient->amount_charge,
	// 									'claim_amount'		=> $outpatient->amount_claim,
	// 									'claim_approve'		=> $outpatient->amount_approved
	// 								);
	// 								array_push($approved_claims,$approve);
	// 							}

	// 							if($outpatient->is_approve == 2)
	// 							{
	// 								$reject = array
	// 								(
	// 									'id'				=> $outpatient->id,
	// 									'journal_id' 		=> $outpatient->journal_id,
	// 									'journal_amount'	=> $outpatient->amount_charge,
	// 									'claim_amount'		=> $outpatient->amount_claim,
	// 									'claim_approve'		=> $outpatient->amount_approved
	// 								);
	// 								array_push($rejected_claims,$reject);
	// 							}

	// 						}
	// 					}
	// 				}
	// 			}	
	// 		}
	// 	} 

	// 	//3. set semua pending jadi is_delete
	// 	if(!empty($pending_claims))
	// 	{
	// 		foreach ($pending_claims as $key => $pending) 
	// 		{
	// 			$this->outpatient->updateOutpatient(array('is_delete' => 1),array('id' => $pending['id']));		
	// 		}
	// 	}

	// 	//4. kira berapa approved dan rejected
	// 	if(!empty($claims))
	// 	{	
	// 		foreach ($claims as $key => $claim) 
	// 		{
	// 			$approved_and_rejected_amount = 0;
	// 			foreach ($approved_claims as $inner_key => $approved) 
	// 			{
	// 				if($approved['journal_id'] == $claim['id'])
	// 				{
	// 					$approved_and_rejected_amount += $approved['claim_approve'];
	// 				}
	// 			}
	// 			$claims[$key]['approved_and_rejected_amount']  =  $approved_and_rejected_amount;

    //             $outpatient = new Outpatient();
	// 			$outpatient->id 				= $claim['id'];
	// 			$outpatient->user_id 			= $claim['user_id'];
	// 			$outpatient->claim_id 			= $claim['claim_id'];
	// 			$outpatient->journal_id 		= $claim['id'];
	// 			$outpatient->date 				= $claim['date'];
	// 			$outpatient->prorate_month 		= $claim['prorated_month'];
	// 			$outpatient->invoice_chit 		= $claim['invoice_chit'];
	// 			$outpatient->clinic_id 			= $claim['clinic_name']; 
	// 			$outpatient->patient_id 		= null;
	// 			$outpatient->patient_name 		= $claim['patient_name'];
	// 			$outpatient->relation 			= $claim['relation'];
	// 			$outpatient->treatment 			= $claim['treatment'];
	// 			$outpatient->amount_charge 		= $claim['amount_charge'];
	// 			$outpatient->amount_claim 		= $claim['amount_claim'];
	// 			$outpatient->is_medical 		= 0;
	// 			$outpatient->is_approve 		= 0;
	// 			$outpatient->amount_approved 	= 0;
	// 			// $outpatient->approved_date 		= null;
	// 			// $outpatient->approved_by 		= null;
	// 			$outpatient->is_hod_approved 	= 0;
	// 			// $outpatient->approved_hod_by 	= null;
	// 			$outpatient->hod_remarks 		= '';
	// 			$outpatient->admin_remarks 		= '';
	// 			$outpatient->is_delete 			= 0;
	// 			// $outpatient->delete_by 			= null;
	// 			// die(debug($outpatient));
	// 			$this->recursiveOutpatient($outpatient->journal_id,(array)$outpatient,$outpatient,date('m',strtotime($outpatient->date)),date('Y',strtotime($outpatient->date)),$claim['month'],$claim['year']);
	// 		}
	// 	}

	// }
	/**
	 * end : original _outpatientAdjustment
	 * 
	 * 
	 */


	private function _outpatientAdjustment($user_id,$year)
	{
		$claims = array();
		$pending_claims  = array();$total_pending = 0;
		$approved_claims = array();
		$rejected_claims = array();

		//1. get all journal for the year where is_delete is 0
		$journal_collections = $this->outpatient->get_all_claim_by_prorated_year($user_id,$year);

		//2. foreach journal cari claim yang masih lagi pending
		if(!empty($journal_collections))
		{
			foreach ($journal_collections as $outer_key => $collections) 
			{
				if(!empty($collections))
				{
					foreach ($collections as $key => $collection) 
					{
						$claim = array
						(
							'id' 				=> $collection->id,
							'user_id'			=> $collection->user_id,
							'date'				=> $collection->date,
							'year'				=> $collection->year,			//submission year
							'month'				=> $collection->month,			//submission month
							'claim_id'			=> $collection->claim_id,
							'invoice_chit'		=> $collection->invoice_chit,
							'clinic_name'		=> $collection->clinic_name,
							'treatment'			=> $collection->treatment,
							'patient_id'		=> $collection->outpatients[0]->patient_id,
							'patient_name'		=> $collection->patient_name,
							'relation'			=> $collection->relation,
							'amount_claim'		=> $collection->amount_claim,
							'amount_charge'		=> $collection->amount_charge,
							'is_delete'			=> $collection->is_delete,
							'is_approve'		=> $collection->is_approve,
							'is_hod_approved'	=> $collection->is_hod_approved,
							'hod_remarks'		=> $collection->hod_remarks,
							'admin_remarks'		=> $collection->admin_remarks,
							'approved_hod_by'	=> $collection->approved_hod_by,
							'prorated_month'	=> date('m',strtotime($collection->date)),
							'prorated_year'		=> date('Y',strtotime($collection->date))
						);
						array_push($claims,$claim);
						if(!empty(!empty($collection->outpatients)))	
						{
							foreach ($collection->outpatients as $inner_key => $outpatient) 
							{
								if($outpatient->is_approve == 0)
								{
									$pending = array
									(
										'id'				=> $outpatient->id,
										'journal_id' 		=> $outpatient->journal_id,
										'journal_amount'	=> $outpatient->amount_charge,
										'claim_amount'		=> $outpatient->amount_claim,
										'claim_approve'		=> $outpatient->amount_approved
									);
									array_push($pending_claims,$pending);
									$total_pending += $outpatient->amount_claim;
								}

								if($outpatient->is_approve == 1)
								{
									$approve = array
									(
										'id'				=> $outpatient->id,
										'journal_id' 		=> $outpatient->journal_id,
										'journal_amount'	=> $outpatient->amount_charge,
										'claim_amount'		=> $outpatient->amount_claim,
										'claim_approve'		=> $outpatient->amount_approved
									);
									array_push($approved_claims,$approve);
								}

								if($outpatient->is_approve == 2)
								{
									$reject = array
									(
										'id'				=> $outpatient->id,
										'journal_id' 		=> $outpatient->journal_id,
										'journal_amount'	=> $outpatient->amount_charge,
										'claim_amount'		=> $outpatient->amount_claim,
										'claim_approve'		=> $outpatient->amount_approved
									);
									array_push($rejected_claims,$reject);
								}

							}
						}
					}
				}	
			}
		} 


		//3. set semua pending jadi is_delete *2021/03/02 off due to off prorate by FARID
		// if(!empty($pending_claims))
		// {
		// 	foreach ($pending_claims as $key => $pending) 
		// 	{
		// 		$this->outpatient->updateOutpatient(array('is_delete' => 1),array('id' => $pending['id']));
		// 	}
		// }

		
		//4. kira berapa approved dan rejected
		if(!empty($claims))
		{	
			foreach ($claims as $key => $claim) 
			{
				$approved_and_rejected_amount = 0;
				foreach ($approved_claims as $inner_key => $approved) 
				{
					if($approved['journal_id'] == $claim['id'])
					{
						$approved_and_rejected_amount += $approved['claim_approve'];
					}
				}
				$claims[$key]['approved_and_rejected_amount']  =  $approved_and_rejected_amount;

                $outpatient = new Outpatient();
				$outpatient->id 				= $claim['id'];
				$outpatient->user_id 			= $claim['user_id'];
				$outpatient->claim_id 			= $claim['claim_id'];
				$outpatient->journal_id 		= $claim['id'];
				$outpatient->date 				= $claim['date'];
				$outpatient->prorate_month 		= $claim['prorated_month'];
				$outpatient->invoice_chit 		= $claim['invoice_chit'];
				$outpatient->clinic_id 			= $claim['clinic_name']; 
				$outpatient->patient_id 		= $claim['patient_id'];
				$outpatient->patient_name 		= $claim['patient_name'];
				$outpatient->relation 			= $claim['relation'];
				$outpatient->treatment 			= $claim['treatment'];
				$outpatient->amount_charge 		= $claim['amount_charge'];
				$outpatient->amount_claim 		= $claim['amount_claim'];
				$outpatient->is_medical 		= 0;
				$outpatient->is_approve 		= 0;
				$outpatient->amount_approved 	= 0;
				// $outpatient->approved_date 		= null;
				// $outpatient->approved_by 		= null;
				$outpatient->is_hod_approved 	= 0;
				// $outpatient->approved_hod_by 	= null;
				$outpatient->hod_remarks 		= '';
				$outpatient->admin_remarks 		= '';
				$outpatient->is_delete 			= 0;
				// $outpatient->delete_by 			= null;
				// die(debug($outpatient));
				$this->recursiveOutpatient($outpatient->journal_id,(array)$outpatient,$outpatient,date('m',strtotime($outpatient->date)),date('Y',strtotime($outpatient->date)),$claim['month'],$claim['year']);
			}
		}
	}


	private function _dental_optical_adjustment($user_id,$year)
	{	
		$claims = array();
		$pending_claims  = array();
		$approved_claims = array();
		$rejected_claims = array();

		$journal_collections = $this->dental->get_all_claim_by_prorated_year($user_id,$year);
		if(!empty($journal_collections))
		{
			foreach ($journal_collections as $outer_key => $journals) 
			{
				if(!empty($journals))
				{
					foreach ($journals as $journal_key => $journal) 
					{

						if(!empty($journal->dentals))
						{
							foreach ($journal->dentals as $dental_key => $dental) 
							{
								$claim = array
								(
									'id' 				=> $journals[$journal_key]->id,
									'claim_id'			=> $journals[$journal_key]->claim_id,
									'user_id'			=> $journals[$journal_key]->user_id,
									'date'				=> $journals[$journal_key]->date,
									'year'				=> $journals[$journal_key]->year,
									'month'				=> $journals[$journal_key]->month,
									'invoice_chit'		=> $journals[$journal_key]->invoice_chit,
									'clinic_name'		=> $journals[$journal_key]->clinic_name,
									'amount_charge'		=> $journals[$journal_key]->amount_charge,
									'amount_claim'		=> $journals[$journal_key]->amount_claim,
									'hod_remarks'		=> '',
									'admin_remarks'		=> '',
									'is_delete'			=> 0,
									'is_hod_approved'	=> 0,
									'is_approved'		=> 0,
									'approved_hod_by' 	=> 0
								);
								array_push($claims,$claim);

								if($dental->is_approve == 0)
								{
									$pending = array
									(
										'id'				=> $dental->id,
										'journal_id' 		=> $dental->journal_id,
										'journal_amount'	=> $dental->amount_charge,
										'claim_amount'		=> $dental->amount_claim,
										'claim_approve'		=> $dental->amount_approved
									);
									array_push($pending_claims,$pending);
								}

								if($dental->is_approve == 1)
								{
									$approve = array
									(
										'id'				=> $dental->id,
										'journal_id' 		=> $dental->journal_id,
										'journal_amount'	=> $dental->amount_charge,
										'claim_amount'		=> $dental->amount_claim,
										'claim_approve'		=> $dental->amount_approved
									);
									array_push($approved_claims,$approve);
								}

								if($dental->is_approve == 2)
								{
									$reject = array
									(
										'id'				=> $dental->id,
										'journal_id' 		=> $dental->journal_id,
										'journal_amount'	=> $dental->amount_charge,
										'claim_amount'		=> $dental->amount_claim,
										'claim_approve'		=> $dental->amount_approved
									);
									array_push($rejected_claims,$reject);
								}

							}
						}
					}
				}
			}
		}

		// die(debug($pending_claims));
		//3. set semua pending jadi is_delete
		if(!empty($pending_claims))
		{
			foreach ($pending_claims as $key => $pending) 
			{
				$this->dental->updateDental(array('is_delete' => 1),array('id' => $pending['id']));
			}
		}

		// die(debug($claims,$pending_claims,$approved_claims,$rejected_claims));

		//kira berapa approved and rejected claims
		if(!empty($claims))
		{
			foreach ($claims as $claim_key => $claim) 
			{
				$approved_and_rejected_amount = 0;
				foreach ($approved_claims as $approved_key => $approved) 
				{					
					if($approved['journal_id'] == $claim['id'])
					{
						$approved_and_rejected_amount += $approved['claim_approve'];
					}
				}

					$dental_optical = new Dental();
					// $dental_optical->id 			 = $claim['id'];
					$dental_optical->claim_id 		 = $claim['claim_id'];
					$dental_optical->user_id 		 = $claim['user_id'];
					$dental_optical->journal_id 	 = $claim['id'];
					$dental_optical->date 			 = date('d-m-Y',strtotime($claim['date']));
					$dental_optical->prorate_month 	 = date('m',strtotime($claim['date']));
					$dental_optical->invoice_chit 	 = $claim['invoice_chit'];
					$dental_optical->clinic_name 	 = $claim['clinic_name'];
					$dental_optical->amount_charge   = $claim['amount_charge']; 
					$dental_optical->amount_claim 	 = $claim['amount_claim'] - $approved_and_rejected_amount;
					$dental_optical->is_approve 	 = 0;
					$dental_optical->amount_approved = 0;
					$dental_optical->approved_by 	 = 0;
					$dental_optical->is_delete 		 = 0;
					$dental_optical->is_hod_approved = 0;
					$dental_optical->hod_remarks 	 = '';
					$dental_optical->admin_remarks   = '';
					$dental_optical->approved_hod_by = 0;
					$dental_optical->delete_by 		 = 0;
					$this->recursiveDental($dental_optical,(array)$dental_optical,$dental_optical->journal_id,date('m',strtotime($dental_optical->date)),date('Y',strtotime($dental_optical->date)),$claim['month'],$claim['year']);
			}
		}
	}

	//to avoid multiple request in recursive operation [outpatient / dental]
	private $prorate_table; 
	private $outpatient_total_allocation; 
	private $patient_info;
	private function recursiveOutpatient($journal_id,$journal,$claim_outpatient,$prorated_month,$prorated_year,$submission_month = null,$submission_year = null)
	{
		$data = array
		(
			'journal_id'				=> $journal_id,
			'journal'					=> $journal,
			'form'						=> $claim_outpatient,
			'view_claim_outpatient'		=> $this->outpatient->get_view_outpatient($prorated_month,$prorated_year,$journal['user_id']),
			'prorated_month'			=> $prorated_month,
			'prorated_year'				=> $prorated_year,
			'submission_month'			=> $submission_month,
			'submission_year'			=> $submission_year,
			'is_submission_created'		=> (!empty($claim = $this->model_claim->getClaimId((!empty($submission_month))?$submission_month:$prorated_month,(!empty($submission_year))?$submission_year:$prorated_year,$journal['user_id'])))?true:false, 
			'claim_id'					=> (!empty($claim))?$claim[0]->id:null,
			'patient_info'				=> (!empty($this->patient_info))?$this->patient_info:$this->patient_info = $this->get_patient_info($journal),
		);
	
		if($data['prorated_month'] >= 13)return;
		if($data['form']->amount_claim <= 0)return;
		if(empty($data['view_claim_outpatient'])) return;

		if($data['view_claim_outpatient'][0]->balanced_prorate > 0)
		{
			if(empty($data['is_submission_created']))
			{
				//create submission if the submission is not created yet
				$table_claim = array
				(
					'user_id' 		=> $journal['user_id'],
					'year'			=> $submission_year,
					'month'			=> $submission_month,
					'status'		=> 0,
					'is_submit'		=> 0,
					'is_delete'		=> 0,
					'paid_amount'	=> null,
				);
				$data['claim_id'] = $this->claim->insertNewClaimMonth($table_claim);
			}

			$claimable_amount = 0;
			if($data['form']->amount_claim > $data['view_claim_outpatient'][0]->balanced_prorate)
			{
				$claimable_amount = $data['view_claim_outpatient'][0]->balanced_prorate;
				$claim_outpatient->amount_claim = $data['form']->amount_claim - $data['view_claim_outpatient'][0]->balanced_prorate;
			}else{
				$claimable_amount = $data['form']->amount_claim;
				$claim_outpatient->amount_claim = 0;
			}

			$table_claim_outpatient = array
			(
				'claim_id' 			=> $data['claim_id'],
				'journal_id' 		=> $data['journal_id'],
				// 'date' 				=> $journal['date'],
				'date' 				=> $data['form']->date,

				'prorate_month' 	=> $prorated_month, 							//ni value prorate ker month submission,kene reconfirm balik (macam date submission jer)
				'invoice_chit' 		=> $data['form']->invoice_chit,
				'clinic_id' 		=> $data['form']->clinic_id,
				'patient_id' 		=> $data['form']->patient_id,
				'patient_name' 		=> $data['patient_info']['patient_name'],
				'relation' 			=> $data['patient_info']['relation'],
				'treatment' 		=> $data['journal']['treatment'],
				'amount_charge' 	=> $data['form']->amount_charge,
				'amount_claim' 		=> $claimable_amount, 							//kene kira berapa banyak claim yang tinggal untuk claim di bulan tu
				'is_medical' 		=> 0,
				'is_approve' 		=> 0,
				'amount_approved' 	=> 0,
				'is_hod_approved' 	=> 0,
				'hod_remarks' 		=> '',
				'admin_remarks' 	=> '',
				'is_delete' 		=> 0,
			);
			$this->outpatient->createOutpatient($table_claim_outpatient);
		}

		$prorated_month = $prorated_month + 1;
		//change submission month and submission year value
		/**
		 * check submission month dah kene tambah satu ker belum lagi
		 * bila year patut naik satu???
		 * kalau submission month naik satu dan jadi bulan satu, year kene naik satu
		 */
		$month_diff = $submission_month - $prorated_month;
		if($submission_month > 2)
		{
			if($month_diff <= 0)
			{
				$submission_month += 1;
				if($submission_month == 13 && $prorated_month == 12)
				{
					$submission_month = 1;
					$submission_year += 1;
				}
			}
		}else{
			if($submission_month == 2 && $prorated_month == 2)
			{
				$submission_month = 3;
			}
		}
		$this->recursiveOutpatient($journal_id,$journal,$claim_outpatient,$prorated_month,$prorated_year,$submission_month,$submission_year);
	}

	private function recursiveDental($claim_dental,$journal,$journal_id,$prorated_month,$prorated_year,$submission_month,$submission_year)
	{
		$data = array
		(
			'journal_id'				=> $journal_id,
			'journal'					=> $journal,
			'form'						=> $claim_dental,
			'view_claim_dental_optical' => $this->dental->get_view_claim_dental_optical($journal['user_id'],$prorated_year,$prorated_month),
			'prorated_month'			=> $prorated_month,
			'prorated_year'				=> $prorated_year,
			'submission_month'			=> $submission_month,
			'submission_year'			=> $submission_year,
			'is_submission_created'		=> (!empty($claim = $this->model_claim->getClaimId((!empty($submission_month))?$submission_month:$prorated_month,(!empty($submission_year))?$submission_year:$prorated_year,$journal['user_id'])))?true:false, 
			'claim_id'					=> (!empty($claim))?$claim[0]->id:null,
		);

		//1. create an exit point for the recursive 
		if($data['prorated_month'] >= 13)return;
		if($data['form']->amount_claim <= 0)return;
		if(empty($data['view_claim_dental_optical'])) return;

		if($data['view_claim_dental_optical'][0]->balanced_prorate > 0)
		{
			if(empty($data['is_submission_created']))
			{
				//create submission if the submission is not created yet
				$table_claim = array
				(
					'user_id' 		=> $journal['user_id'],
					'year'			=> $submission_year,
					'month'			=> $submission_month,
					'status'		=> 0,
					'is_submit'		=> 0,
					'is_delete'		=> 0,
					'paid_amount'	=> null,
				);
				$data['claim_id'] = $this->model_claim->insertNewClaimMonth($table_claim);
			}

			$claimable_amount = 0;
			if($data['form']->amount_claim > $data['view_claim_dental_optical'][0]->balanced_prorate)
			{
				$claimable_amount = $data['view_claim_dental_optical'][0]->balanced_prorate;
				$claim_dental->amount_claim = $data['form']->amount_claim - $data['view_claim_dental_optical'][0]->balanced_prorate;
			}else{
				$claimable_amount = $data['form']->amount_claim;
				$claim_dental->amount_claim = 0;
			}

			$table_claim_dental = array
			(
				// 'id' 				=> null,
				'claim_id' 			=> $data['claim_id'],
				'journal_id' 		=> $journal_id,
				'date' 				=> date('Y-m-d',strtotime($data['form']->date)),
				'prorate_month' 	=> $data['prorated_month'],
				'invoice_chit' 		=> $data['form']->invoice_chit,
				'clinic_name' 		=> $data['journal']['clinic_name'],
				'amount_charge' 	=> $data['form']->amount_charge,
				'amount_claim' 		=> $claimable_amount,
				'is_approve' 		=> 0,
				'amount_approved' 	=> 0,
				// 'approved_date' 	=> null,
				// 'approved_by' 		=> null,
				'is_delete' 		=> 0,
				'is_hod_approved' 	=> '',
				'hod_remarks' 		=> '',
				'admin_remarks'	 	=>'',
				// 'approved_hod_by' 	=> null,
				// 'delete_by'			=> null,
			);

			$dental_id = $this->dental->createDental($table_claim_dental);
		} 

		$prorated_month = $prorated_month + 1;
		//change submission month and submission year value
		/**
		 * check submission month dah kene tambah satu ker belum lagi
		 * bila year patut naik satu???
		 * kalau submission month naik satu dan jadi bulan satu, year kene naik satu
		 */
		$month_diff = $submission_month - $prorated_month;
		if($submission_month > 2)
		{
			if($month_diff <= 0)
			{
				$submission_month += 1;
				if($submission_month == 13 && $prorated_month == 12)
				{
					$submission_month = 1;
					$submission_year += 1;
				}
			}
		}else{
			if($submission_month == 2 && $prorated_month == 2)
			{
				$submission_month = 3;
			}
		}
		
		$this->recursiveDental($claim_dental,$journal,$journal_id,$prorated_month,$prorated_year,$submission_month,$submission_year);
	}

	private function get_patient_info($claim_outpatient)
	{
		// die(debug($claim_outpatient));
		if (strtolower($claim_outpatient['relation']) == 'self') 
		{
			$relation = 0;
			$patient_name = $_SESSION['user']['name'];
		}elseif (strtolower($claim_outpatient['relation']) == 'child') 
		{
			$relation = 1;
			$patient_name = $this->family->find($claim_outpatient['patient_name'])[0]->name;
		}elseif (strtolower($claim_outpatient['relation']) == 'spouse') 
		{
			$relation = 2;
			$patient_name = $this->family->find($claim_outpatient['patient_name'])[0]->name;
		}
		return array('relation' => $relation,'patient_name' =>$patient_name);
	}

	public function getGadgetYear()
	{
		$staff_id	= $this->input->post('staff_id');
		$year_start = $this->input->post('year_start');

		$check_year_exist = $this->model_claim->checkGadgetYear($staff_id, $year_start);

		if(empty($check_year_exist)){
			print json_encode(array(
				"status" => "success"
			)); 
		}else{
			print json_encode(array(
				"status" => "error",
				"msg"    => "Year allocation already exist for this staff."
			));
		}
	}

	public function saveDressingAllocation()
	{
		$check_existing_year_allocation_dressing = $this->model_claim->check_existing_year_allocation_dressing($this->input->post('staff_id'), $this->input->post('year'));

		if(empty($check_existing_year_allocation_dressing))
		{
			$insertData = array(
				'staff_id' 	=> $this->input->post('staff_id'),
				'year' 		=> $this->input->post('year'),
				'amount' 	=> $this->input->post('amount'),
				'created_by'=> $this->logged_user['id']
			);

			$dressingAllocation = $this->model_general->insert('hr__claim_allocation_dressing', $insertData);

			$this->session->set_flashdata('success',"Successfully create dressing allocation.");
			
			print json_encode(array(
				"status" => "success",
				"message" => $dressingAllocation
			));

		}else{
			print json_encode(array(
				"status" => "error"
			));
		}
	}

	public function saveGadgetAllocation()
	{
		$check_existing_year_allocation_gadget = $this->model_claim->check_existing_year_allocation_gadget($this->input->post('staff_id'), $this->input->post('year_start'));

		if(empty($check_existing_year_allocation_gadget))
		{
			$insertData = array(
				'staff_id' 	=> $this->input->post('staff_id'),
				'year_start'=> $this->input->post('year_start'),
				'year_end'	=> $this->input->post('year_end'),
				'amount' 	=> $this->input->post('amount'),
				'created_by'=> $this->logged_user['id']
			);

			$gadgetAllocation = $this->model_general->insert('hr__claim_allocation_gadget', $insertData);

			$this->session->set_flashdata('success',"Successfully create gadget allocation.");
			
			print json_encode(array(
				"status" => "success",
				"message" => $gadgetAllocation
			));

		}else{
			print json_encode(array(
				"status" => "error"
			));
		}
	}

	public function checkExistingClaim_dressing()
	{
		$staff_id	= $this->input->post('staff_id');
		$year 		= $this->input->post('year');

		$check_claim_exist = $this->model_claim->checkDressingClaim($staff_id, $year);

		if(empty($check_claim_exist)){
			print json_encode(array(
				"status" => "success"
			)); 
		}else{
			print json_encode(array(
				"status" => "error",
				"msg"    => "This staff already have dressing claim for current selected year."
			));
		}
	}

	public function checkExistingClaim_gadget()
	{
		$staff_id	= $this->input->post('staff_id');
		$year_start = $this->input->post('year_start');
		$year_end 	= $this->input->post('year_end');

		$check_claim_exist = $this->model_claim->checkGadgetClaim($staff_id, $year_start, $year_end);

		if(empty($check_claim_exist)){
			print json_encode(array(
				"status" => "success"
			)); 
		}else{
			print json_encode(array(
				"status" => "error",
				"msg"    => "This staff already have gadget claim for current selected year."
			));
		}
	}

	public function deleteDressingAllocation()
	{
		$allocation_id  = $this->input->post('id');

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

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

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

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

	public function deleteGadgetAllocation()
	{
		$allocation_id  = $this->input->post('id');

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

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

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

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

	public function updateDressingAllocation()
	{
		$allocation_id  = $this->input->post('allocation_id');

		$sets = array(
			'year'		=> $this->input->post('year'),
			'amount'	=> $this->input->post('amount'),
			'updated_by'=> $this->logged_user['id']
		);

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

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

		if($affected_rows){
			print json_encode(array(
				"status" => "success",
				"msg"  	 => "Successfully edit dressing allocation."
			)); 
		}else{
			print json_encode(array(
				"status" => "Error",
				"msg"    => "System failed to edit dressing allocation."
			));
		}
	}

	public function updateGadgetAllocation()
	{
		$allocation_id  = $this->input->post('allocation_id');

		$sets = array(
			'year_start'	=> $this->input->post('year_start'),
			'year_end'		=> $this->input->post('year_end'),
			'amount'		=> $this->input->post('amount'),
			'updated_by'  	=> $this->logged_user['id']
		);

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

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

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

	public function specialClaim_dressing($year,$month,$user_id,$claim_id)
	{
		if(!$year || !$month || !$user_id || !$claim_id || ($user_id != $_SESSION['user']['id']) || !$claim_id)
		{
			redirect(base_url('/hr/claim'));
		}

		$check_eligable_for_claim	= $this->model_claim->check_existing_year_allocation_dressing($user_id,$year);

		$is_previous_claimable 		= true;
		$is_previous_2_claimable 	= true;

		if($month == 1)
		{//submission january

			$last_month_allocation_balance 	 = $this->dressing->get_balance_allocation_for_the_year($user_id,$year-1);
			$last_2_month_allocation_balance = $last_month_allocation_balance;

		}elseif($month == 2){

			$last_month_allocation_balance 	 = $this->dressing->get_balance_allocation_for_the_year($user_id,$year);
			$last_2_month_allocation_balance = $this->dressing->get_balance_allocation_for_the_year($user_id,$year-1);

		}else{

			$last_month_allocation_balance 	 = $this->dressing->get_balance_allocation_for_the_year($user_id,$year);
			$last_2_month_allocation_balance = $last_month_allocation_balance;

		}

		if($last_month_allocation_balance 	<= 0)$is_previous_claimable 	= false;
		if($last_2_month_allocation_balance <= 0)$is_previous_2_claimable 	= false;

		$data = array
		(	
			'page_setup' 	=> $this->template->pageSetup('HR', 'home', 'Claim'),
			'Operation'  	=> "Add New",
			'year'			=> $year,
			'month'			=> $month,
			'check_eligable_for_claim'			=> $check_eligable_for_claim,
			'last_month_allocation_balance' 	=> $last_month_allocation_balance,
			'last_2_month_allocation_balance' 	=> $last_2_month_allocation_balance,
			'current_allocation_balance'		=> $this->dressing->get_balance_allocation_for_the_year($user_id,$year)
		);

		$this->template->view('hr/claim/dressing', $data);
	}

	public function specialClaim_gadget($year,$month,$user_id,$claim_id)
	{
		if(!$year || !$month || !$user_id || !$claim_id || ($user_id != $_SESSION['user']['id']) || !$claim_id)
		{
			redirect(base_url('/hr/claim'));
		}

		$check_eligable_for_claim	= $this->model_claim->check_existing_year_allocation_gadget($user_id,$year);

		$is_previous_claimable 		= true;
		$is_previous_2_claimable 	= true;

		if($month == 1)
		{//submission january

			$last_month_allocation_balance 	 = $this->gadget->get_balance_allocation_for_the_year($user_id,$year-1);
			$last_2_month_allocation_balance = $last_month_allocation_balance;

		}elseif($month == 2){

			$last_month_allocation_balance 	 = $this->gadget->get_balance_allocation_for_the_year($user_id,$year);
			$last_2_month_allocation_balance = $this->gadget->get_balance_allocation_for_the_year($user_id,$year-1);

		}else{

			$last_month_allocation_balance 	 = $this->gadget->get_balance_allocation_for_the_year($user_id,$year);
			$last_2_month_allocation_balance = $last_month_allocation_balance;

		}

		if($last_month_allocation_balance 	<= 0)$is_previous_claimable 	= false;
		if($last_2_month_allocation_balance <= 0)$is_previous_2_claimable 	= false;

		$data = array
		(
			
			'page_setup' 	 => $this->template->pageSetup('HR', 'home', 'Claim'),
			'Operation'  	 => "Add New",
			'year'			 => $year,
			'month'			 => $month,
			'check_eligable_for_claim'			=> $check_eligable_for_claim,
			'last_month_allocation_balance' 	=> $last_month_allocation_balance,
			'last_2_month_allocation_balance' 	=> $last_2_month_allocation_balance,
			'current_allocation_balance'		=> $this->gadget->get_balance_allocation_for_the_year_all($user_id,$year)
		);

		$this->template->view('hr/claim/gadget', $data);
	}

	public function get_claim_job_info()
	{
		$claim_id  		= $this->input->post('claim_id');
		$data_claim_job = array();

		$claim_job_travelling 		= $this->job_v2->get_claim_jobs($claim_id, 'hr__claim_travelling', 'claim_travelling');
		$claim_job_petrol 			= $this->job_v2->get_claim_jobs($claim_id, 'hr__claim_petrol', 'claim_petrol');
		$claim_job_accommodation 	= $this->job_v2->get_claim_jobs($claim_id, 'hr__claim_accommodation', 'claim_accommodation');
		$claim_job_meals 			= $this->job_v2->get_claim_jobs($claim_id, 'hr__claim_meals', 'claim_meals');
		$claim_job_subsistence		= $this->job_v2->get_claim_jobs($claim_id, 'hr__claim_subsistence', 'claim_subsistence');
		$claim_job_transportation 	= $this->job_v2->get_claim_jobs($claim_id, 'hr__claim_transportation', 'claim_transportation');
		$claim_job_parking 			= $this->job_v2->get_claim_jobs($claim_id, 'hr__claim_parking', 'claim_parking');
		$claim_job_toll				= $this->job_v2->get_claim_jobs($claim_id, 'hr__claim_toll', 'claim_toll');
		$claim_job_entertainment 	= $this->job_v2->get_claim_jobs($claim_id, 'hr__claim_entertainment', 'claim_entertainment');
		$claim_job_trainer 			= $this->job_v2->get_claim_jobs($claim_id, 'hr__claim_trainer', 'claim_trainer');
		$claim_job_others 			= $this->job_v2->get_claim_jobs($claim_id, 'hr__claim_others', 'claim_others');

		array_push($data_claim_job, $claim_job_travelling, $claim_job_petrol, $claim_job_accommodation, $claim_job_meals, $claim_job_subsistence, $claim_job_transportation, $claim_job_parking, $claim_job_toll, $claim_job_entertainment, $claim_job_trainer, $claim_job_others);

		if($data_claim_job){
			print json_encode(array(
				"status"	=> "success",
				"claim_job"	=> $data_claim_job
			)); 
		}else{
			print json_encode(array(
				"status" => "error"
			));
		}
	}

}

class Outpatient 
{
	public $id;
	public $user_id;
	public $claim_id;
	public $journal_id;
	public $date;
	public $prorate_month;
	public $invoice_chit;
	public $clinic_id;
	public $patient_id;
	public $patient_name;
	public $relation;
	public $treatment;
	public $amount_charge;
	public $amount_claim;
	public $is_medical;
	public $is_approve;
	public $amount_approved;
	public $approved_date;
	public $approved_by;
	public $is_hod_approved;
	public $approved_hod_by;
	public $hod_remarks;
	public $admin_remarks;
	public $is_delete;
	public $delete_by;
}

class Dental 
{
	public $id;
	public $user_id;
	public $claim_id;
	public $journal_id;	
	public $date;
	public $prorate_month;
	public $invoice_chit;
	public $clinic_name;
	public $amount_charge;
	public $amount_claim;
	public $is_approve;
	public $amount_approved;
	public $approved_date;
	public $approved_by;
	public $is_delete;
	public $is_hod_approved;
	public $hod_remarks;
	public $admin_remarks;
	public $approved_hod_by;
	public $delete_by;
}