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

class Claim extends MY_Controller
{
	private $isValidUser = true;
	private $user_id;

	//to avoid multiple request in recursive operation [outpatient / dental]
	private $prorate_table; 
	private $outpatient_total_allocation; 
	private $patient_info;

	function __construct()
	{
		$this->load->module('template');
		$this->load->model('admin/model_user');
		$this->load->model('hr/model_ref_claim_type_detail','claim_type');
		$this->load->model('hr/model_claim_allocation','allocation');
		$this->load->model('hr/model_claim_outpatient','outpatient');
		$this->load->model('hr/model_hospitalization','hospitalization');
		$this->load->model('hr/model_dental','dental');
		$this->load->model('hr/model_medical_screening','medical');
		$this->load->model('hr/model_claim_mileage','mileage');
		$this->load->model('hr/model_claim_others','other');
		$this->load->model('hr/model_claim_travel','travel');
		$this->load->model('hr/model_claim_travel_rate','travel_rate');
		$this->load->model('hr/model_claim_meal','meal');
		$this->load->model('hr/model_user_family','family');
		$this->load->model('hr/model_claim_accomodation','accommodation');
		$this->load->model('hr/model_claim_transportation','transportation');
		$this->load->model('hr/Model_claim_purchase','purchase');
		$this->load->model('hr/Model_claim_subsistence_allowance','subsistence');
		$this->load->model('hr/model_claim_parking','parking');
		$this->load->model('hr/model_claim_toll','toll');
		$this->load->model('hr/model_claim_airport_taxes','airport');
		$this->load->model('hr/model_service_taxes','service');
		$this->load->model('hr/model_claim_laundry','laundry');
		$this->load->model('hr/model_claim_excess_baggage','excess_baggage');
		$this->load->model('hr/model_claim_loss_forex','forex');
		$this->load->model('hr/model_claim_trainer','trainer');
		$this->load->model('hr/model_claim','claim');
		$this->load->model('Model_claim_allocation_detail','allocation_detail');
		$this->load->model('hr/Model_claim_panel','panel');
		$this->load->model('hr/model_dressing','dressing');
		$this->load->model('hr/model_gadget','gadget');

		/**
		 * function JWT ni selalu bagi error token tak dapat..
		 * tak tahu sbb apa
         * kemungkinan sebab id token kot dalam user login kene study lagi tentang bug ni
         * kalau disabled jwt ni ada kemungkinan ada sesetangah function dalam class ni tak dapat jalan
		 */
		$this->load->model('hr/model_claim_','forex');
		$this->load->helper('jwt_helper');
			/**
			 *  takde fancy2 sangat..JWT ni problem tak tahu kat mana..
			 */
		$this->user_id = $this->session->userdata('user')['id'];
		if($this->user_id)
		{
			$this->isValidUser = true;
		}else{
			$this->isValidUser = false;
		}
		
		// $token = explode('.', $this->input->post('token'));
		// list($headb64, $bodyb64, $cryptob64) = $token;
		// $payload = json_e_decode(urlsafe_base64_decode($bodyb64));
		// if(count($payload) >= 0)
		// {
		// 	$this->user_id = $payload[0]->user_id;
		// }
		// $key = $this->model_user->getUserToken($this->user_id);
		// $isValidToken = jwt_decode($this->input->post('token'),$key->id_token,true);
		// if($token)
		// {
		// 	$this->isValidUser = true;
		// }else
		// {
		// 	$data = array(
		// 		'status' => 'failed',
		// 		'message'=>	'invalid token',
		// 		'user_id'=>$this->user_id,
		// 		'isValidToken'=>$payload
		// 	);
		// 	echo json_encode($data);
		// 	return true; 
		// }

	}
	
	function createOutpatient()
	{
		// die(debug($this->input->post('form')));
		$year 				= $this->input->post('year');
		$month 				= $this->input->post('month');
		$user 				= $this->input->post('user');
		$claim_id 			= $this->input->post('claim_id');
		$claim_outpatient 	= json_decode($this->input->post('form'));
		$attachment 		= $this->input->post('attachment');
		$prorate_month 		= date('m',strtotime($claim_outpatient->date)); 

			if(!$this->isValidUser)
			{
				$data = array
				(
					'status'	=> 'failed',
					'message'	=> 'Invalid user token, please relogin before creating claim'
				);
				echo json_encode($data);
				return true;
			}

		/**
		 * CREATE JOURNAL OUTPATIENT CLAIM 
		 * START
		 */
			// if($this->outpatient->get_balance_allocation_for_the_year($user,date('Y',strtotime($claim_outpatient->date))) <= 0)
			// {
			// 	$data = array(
			// 		'status'	=> 'failed',
			// 		'msg'		=> 'Unabled to create claim, allocation balance is empty',
			// 	);
			// 	echo json_encode($data);
			// 	return true;
			// }	

			$this->patient_info = $this->get_patient_info((array)$claim_outpatient);

			switch ($this->patient_info['relation']) 
			{
				case 0:
					$relation = 'Self';
					break;
				case 1:
					$relation = 'Child';
					break;
				case 2:
					$relation = 'Spouse';
					break;
			}

			$journal = array
			(
				'user_id' 			=> $user,
				'date'				=> date('Y-m-d',strtotime($claim_outpatient->date)),
				'year'				=> $year,
				'month'				=> $month,
				'claim_id'			=> $claim_id,
				'invoice_chit'		=> $claim_outpatient->invoice_chit,
				'clinic_name'		=> $claim_outpatient->hospital,
				'treatment'			=> $claim_outpatient->treatment,
				'patient_name'		=> $this->patient_info['patient_name'],
				'relation'			=> $relation,
				'amount_claim'		=> $claim_outpatient->amount_claim,
				'amount_charge'		=> $claim_outpatient->amount_charge,
				'is_delete'			=> 0
			);

			// die(debug($journal));
			$journal_id = $this->outpatient->createOutpatientJournal($journal);
			if(!empty($attachment))
			{	
				$batch_outpatient = array();
				foreach ($attachment as $key => $att) 
				{
					$claim_outpatient_attachment 	= array
					(
						'journal_id'			 => $journal_id,
						'attachment_name'		 => $att['orig_name'],
						'file_type'				 => $att['file_type'],
						'file_ext'				 => str_replace('.','',$att['file_ext']),
						'description'			 => $att['description'],
						'location'				 => 'storage/claim/outpatient/'.$att['file_name'],
						'unique_id'				 => uniqid(),
						'type'					 => 0,
						'is_delete'				 => 0 
					);
					array_push($batch_outpatient,$claim_outpatient_attachment);
				}
				$this->outpatient->createAttachment($batch_outpatient);
			}

		 /**
		  * END
		  */

		if(!empty($journal_id))
		{
			$this->recursiveOutpatient($journal_id,$journal,$claim_outpatient,date('m',strtotime($claim_outpatient->date)),date('Y',strtotime($claim_outpatient->date)),$month,$year);
			// $table_claim_outpatient = array
			// (
			// 	'claim_id' 			=> $claim_id,
			// 	'journal_id' 		=> $journal_id,
			// 	'date' 				=> date('Y-m-d',strtotime($claim_outpatient->date)),
			// 	'prorate_month' 	=> $month, 							
			// 	'invoice_chit' 		=> $claim_outpatient->invoice_chit,
			// 	'clinic_id' 		=> $claim_outpatient->hospital,
			// 	'patient_id' 		=> $this->patient_info['patient_id'],
			// 	'patient_name' 		=> $this->patient_info['patient_name'],
			// 	'relation' 			=> $data['patient_info']['relation'],
			// 	'treatment' 		=> $claim_outpatient->treatment,
			// 	'amount_charge' 	=> $claim_outpatient->amount_charge,
			// 	'amount_claim' 		=> $claim_outpatient->amount_claim, 							
			// 	'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);
		}
			
		$data = array
		(
			'status'	=> 'success',
			'msg'		=> 'Successfully create outpatient claim',
			'input'		=> $this->input->post()
		);
		echo json_encode($data);
		return true;
	}

	/**
	 * version 2.0.2
	 * objective to solve issue from recursiveCreateOutpatient
	 * using view instead of table to calculate how much claimable for outpatient
	 */
	
	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->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'],
				'prorate_month' 	=> $prorated_month, 							//ni value prorate ker month submission,kene reconfirm balik (macam date submission jer)
				'invoice_chit' 		=> $journal['invoice_chit'],
				'clinic_id' 		=> $data['form']->hospital,
				'patient_id' 		=> $data['form']->patient,
				'patient_name' 		=> $data['patient_info']['patient_name'],
				'relation' 			=> $data['patient_info']['relation'],
				'treatment' 		=> $journal['treatment'],
				'amount_charge' 	=> $journal['amount_charge'],
				'amount_claim' 		=> $journal['amount_claim'],							//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 recursiveOutpatient_adjustment($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->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_adjustment($journal_id,$journal,$claim_outpatient,$prorated_month,$prorated_year,$submission_month,$submission_year);
	}

	function removeOutpatientJournal()
	{
		$referrer_explode = explode('/',$_SERVER['HTTP_REFERER']);
		$data = array
		(
			'referrer'  	=> $_SERVER['HTTP_REFERER'],
			'year'	    	=> (!empty($referrer_explode[7]))?$referrer_explode[7]:null, //submission year
			'month'	    	=> (!empty($referrer_explode[8]))?$referrer_explode[8]:null, //submission month
			'user_id'		=> (!empty($referrer_explode[9]))?$referrer_explode[9]:null, //user_id
			'claim_id' 		=> (!empty($referrer_explode[10]))?$referrer_explode[10]:null, //claim_id
		);
	
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$id = $this->input->post('id');
		$outpatients = $this->outpatient->fetchJournalById($id); //untuk dapatkan prorated year
		$this->outpatient->removeOutpatientJournal($id); //yang ni delete journal jer tak delete outpatient
		$this->outpatient_adjustment($data['user_id'],date('Y',strtotime($outpatients[0]->date)));
		echo json_encode(array('status' => 'success','msg' => 'Successfully remove outpatient'));return true;
	}

	//1. year => prorated_year
	private function outpatient_adjustment($user_id,$year)
	{
		$claims = array();
		$pending_claims = array();
		$approved_claims = array();
		$rejected_claims = array();

		//1. get all submission 
		$journal_collections = $this->outpatient->get_all_claim_by_prorated_year($user_id,$year);
		if(!empty($journal_collections))
		{
			foreach ($journal_collections as $collections_key => $journals) 
			{
				if(!empty($journals))
				{
					foreach ($journals as $journal_key => $journal) 
					{
						$claim = array
						(
							'id' 				=> $journal->id,
							'user_id'			=> $journal->user_id,
							'date'				=> $journal->date,
							'year'				=> $journal->year,									//submission year
							'month'				=> $journal->month,									//submission month
							'claim_id'			=> $journal->claim_id,
							'invoice_chit'		=> $journal->invoice_chit,
							'clinic_name'		=> $journal->clinic_name,
							'treatment'			=> $journal->treatment,
							'patient_name'		=> $journal->patient_name,
							'relation'			=> $journal->relation,
							'amount_claim'		=> $journal->amount_claim,
							'amount_charge'		=> $journal->amount_charge,
							'is_delete'			=> $journal->is_delete,
							'is_approve'		=> $journal->is_approve,
							'is_hod_approved'	=> $journal->is_hod_approved,
							'hod_remarks'		=> $journal->hod_remarks,
							'admin_remarks'		=> $journal->admin_remarks,
							'approved_hod_by'	=> $journal->approved_hod_by,
							'prorated_month'	=> date('m',strtotime($journal->date)),
							'prorated_year'		=> date('Y',strtotime($journal->date))
						);
						array_push($claims,$claim);

						if(!empty($journal->outpatients))
						{
							foreach ($journal->outpatients as $outpatient_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);
								}
							}
						}
					}
				}
			}
		}

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

		//3. buat recursive 
		// $this->recursiveOutpatient($journal_id,$journal,$claim_outpatient,$prorated_month,$prorated_year,$submission_month,$submission_year);
		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();
                // die(debug($claim));
				$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_adjustment($outpatient->journal_id,(array)$outpatient,$outpatient,date('m',strtotime($outpatient->date)),date('Y',strtotime($outpatient->date)),$claim['month'],$claim['year']);
			}
		}
	}


	//----------------------------


	function removeOutpatient()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$id = $this->input->post('id');
		$this->outpatient->removeOutpatient($id);
		// $this->outpatient->removeOutpatientJournal($id);
		
		 

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

	function approveOutpatient()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'msg'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$input = $this->input->post();


		$update = array(
			'is_approve' 		=> $input['status'],
			'amount_approved' 	=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'		=> (!empty($input['reason']))?$input['reason']:'',
			'approved_date' 	=> date('Y-m-d'),
			'approved_by' 		=> $this->user_id
		);
		$where = array('id' => $input['approve_id']);

		$this->outpatient->updateOutpatient($update,$where);
        echo json_encode(array('status'=>'success','msg' => 'successfully change claim status'));
        return true;
	}

	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'])[0]->name;
		}elseif (strtolower($claim_outpatient['relation']) == 'spouse') 
		{
			$relation = 2;
			$patient_name = $this->family->find($claim_outpatient['patient'])[0]->name;
		}
		return array('relation' => $relation,'patient_name' =>$patient_name);
	}

	function createHospitalization()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$claim_hospitalization = json_decode($this->input->post('form'));
		$attachment = $this->input->post('attachment');

		$hosp_input = array
		(
			'claim_id' 			=> $this->input->post('claim_id'),
			'date'				=> date('Y-m-d',strtotime($claim_hospitalization->date)),
			'invoice_chit'  	=> (!empty($claim_hospitalization->invoice_chit))?$claim_hospitalization->invoice_chit:'',
			'clinic_name'		=> (!empty($claim_hospitalization->hospital))?$claim_hospitalization->hospital:'',
			'patient_id'		=> (!empty($claim_hospitalization->patient))?$claim_hospitalization->patient:'',
			'treatment'			=> (!empty($claim_hospitalization->treatment))?$claim_hospitalization->treatment:'',
			'day_warded'		=> (!empty($claim_hospitalization->day_warded))?$claim_hospitalization->day_warded:'',
			'payment_method'	=> (!empty($claim_hospitalization->payment_method))?$claim_hospitalization->payment_method:0,
			'room_package_id'	=> (!empty($claim_hospitalization->room_package))?$claim_hospitalization->room_package:'',
			'room_amount'		=> (!empty($claim_hospitalization->room_amount))?$claim_hospitalization->room_amount:'',
			'amount_charge' 	=> (!empty($claim_hospitalization->amount_charge))?$claim_hospitalization->amount_charge:'',
			'amount_claim'		=> (!empty($claim_hospitalization->amount_claim))?$claim_hospitalization->amount_claim:'',
		);
		$isHospitalize = $this->hospitalization->createHospitalization($hosp_input);
		
		if ($isHospitalize) 
		{			
			$att_input = array();
			foreach ($attachment as $key => $row) {
				$container = array(
					'hospitalization_id'=> $isHospitalize,
					'attachment_name'	=> $row['orig_name'],
					'file_type'			=> $row['file_type'],
					'file_ext'			=> str_replace('.', '', $row['file_ext']),
					'description'		=> $row['description'],
					'location'			=> 'storage/claim/hospitalization/'.$row['file_name'],
					'unique_id'			=> time().uniqid(),
					'type'				=> $row['file_type'],
					'is_delete'			=> 0, 
					);
				array_push($att_input, $container);
			}
			$this->hospitalization->createAttachment($att_input);
		}	

		$data = array
		(
			'status'	=> 'success',
			'msg'		=> 'Successfully create hospitalization claim',
			'input'		=> $this->input->post()
		);
		echo json_encode($data);return true;
	}

	function removeHospitalization()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		
		$id = $this->input->post('id');
		$this->hospitalization->removeHospitalization($id);

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

	function approveHospitalization()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$input = $this->input->post();


		$update = array
		(
			'is_approve' 		=> $input['status'],
			'amount_approved' 	=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'		=> (!empty($input['reason']))?$input['reason']:'',
			'approved_date' 	=> date('Y-m-d'),
			'approved_by' 		=> $this->user_id
		);

		$where 	= array('id' => $input['approve_id']);
		$this->hospitalization->updateHospitalization($update,$where);
		echo json_encode(array('status'=>'success','msg' => 'Successfully change hospitalization status'));return true;
	}

	function createDental()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$claim_id 		= $this->input->post('claim_id');
		$claim_dental 	= json_decode($this->input->post('form'));

		$attachment 	= $this->input->post('attachment');
		$year 			= $this->input->post('year');
		$month 			= $this->input->post('month');
		$user 			= $this->input->post('user');
		
		$prorate_year 	= date('Y',strtotime($claim_dental->date));
		$prorate_month 	= date('m',strtotime($claim_dental->date));
		$year_submission = $year;
		
		/**
		 * CREATING JOURNAL FOR DENTAL OPTICAL FOR DELETE PURPOSE
		 * START
		 */
		$journal = array
		(
			'claim_id' 			=> $claim_id, 
			'user_id' 			=> $user, 
			'date' 				=> date('Y-m-d',strtotime($claim_dental->date)),
			'year'				=> $year,
			'month'				=> $month,
			'invoice_chit' 		=> $claim_dental->invoice_chit,
			'clinic_name' 		=> $claim_dental->optometrist_dentist,
			'amount_charge' 	=> $claim_dental->amount_charge,
			'amount_claim' 		=> $claim_dental->amount_claim,
			'hod_remarks' 		=> '',
			'is_delete' 		=> 0,
			'is_hod_approved' 	=> 0
		);
		$journal_id = $this->dental->createJournal($journal);
		/**
		 * END
		 */

		$table_claim_dental = array
		(
			'claim_id'	 		=> $claim_id,
			'journal_id'		=> $journal_id,
			'date'				=> date('Y-m-d',strtotime($claim_dental->date)),
			'prorate_month'		=> $month,
			'invoice_chit'		=> $claim_dental->invoice_chit,
			'clinic_name'		=> $claim_dental->optometrist_dentist,
			'amount_charge'		=> $claim_dental->amount_charge,
			'amount_claim'		=> $claim_dental->amount_claim,
			'is_approve'		=> 0,
			'amount_approved'	=> 0,
			'is_delete'			=> 0,
			'is_hod_approved'	=> '',
			'hod_remarks'		=> '',
			'admin_remarks'		=> '',
		);
		$dental_id = $this->dental->createDental($table_claim_dental);

		if(!empty($journal_id))
		{
			//create attachments
			if(!empty($attachment))
			{	
				$batch_outpatient = array();
				foreach ($attachment as $key => $att) 
				{
					$claim_outpatient_attachment 	= array
					(
						'journal_id'			 => $journal_id,
						'attachment_name'		 => $att['orig_name'],
						'file_type'				 => $att['file_type'],
						'file_ext'				 => str_replace('.','',$att['file_ext']),
						'description'			 => $att['description'],
						'location'				 => 'storage/claim/dental/'.$att['file_name'],
						'unique_id'				 => uniqid(),
						'type'					 => 0,
						'is_delete'				 => 0 
					);
					array_push($batch_outpatient,$claim_outpatient_attachment);
				}
				$this->dental->createAttachment($batch_outpatient);
			}
			//create attachments

			// $this->recursiveCreateDentals($claim_dental,$claim_id,$year_submission,$user,$month,$prorate_month,$prorate_year,null,$journal_id);
			// $this->recursiveDental($claim_dental,$journal,$journal_id,date('m',strtotime($claim_dental->date)),date('Y',strtotime($claim_dental->date)),$month,$year);

			/*START off prorate for 2021 by Farid 20210223 */
			
			// $this->construct_dental_prorate($user,date('m',strtotime($claim_dental->date)),date('Y',strtotime($claim_dental->date)),$month,$year,$claim_dental->amount_claim,$journal_id,date('Y-m-d',strtotime($claim_dental->date)),$claim_dental->invoice_chit,$claim_dental->optometrist_dentist,$claim_dental->amount_charge);

			/*END off prorate for 2021 by Farid 20210223 */
		}
		
		$data = array
		(
			'status'	=> 'success',
			'msg'		=> 'Successfully create dental / optical claim',
			'input'		=> $this->input->post()
		);
		echo json_encode($data);return true;	
	}


	/**
	 * version 2.0.2
	 * 
	 */
	private function construct_dental_prorate($user_id,$claim_month,
											$claim_year,$submission_month,$submission_year,$amount,$journal_id,
											$date,$invoice_chit,$clinic_name,$amount_charge)
	{
		$this->load->model('hr/Model_dental_prorate','dental_prorate');
		$stop_loop = false;
		
		$data['claim_detail'] = array
		(
			'user_id'			=> $user_id,
			'claim_month' 		=> $claim_month,
			'claim_year'		=> $claim_year,
			'submission_month'	=> $submission_month,
			'submission_year'	=> $submission_year,
			'total_claim'		=> $amount
		);
		$data['prorates'] = array();
		
		for ($i=0; $i <= 12 && !$stop_loop; $i++) 
		{

			/*
			 * start : Menentukan prorate mana yang akan dipakai
			 */
				$temp = array
				(
					'claim_month'		=> $claim_month,
					'claim_year'		=> $claim_year,
					'submission_year' 	=> $submission_year,
					'submission_month'	=> $submission_month,
				);
				//kalau submission month bulan satu dan 2
				if($submission_month == 1 || $submission_month == 2)
				{
					if($claim_year == $submission_year-1)
					{
						//ni prorate tahun lepas(samada prorate bulan 11 atau 12)..submission bulan satu atau 2
						$temp['prorated_month'] = $temp['claim_month'];
						if($submission_month == 2)$stop_loop = true;
					}else{
						//claim prorate value tahun ni..sama dengan submission bulan 2
						$temp['prorated_month'] = 1;
					}
				}

				if($submission_month != 1 && $submission_month != 2 && $submission_month != 13 && $submission_month != 14)
				{
					$temp['prorated_month'] = $submission_month-1;
				}	
				
				if($submission_month == 13 || $submission_month == 14)
				{
					$temp['submission_year'] 	= $submission_year+1;
					$temp['submission_month'] 	= ($submission_month == 13)?1:2;
					$temp['prorated_month']		= 12;
					if($submission_month == 14)$stop_loop = true;
				}
				$temp['balanced_prorate'] = number_format($this->dental_prorate->get_balanced($temp['prorated_month'],$claim_year,$user_id),2);
			/*
			 * end : Menentukan prorate mana yang akan dipakai
			 */


			/*
				- start : save operation
			*/
				$is_submission_created = (!empty($claim = $this->claim->getClaimId($temp['submission_month'],$temp['submission_year'],$user_id)))?true:false;
				if($temp['balanced_prorate'] > 0)
				{
					if(empty($is_submission_created))
					{
						//create a new submission
						$table_claim = array
						(
							'user_id' 		=> $user_id,
							'year'			=> $submission_year,
							'month'			=> $submission_month,
							'status'		=> 0,
							'is_submit'		=> 0,
							'is_delete'	 	=> 0,
							'paid_amount'	=> null,
						);
						$claim_id = $this->claim->insertNewClaimMonth($table_claim);
					}else{
						$claim_id = $claim[0]->id;
					}

					$claimable_amount = 0;
					
					if($amount > $temp['balanced_prorate'])
					{
						$amount = $amount - $temp['balanced_prorate'];
						$claimable_amount = $temp['balanced_prorate'];
					}else{
						$claimable_amount = $amount;
						$stop_loop = true;
					}

					$table_claim_dental = array
					(
						'claim_id'	 		=> $claim_id,
						'journal_id'		=> $journal_id,
						'date'				=> $date,
						'prorate_month'		=> $temp['prorated_month'],
						'invoice_chit'		=> $invoice_chit,
						'clinic_name'		=> $clinic_name,
						'amount_charge'		=> $amount_charge,
						'amount_claim'		=> $claimable_amount,
						'is_approve'		=> 0,
						'amount_approved'	=> 0,
						'is_delete'			=> 0,
						'is_hod_approved'	=> '',
						'hod_remarks'		=> '',
						'admin_remarks'		=> '',
					);
					$dental_id = $this->dental->createDental($table_claim_dental);
				}
			/*
				- end : save operation
			*/
			$submission_month++;
		}
	}











	/**
	 * version 2.0.1
	 * 
	 * This functions does not works for kak salina prorate not sure why..
	 */
	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->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->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,
				'is_delete' 		=> 0,
				'is_hod_approved' 	=> '',
				'hod_remarks' 		=> '',
				'admin_remarks'	 	=>'',
			);

			$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);
	}
	
	function removeDental()
	{
		
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$id = $this->input->post('id');
		$this->dental->removeDental($id);

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

	function removeDentalJournal()
	{
		$referrer_explode = explode('/',$_SERVER['HTTP_REFERER']);
		$data = array
		(
			'referrer'  	=> $_SERVER['HTTP_REFERER'],
			'year'	    	=> (!empty($referrer_explode[7]))?$referrer_explode[7]:null, //submission year
			'month'	    	=> (!empty($referrer_explode[8]))?$referrer_explode[8]:null, //submission month
			'user_id'		=> (!empty($referrer_explode[9]))?$referrer_explode[9]:null, //user_id
			'claim_id' 		=> (!empty($referrer_explode[10]))?$referrer_explode[10]:null, //claim_id
		);

		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$id = $this->input->post('id');
		$dentals = $this->dental->fetchJournalById($id);
		$this->dental->removeDentalJournal($id);
		// $this->dental_adjustment($data['user_id'],date('Y',strtotime($dentals[0]->date))); *comment for off prorate 2021 by Farid 20210304
		echo json_encode(array('status' => 'success'));return true;
	}

	function dental_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']);
			}
		}
	}

	function approveDentals()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$input = $this->input->post();

		$update = array
		(
			'is_approve' 		=> $input['status'],
			'amount_approved' 	=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'		=> (!empty($input['reason']))?$input['reason']:'',
			'approved_date' 	=> date('Y-m-d'),
			'approved_by' 		=> $this->user_id
		);
		$where = array('id' => $input['approve_id']);

		$this->dental->updateDental($update,$where);
		
		//if status is approved set journal to approve too
		// if($input['status'] == 1)
		// {
		// 	$journal_data = array();
		// 	$this->dental->updateDentalJournal($input,$where = array(''));
		// }
		echo json_encode(array('status'=>'success','msg' => 'Successfully change dental claim status'));return true;	
	} 

	/*
	public function recursiveCreateDentals($claim_dental,$claim_id,$attachment,$year,$user,$month)
	{
		$allocation 			= $this->allocation_detail->calcBalancedAllocation($year,$month,$user);
		$prorated_value_left	= $allocation['dental_optical'];
		$amount_claim 			= $claim_dental->amount_claim;

		if($prorated_value_left < 0)
		{
			return;
		}
		

		$dental_input = array
		(
			'claim_id' 			=> $claim_id,
			'date'				=> date('Y-m-d',strtotime($claim_dental->date)),
			'invoice_chit' 		=> $claim_dental->invoice_chit,
			'clinic_name'		=> $claim_dental->optometrist_dentist,
			'amount_charge'		=> $claim_dental->amount_charge,
			'amount_claim'		=> $prorated_value_left,
			'is_approve'		=> 0,
			'is_delete'			=> 0,
		);
		$isClaimDental = $this->dental->createDental($dental_input);
		if ($isClaimDental) 
		{
			$att_input = array();
			foreach ($attachment as $key => $row) {
				$container = array(
					'dental_id'			=> $isClaimDental,
					'attachment_name'	=> $row['file_name'],
					'file_type'			=> $row['file_type'],
					'file_ext'			=> str_replace('.', '', $row['file_ext']),
					'description'	 	=> $row['description'],
					'location'			=> 'storage/claim/dental/'.$row['file_name'],
					'unique_id'			=> time().uniqid(),
					'type'				=> $row['file_type'],
					);
				array_push($att_input, $container);
			}
			$this->dental->createAttachment($att_input);
		}
	

		if($claim_dental->amount_claim <= 0)
		{
			return;
		}else{

			if($month < 12 && $claim_dental->amount_claim > 0)
			{	
				$month += 1;
				$allocation 			= $this->allocation_detail->calcBalancedAllocation($year,$month,$user);
				
				
				$claims = $this->claim->getClaimId($month,$year,$user);
				if(empty($claims))
				{
					$hr_claim = array
					(
						'user_id'	=> $user,
						'year'		=> $year,
						'month'		=> $month,
						'status'	=> 0,
						'is_submit'	=> 0,
						'is_delete'	=> 0
					);
					$claim_id = $this->claim->insertNewClaimMonth($hr_claim);
				}else{
					$claim_id = $claims[0]->id;
				}

				$this->recursiveCreateDentals($claim_dental,$claim_id,$attachment,$year,$user,$month);
			}else{
				return;
			}
		}
	}
	*/

	function approveMedicals()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$input = $this->input->post();


		$update = array
		(
			'is_approve' 		=> $input['status'],
			'amount_approved' 	=> ($input['status'] == 1)?$input['amount_approve']:0,
			'approved_date' 	=> date('Y-m-d'),
			'approved_by' 		=> $this->user_id
		);

		$where = array('id' => $input['approve_id']);
		$this->medical->updateMedical($update,$where);
		echo json_encode(array('status'=>'success','msg' => 'successfully change medical claim status'));return true;
	}



	 /*
	public function createMileage()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$claim_mileage 	= json_decode($this->input->post('form'));
		$attachment 	= $this->input->post('attachment');

		$amount_claim = $this->mileageToAmount($claim_mileage->distance,$claim_mileage->transport);
		$mileage_input = array(
			'claim_id'		=> $this->input->post('claim_id'),
			'date'			=> date('Y-m-d',strtotime($claim_mileage->date)),
			'transport'		=> $claim_mileage->transport,
			'distance'		=> $claim_mileage->distance,
			'description'	=> $claim_mileage->description,
			'is_approve'	=> 0,
			'amount_claim'	=> $amount_claim,
			'is_delete'		=> 0,
		);

		$mileage_id = $this->mileage->createMileage($mileage_input);
		if($mileage_id){
			$att_input = array();
			foreach ($attachment as $key => $row) {
				$container = array(
					'mileage_id'		=> $mileage_id,
					'attachment_name'	=> $row['file_name'],
					'file_type'			=> $row['file_type'],
					'file_ext'			=> str_replace('.', '', $row['file_ext']),
					'description'	 	=> $row['description'],
					'location'			=> 'storage/claim/dental/'.$row['file_name'],
					'unique_id'			=> time().uniqid(),
					'type'				=> $row['file_type'],
					);
				array_push($att_input, $container);
			}
			$this->mileage->createAttachment($att_input);
		}

		echo json_encode($this->input->post());return true;
	}

	public function removeMileage()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

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

		$this->mileage->removeMileage($id);
		echo json_encode(array('status' => 'success'));return true;
	}

	public function approveMileage()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$input = $this->input->post();


		$update = array('is_approve' => $input['status'],'amount_approve' => $input['amount_approve'],'approved_date' => date('Y-m-d'),'approved_by' => $this->user_id);
		$where = array('id' => $input['approve_id']);

		$this->mileage->updateMileage($update,$where);
		echo json_encode(array('status'=>'success'));return true;
	}
	*/

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

		// die(debug($input));
		
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		/**
		 * - create accommodation
		 */
		$accommodation = array
		(
			'claim_id'				=> $input['claim_id'],
			'date_from'				=> date('Y-m-d',strtotime($input['from'])),
			'date_to'				=> date('Y-m-d',strtotime($input['to'])),
			'amount'				=> $input['amount'],
			'amount_approved'		=> 0,
			'location'				=> $input['location'],
			'type'					=> $input['type'],
			'description'			=> $input['description'],
			'is_admin_approve'		=> 0,
			'is_hod_approve'		=> 0,
			'is_delete'				=> 0,
		);
		$accomodation_id = $this->accommodation->create($accommodation);

		/**
		 * - create receipts
		 */
		if(!empty($input['receipt']))
		{
			$receipts = array
			(
				'accommodation_id'		=> $accomodation_id,
				'attachment_name'		=> $input['receipt']['orig_name'],
				'file_type'				=> $input['receipt']['file_type'],
				'file_ext'				=> $input['receipt']['file_ext'],
				'description'			=> '',
				'location'				=> '/application/storage/claim/traveling/accomodation/'.$input['receipt']['file_name'],
				'unique_id'				=> uniqid(),
				'type'					=> $input['receipt']['file_ext'],
				'is_delete'				=> 0,
			);
			$this->accommodation->createReceipt($receipts);
		}
		

		/**
		 * create movements
		 */
		$movements = [];
		foreach($input['staff_movement'] as $key => $value)
		{
			$movement = array
			(
				'accommodation_id'		=> $accomodation_id,
				'movement_id'			=> $value['group_id'],
			);
			array_push($movements,$movement);
		}
		$this->accommodation->createBatchMovement($movements);
		
		$data = array
		(
			'status'	=> 'success',
			'msg'		=> 'Successfully create accomodation claim',
			'input'		=> $input
		);
		echo json_encode($data);return true;
	}

	function approveAccomodation()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		
		$input = $this->input->post();
	
		$update = array
		(
			'is_admin_approve' 		=> $input['status'],
			'amount_approved' 		=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'			=> (!empty($input['reason']))?$input['reason']:0,
		);
		$where = array('id' => $input['approve_id']);

		$this->accommodation->updateClaim($update,$where);
		echo json_encode(array('status' => 'success','msg' => 'Successfully update accomodation status'));
	}
	
	function removeAccomodation()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$id = $this->input->post('id');
		$data = array
		(
			'is_delete' => 1
		);
		$this->accommodation->updateClaim(array('is_delete' => 1),array('id' => $id));
		echo json_encode(array('status' => 'success','message' => 'Successfully remove accommodation claim'));return true;
	}

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

		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		/**
		 * create transportation
		 */
		$transportation = array
		(
			'claim_id'				=> $input['claim_id'],
			'date'					=> date('Y-m-d',strtotime($input['date'])),
			'transportation_id'		=> $input['transportation'],
			'amount'				=> $input['amount'],
			'amount_approved'		=> 0,
			'description'			=> $input['description'],
			'is_hod_approved'		=> 0,
			'is_admin_approved'		=> 0,
			'hod_remarks'			=> '',
			'admin_remarks'			=> '',
			'is_delete'				=> 0,
			'delete_by'				=> 0,
		);
		$claim_transportation_id = $this->transportation->create($transportation);

		/**
		 * create transportation attachments
		 */
		$attachments = [];
		foreach($input['attachments'] as $key => $value)
		{
			$attachment = array
			(
				'claim_transportation_id'		=> $claim_transportation_id,
				'attachment_name'				=> $value['orig_name'],
				'file_type'						=> $value['file_type'],
				'file_ext'						=> $value['file_ext'],
				'description'					=> $value['description'],
				'location'						=> '/application/storage/claim/traveling/transportation/'.$value['file_name'],
				'unique_id'						=> uniqid(),
				'type'							=> $value['file_type'],
				'is_delete'						=> '0',
			);
			array_push($attachments,$attachment);
		}
		$this->transportation->createAttachment($attachments);

		/**
		 * create movements
		 */
		$staff_movements = [];
		foreach($input['staff_movements'] as $key => $value)
		{
			$movement = array
			(
				'claim_transportation_id'		=> $claim_transportation_id,
				'movement_id'					=> $value['group_id'],
			);
			array_push($staff_movements,$movement);
		}
		$this->transportation->createMovement($staff_movements);


		$data = array
		(
			'status'	=> 'success',
			'msg'		=> 'Successfully create transportation claim',
			'input'		=> $input
		);
		echo json_encode($data);return true;

	}

	function approveTransportation()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		
		$input = $this->input->post();
	
		$update = array
		(
			'is_admin_approved' 		=> $input['status'],
			'amount_approved' 			=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'			=> (!empty($input['reason']))?$input['reason']:0,
		);
		$where = array('id' => $input['approve_id']);

		$this->transportation->updateTransportation($update,$where);
		echo json_encode(array('status' => 'success','msg' => 'Successfully update transportation status'));
	}

	function removeTransportation()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$id = $this->input->post('id');
		$this->transportation->updateTransportation(array('is_delete' => 1),array('id' => $id));
		echo json_encode(array('status' => 'success','msg' => 'Successfully remove transportation claim'));return true;
	}

	function createPurchaseTraveling()
	{
		$input = $this->input->post();
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}


		$purchase_travel = array
		(
			'claim_id'			=> $input['claim_id'],
			'date'				=> date('Y-m-d',strtotime($input['date'])),
			'amount'			=> $input['amount'],
			'amount_approved'	=> 0,
			'description'		=> $input['description'],
			'is_admin_approve'	=> 0,
			'is_hod_approve'	=> 0,
			'hod_remarks'		=> '',
			'admin_remarks'		=> '',
			'is_delete'			=> 0,
			'delete_by'			=> 0,
		);
		$purchase_id = $this->purchase->create($purchase_travel);

		$staff_movements = [];
		foreach($input['staff_movements'] as $key => $value)
		{
			$movement = array
			(
				'claim_purchase_id'	=> $purchase_id,
				'movement_id'		=> $value['group_id'],
			);
			array_push($staff_movements,$movement);
		}
		$this->purchase->createMovement($staff_movements);

		$attachments = [];
		foreach($input['attachments'] as $key => $value)
		{
			$temp = array
			(
				'claim_purchase_id'		=> $purchase_id,
				'attachment_name'		=> $value['orig_name'],
				'file_type'				=> $value['file_type'],
				'file_ext'				=> $value['file_ext'],
				'description'			=> $value['description'],
				'location'				=> '/application/storage/claim/traveling/purchase'.$value['orig_name'],
				'unique_id'				=> uniqid(),
				'type'					=> $value['file_type'],
				'is_delete'				=> 0,
			);
			array_push($attachments,$temp);
		}
		$this->purchase->createAttachment($attachments);





		$data = array
		(
			'status'	=> 'success',
			'msg'		=> 'Successfully create traveling purchase claim',
			'input'		=> $input
		);

		echo json_encode($data);
		return true;
	}

	function createSubsistence()
	{
		$input = $this->input->post();
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}



		if(!empty($input['type']) && $input['type'] == 1)
		{
			//international traveling 
			//only have one type of allowance 

			$subsistence = array
			(
				'claim_id'			=> $input['claim_id'],
				'date_from'			=> date('Y-m-d',strtotime($input['date_from'])),
				'date_to'			=> date('Y-m-d',strtotime($input['date_to'])),
				'location'			=> $input['location'],
				'amount'			=> $input['amount'],
				'amount_approved'	=> 0,
				'is_admin_approved' => 0,
				'is_hod_approved'	=> 0,
				'hod_remarks'		=> '',
				'admin_remarks'		=> '',
				'type'				=> $input['type'],
				'allowance'			=> 'TRAVEL',
				'is_delete'			=> 0,
				'delete_by'			=> null,
			);
			$claim_subsistence_id = $this->subsistence->create($subsistence);
			$staff_movements = [];
			foreach($input['staff_movements'] as $key => $value)
			{
				$movement = array
				(
					'claim_subsistence_id'	=> $claim_subsistence_id,
					'movement_id'			=> $value['group_id']
				);
				array_push($staff_movements,$movement);
			}
			$this->subsistence->createMovement($staff_movements);
		}else{
			//local traveling 
			//have two type of allowance need to be separate into meals and outstation

			
			/**
			 * 1. store value for outstation allowance
			 */
			$subsistence = array
			(
				'claim_id'			=> $input['claim_id'],
				'date_from'			=> date('Y-m-d',strtotime($input['date_from'])),
				'date_to'			=> date('Y-m-d',strtotime($input['date_to'])),
				'location'			=> $input['location'],
				'amount'			=> $input['outstation_allowance'],
				'amount_approved'	=> 0,
				'is_admin_approved' => 0,
				'is_hod_approved'	=> 0,
				'hod_remarks'		=> '',
				'admin_remarks'		=> '',
				'type'				=> $input['type'],
				'allowance'			=> 'OUTSTATION',
				'is_delete'			=> 0,
				'delete_by'			=> null,
			);
			$claim_subsistence_id = $this->subsistence->create($subsistence);

			$staff_movements = [];
			foreach($input['staff_movements'] as $key => $value)
			{
				$movement = array
				(
					'claim_subsistence_id'	=> $claim_subsistence_id,
					'movement_id'			=> $value['group_id']
				);
				array_push($staff_movements,$movement);
			}
			$this->subsistence->createMovement($staff_movements);


			/**
			 * 2. store value for meals allowance
			 */
			$subsistence = array
			(
				'claim_id'			=> $input['claim_id'],
				'date_from'			=> date('Y-m-d',strtotime($input['date_from'])),
				'date_to'			=> date('Y-m-d',strtotime($input['date_to'])),
				'location'			=> $input['location'],
				'amount'			=> $input['meal_allowance'],
				'amount_approved'	=> 0,
				'is_admin_approved' => 0,
				'is_hod_approved'	=> 0,
				'hod_remarks'		=> '',
				'admin_remarks'		=> '',
				'type'				=> $input['type'],
				'allowance'			=> 'MEALS',
				'is_delete'			=> 0,
				'delete_by'			=> null,
			);
			$claim_subsistence_id = $this->subsistence->create($subsistence);

			$staff_movements = [];
			foreach($input['staff_movements'] as $key => $value)
			{
				$movement = array
				(
					'claim_subsistence_id'	=> $claim_subsistence_id,
					'movement_id'			=> $value['group_id']
				);
				array_push($staff_movements,$movement);
			}
			$this->subsistence->createMovement($staff_movements);
		}


		$data = array
		(
			'status' => 'success',
			'msg'	 => 'Successfuly create subsistence claim',
			'input'	 => $input
		);
		echo json_encode($data);return true;
	}

	function approveSubsistence()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		
		$input = $this->input->post();
	
		$update = array
		(
			'is_admin_approved' 		=> $input['status'],
			'amount_approved' 			=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'			=> (!empty($input['reason']))?$input['reason']:0,
		);
		$where = array('id' => $input['approve_id']);

		$this->subsistence->updateSubsistence($update,$where);
		echo json_encode(array('status' => 'success','msg' => 'Successfully update subsistence allowance'));		
	}

	function removeSubsistence()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'msg'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$id = $this->input->post('id');
		
		$this->subsistence->updateSubsistence(array('is_delete' => 1),array('id' => $id));
		echo json_encode(array('status' => 'success','msg' => 'Successfully remove subsistence claim'));return true;
	}

	function createCall()
	{
		$input = $this->input->post();
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		


		$data = array
		(
			'data' 	=> 'Success',
			'msg'	=> 'Successfully create traveling calls claim',
			'input'	=> $input,
		);

		echo json_encode($data);return true;

	}

	function createParking()
	{
		$input = $this->input->post();
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$arr = array
		(
			'claim_id'				=> $input['claim_id'],
			'date'					=> date('Y-m-d',strtotime($input['date'])),
			'amount'				=> $input['amount'],
			'amount_approved'		=> 0,
			'user_id'				=> $input['user_id'],
			'is_admin_approve'		=> 0,
			'is_hod_approve'		=> 0,
			'hod_remarks'			=> '',
			'admin_remarks'			=>'',
			'is_delete'				=> 0,
			'delete_by'				=> 0,
		);
		$claim_parking_id = $this->parking->create($arr);

		$staff_movements =[];
		foreach($input['staff_movement'] as $key => $value)
		{
			$movement = array
			(
				'claim_parking_id'	=> $claim_parking_id,
				'movement_id'		=> $value['group_id']
			);
			array_push($staff_movements,$movement);
		}
		$this->parking->createMovement($staff_movements);

		$attachments = [];
		foreach($input['attachment'] as $key => $value)
		{
			$attachment = array
			(
				'claim_parking_id' 		=> $claim_parking_id,
				'attachment_name'		=> $value['client_name'],
				'file_type'				=> $value['file_type'],
				'file_ext'				=> $value['file_ext'],
				'description'			=> $value['description'],
				'location'				=> '/application/storage/claim/traveling/parking_charges/'.$value['file_name'],
				'unique_id'				=> uniqid(),
				'type'					=> $value['file_type'],
				'is_delete'				=> 0,
			);
			array_push($attachments,$attachment);
		}
		$this->parking->createAttachment($attachments);


		$data = array
		(
			'status'	=> 'Success',
			'msg'		=> 'Successfully create parking claims',
			'input'		=> $input,
		);
		echo json_encode($data);return true;
	}

	function approveParking()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		
		$input = $this->input->post();
	
		$update = array
		(
			'is_admin_approve' 			=> $input['status'],
			'amount_approved' 			=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'				=> (!empty($input['reason']))?$input['reason']:0,
		);
		$where = array('id' => $input['approve_id']);
		$this->parking->updateParking($update,$where);
		echo json_encode(array('status' => 'success','msg' => 'Parking'));		
	}

	function removeParking()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'msg'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$id = $this->input->post('id');
		$this->parking->updateParking(array('is_delete' => 1),array('id' => $id));
		echo json_encode(array('status' => 'success','msg' => 'Successfully remove parking claim'));return true;
	}


	function removePetrol()
	{
		$this->load->model('model_claim_petrol','petrol');
		$id = $this->input->post('id');
		$this->petrol->updatePetrol(array('is_delete' => 1),array('id' => $id));
		echo json_encode(array('status' => 'success','msg' => 'Successfully remove petrol claim'));return true;
	}

	function removeEntertainment()
	{
		$this->load->model('model_claim_entertainment','entertainment');
		$id = $this->input->post('id');
		$this->entertainment->update_entertainment(array('is_delete' => 1),array('id' => $id));
		echo json_encode(array('status' => 'success','msg' => 'Successfully remove entertainment claim'));return true; 
	}

	function createToll()
	{
		$input = $this->input->post();
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$arr = array
		(
			'claim_id'				=> $input['claim_id'],
			'date'					=> date('Y-m-d',strtotime($input['date'])),
			'amount'				=> $input['amount'],
			'amount_approved'		=> 0,
			'user_id'				=> $input['user_id'],
			'is_admin_approve'		=> 0,
			'is_hod_approve'		=> 0,
			'hod_remarks'			=> '',
			'admin_remarks'			=>'',
			'is_delete'				=> 0,
			'delete_by'				=> 0,
		);
		$claim_toll_id = $this->toll->create($arr);

		$staff_movements =[];
		foreach($input['staff_movement'] as $key => $value)
		{
			$movement = array
			(
				'claim_toll_id'	=> $claim_toll_id,
				'movement_id'		=> $value['group_id']
			);
			array_push($staff_movements,$movement);
		}
		$this->toll->createMovement($staff_movements);

		$attachments = [];
		foreach($input['attachment'] as $key => $value)
		{
			$attachment = array
			(
				'claim_toll_id' 		=> $claim_toll_id,
				'attachment_name'		=> $value['orig_name'],
				'file_type'				=> $value['file_type'],
				'file_ext'				=> $value['file_ext'],
				'description'			=> $value['description'],
				'location'				=> '/application/storage/claim/traveling/toll_charges/'.$value['file_name'],
				'unique_id'				=> uniqid(),
				'type'					=> $value['file_type'],
				'is_delete'				=> 0,
			);
			array_push($attachments,$attachment);
		}
		$this->toll->createAttachment($attachments);


		$data = array
		(
			'status'	=> 'Success',
			'msg'		=> 'Successfully create toll claims',
			'input'		=> $input,
		);
		echo json_encode($data);return true;
	}

	function approveTolls()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		
		$input = $this->input->post();
	
		$update = array
		(
			'is_admin_approve' 		=> $input['status'],
			'amount_approved' 		=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'			=> (!empty($input['reason']))?$input['reason']:'',
		);
		$where = array('id' => $input['approve_id']);
		$this->toll->updateToll($update,$where);
		echo json_encode(array('status' => 'success','msg' => 'Successfully update toll status'));				
	}

	function removeToll()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'msg'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$id = $this->input->post('id');
	
		$this->toll->updateToll(array('is_delete' => 1),array('id' => $id));
		echo json_encode(array('status' => 'success','msg' => 'Successfully remove toll claim'));return true;
	}


	// approve petrol and remove petrol
	function approvePetrol()
	{
		$this->load->model('model_claim_petrol','petrol');
		$input = $this->input->post(); 

		$update = array
		(
			'is_admin_approve' 	=> $input['status'],
			'amount_approved' 	=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'		=> (!empty($input['reason']))?$input['reason']:'',
		);

		$this->petrol->updatePetrol($update,array('id' => $this->input->post('approve_id')));
		echo json_encode(array('status' =>'success','msg' => 'Successfully update petrol status'));
	}


	//approve entertainment and remove entertainment
	function approveEntertainment()
	{
		$this->load->model('model_claim_entertainment','entertainment');
		$input = $this->input->post(); 

		$update = array
		(
			'is_approve' 		=> $input['status'],
			'amount_approved' 	=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'		=> (!empty($input['reason']))?$input['reason']:'',
		);
		$this->entertainment->update_entertainment($update,array('id' => $this->input->post('approve_id')));
		echo json_encode(array('status' => 'ok'));
	}


	function createAirportTaxes()
	{
		$input = $this->input->post();
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$arr = array
		(
			'claim_id'				=> $input['claim_id'],
			'date'					=> date('Y-m-d',strtotime($input['date'])),
			'amount'				=> $input['amount'],
			'amount_approved'		=> 0,
			'is_admin_approve'		=> 0,
			'is_hod_approve'		=> 0,
			'hod_remarks'			=> '',
			'admin_remarks'			=>'',
			'is_delete'				=> 0,
			'delete_by'				=> 0,
		);
		$claim_airport_id = $this->airport->create($arr);

		$staff_movements =[];
		foreach($input['staff_movement'] as $key => $value)
		{
			$movement = array
			(
				'claim_airport_id'	=> $claim_airport_id,
				'movement_id'		=> $value['group_id']
			);
			array_push($staff_movements,$movement);
		}
		$this->airport->createMovement($staff_movements);

		$attachments = [];
		foreach($input['attachment'] as $key => $value)
		{
			$attachment = array
			(
				'claim_airport_id' 		=> $claim_airport_id,
				'attachment_name'		=> $value['client_name'],
				'file_type'				=> $value['file_type'],
				'file_ext'				=> $value['file_ext'],
				'description'			=> $value['description'],
				'location'				=> '/application/storage/claim/traveling/airport_taxes/'.$value['orig_name'],
				'unique_id'				=> uniqid(),
				'type'					=> $value['file_type'],
				'is_delete'				=> 0,
			);
			array_push($attachments,$attachment);
		}
		$this->airport->createAttachment($attachments);


		$data = array
		(
			'status'	=> 'Success',
			'msg'		=> 'Successfully create parking claims',
			'input'		=> $input,
		);
		echo json_encode($data);return true;
	}

	function createServiceTaxes()
	{
		$input = $this->input->post();
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$arr = array
		(
			'claim_id'				=> $input['claim_id'],
			'date'					=> date('Y-m-d',strtotime($input['date'])),
			'amount'				=> $input['amount'],
			'amount_approved'		=> 0,
			'is_admin_approve'		=> 0,
			'is_hod_approve'		=> 0,
			'hod_remarks'			=> '',
			'admin_remarks'			=> '',
			'is_delete'				=> 0,
			'delete_by'				=> 0,
		);
		$claim_service_id = $this->service->create($arr);

		$staff_movements =[];
		foreach($input['staff_movement'] as $key => $value)
		{
			$movement = array
			(
				'claim_service_id'	=> $claim_service_id,
				'movement_id'		=> $value['group_id']
			);
			array_push($staff_movements,$movement);
		}
		$this->service->createMovement($staff_movements);

		$attachments = [];
		foreach($input['attachment'] as $key => $value)
		{
			$attachment = array
			(
				'claim_service_id' 		=> $claim_service_id,
				'attachment_name'		=> $value['client_name'],
				'file_type'				=> $value['file_type'],
				'file_ext'				=> $value['file_ext'],
				'description'			=> $value['description'],
				'location'				=> '/application/storage/claim/traveling/airport_taxes/'.$value['orig_name'],
				'unique_id'				=> uniqid(),
				'type'					=> $value['file_type'],
				'is_delete'				=> 0,
			);
			array_push($attachments,$attachment);
		}
		$this->service->createAttachment($attachments);


		$data = array
		(
			'status'	=> 'Success',
			'msg'		=> 'Successfully create parking claims',
			'input'		=> $input,
		);
		echo json_encode($data);return true;
	}

	function createTipsAndPortage()
	{
		$input = $this->input->post();
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$arr = array
		(
			'claim_id'				=> $input['claim_id'],
			'date'					=> date('Y-m-d',strtotime($input['date'])),
			'amount'				=> $input['amount'],
			'amount_approved'		=> 0,
			'is_admin_approve'		=> 0,
			'is_hod_approve'		=> 0,
			'hod_remarks'			=> '',
			'admin_remarks'			=> '',
			'is_delete'				=> 0,
			'delete_by'				=> 0,
		);
		$claim_service_id = $this->service->create($arr);

		$staff_movements =[];
		foreach($input['staff_movement'] as $key => $value)
		{
			$movement = array
			(
				'claim_service_id'	=> $claim_service_id,
				'movement_id'		=> $value['group_id']
			);
			array_push($staff_movements,$movement);
		}
		$this->service->createMovement($staff_movements);

		$attachments = [];
		foreach($input['attachment'] as $key => $value)
		{
			$attachment = array
			(
				'claim_service_id' 		=> $claim_service_id,
				'attachment_name'		=> $value['client_name'],
				'file_type'				=> $value['file_type'],
				'file_ext'				=> $value['file_ext'],
				'description'			=> $value['description'],
				'location'				=> '/application/storage/claim/traveling/airport_taxes/'.$value['orig_name'],
				'unique_id'				=> uniqid(),
				'type'					=> $value['file_type'],
				'is_delete'				=> 0,
			);
			array_push($attachments,$attachment);
		}
		$this->service->createAttachment($attachments);

		$data = array
		(
			'status'	=> 'Success',
			'msg'		=> 'Successfully create parking claims',
			'input'		=> $input,
		);
		echo json_encode($data);return true;
	}

	function createLaundry()
	{
		$input = $this->input->post();
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$arr = array
		(
			'claim_id'			=> $input['claim_id'],
			'date_from'			=> date('Y-m-d',strtotime($input['date_from'])),
			'date_to'			=> date('Y-m-d',strtotime($input['date_to'])),
			'amount'			=> $input['amount'],
			'amount_approved'	=> 0,
			'is_admin_approve'	=> 0,
			'is_hod_approve'	=> 0,
			'hod_remarks'		=> '',
			'admin_remarks'		=> '',
			'is_delete'			=> 0,
			'delete_by'			=> 0,
		);
		$claim_laundry_id = $this->laundry->create($arr);

		$staff_movements = [];
		foreach($input['staff_movement'] as $key => $value)
		{
			$movement = array
			(
				'claim_laundry_id'		=> $claim_laundry_id,
				'movement_id'			=> $value['group_id'],
			);
			array_push($staff_movements,$movement);
		}
		$this->laundry->createMovement($staff_movements);

		$attachments = [];
		foreach($input['attachment'] as $key => $value)
		{
			$attachment = array
			(
				'claim_laundry_id'	=> $claim_laundry_id,
				'attachment_name'	=> $value['file_name'],
				'file_type'			=> $value['file_type'],
				'file_ext'			=> $value['file_ext'],
				'description'		=> $value['description'],
				'location'			=> '/application/storage/claim/traveling/laundry/'.$value['file_name'],
				'unique_id'			=> uniqid(),
				'type'				=> $value['file_type'],
				'is_delete'			=> 0,
			);
			array_push($attachments,$attachment);
		}
		$this->laundry->createAttachment($attachments);

		$data = array	
		(
			'status'	=> 'success',
			'msg'		=> 'Successfully create laundry claims',
			'input'		=> $input
		);
		echo json_encode($data);return true;
	}

	function createExcessBaggage()
	{
		$input = $this->input->post();
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$excess_baggage = array
		(
			'claim_id'			=> $input['claim_id'],
			'date'				=> date('Y-m-d',strtotime($input['date'])),
			'amount'			=> $input['amount'],
			'amount_approved'	=> 0,
			'is_admin_approve'	=> 0,
			'is_hod_approve'	=> 0,
			'hod_remarks'		=> '',
			'admin_remarks'		=> '',
			'is_delete'			=> 0,
			'delete_by'			=> 0,
		);
		$claim_excess_baggage_id = $this->excess_baggage->create($excess_baggage);

		$attachments = [];
		foreach($input['attachment'] as $key => $value)
		{
			$attachment = array
			(
				'claim_excess_baggage_id'	=> $claim_excess_baggage_id,
				'attachment_name'			=> $value['file_name'],
				'file_type'					=> $value['file_type'],
				'file_ext'					=> $value['file_ext'],
				'description'				=> $value['description'],
				'location'					=> '/application/storage/claim/traveling/excess_baggage/'.$value['file_name'],
				'unique_id'					=> uniqid(),
				'type'						=> $value['file_type'],
				'is_delete'					=> 0,	
			);
			array_push($attachments,$attachment);
		}
		$this->excess_baggage->createAttachment($attachments);

		$staff_movements = [];
		foreach($input['staff_movement'] as $key => $value)
		{
			$movement = array
			(
				'movement_id'				=> $value['group_id'],
				'claim_excess_baggage_id'	=> $claim_excess_baggage_id,
			);
			array_push($staff_movements,$movement);
		}
		$this->excess_baggage->createMovement($staff_movements);

		$data = array
		(
			'status'	=> 'success',
			'msg'		=> 'Successfully create excess baggage claims',
			'input'		=> $input
		);
		echo json_encode($data);return true;
		
	}

	function createLossForex()
	{
		$input = $this->input->post();
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$forex = array
		(
			'claim_id'			=> $input['claim_id'],
			'date'				=> date('Y-m-d',strtotime($input['date'])),
			'amount'			=> $input['amount'],
			'amount_approved'	=> 0,
			'is_admin_approve'	=> 0,
			'is_hod_approve'	=> 0,
			'hod_remarks'		=> '',
			'admin_remarks'		=> '',
			'is_delete'			=> 0,
			'delete_by'			=> 0,
		);
		$forex_claim_id = $this->forex->create($forex);


		$attachments = [];
		foreach($input['attachment'] as $key => $value)
		{
			$attachment = array
			(
				'claim_forex_id'	=> $forex_claim_id,
				'attachment_name'	=> $value['file_name'],
				'file_type'			=> $value['file_type'],
				'file_ext'			=> $value['file_ext'],
				'description'		=> $value['description'],
				'location'			=> '/application/storage/claim/traveling/loss_forex/'.$value['file_name'],
				'unique_id'			=> uniqid(),
				'type'				=> $value['file_type'],
				'is_delete'			=> 0,
			);
			array_push($attachments,$attachment);
		}
		$this->forex->createAttachment($attachments);

		$staff_movements = [];
		foreach($input['staff_movement'] as $key => $value)
		{
			$movement = array
			(
				'claim_forex_id'	=> $forex_claim_id,
				'movement_id'		=> $value['group_id']
			);
			array_push($staff_movements,$movement);
		}
		$this->forex->createMovement($staff_movements);
		
		$data = array
		(
			'status'	=> 'success',
			'msg'		=> 'Successfully create loss in foreign exchange claims',
			'input'		=> $input
		);
		echo json_encode($data);return true;
	}

	function createMeal()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$date 			= $this->input->post('date');
		$amount_claim 	= $this->input->post('amount_claim');

		$meal_claim = json_decode($this->input->post('form'));
		

		$meal_input = array(
			'claim_id' 				=> $this->input->post('claim_id'),
			'date' 					=> date('Y-m-d',strtotime($date)),
			'restaurant_name'		=> '',
			'amount_charge'			=> 0,
			'amount_claim'			=> $amount_claim,
			'is_approve'			=> 0,
			'amount_approved'		=> 0,
			'is_delete'				=> 0,
		);

		$meal_id = $this->meal->createClaim($meal_input);
		$user_id = $this->input->post('user');
		$staff_movements = json_decode($this->input->post('staff_movement'));

		if(!empty($meal_id))
		{
			$insert_data = array();
			foreach ($staff_movements as $key => $movement) 
			{	
				$temp_data = array
				(
					'meals_id' 		=> $meal_id,
					'movement_id'	=> $movement->id,
					'is_delete'		=> 0
				);
				array_push($insert_data,$temp_data);
			}
			//bulk insert 
			$this->db->insert_batch('hr__claim_meals_movement',$insert_data);
		}
		echo json_encode($this->input->post());return true;
	}

	function removeMeal()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

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

		$this->meal->removeMeal($id);
		echo json_encode(array('status' => 'success','message' => 'Successfully remove meal allowance'));return true;
	}

	function approveMeals()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$input = $this->input->post();


		$update = array(
			'is_approve' 		=> $input['status'],
			'amount_approved' 	=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'		=> (!empty($input['reason']))?$input['reason']:'',
			'approved_date' 	=> date('Y-m-d'),
			'approved_by' 		=> $this->user_id
		);
		$where = array('id' => $input['approve_id']
		);

		$this->meal->updateMeal($update,$where);
		echo json_encode(array('status'=>'success','msg' => 'Successfully change meals claim status'));return true;
	}

	function createTrainer()
	{
		$input = $this->input->post();
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$start_time = date("G:i", strtotime($input['start']));
		$end_time = date("G:i",strtotime($input['end']));

		$diff = (strtotime('2020-01-01'.$input['end']) - strtotime('2020-01-01'.$input['start']))/3600;
		debug($diff);

		if($diff >= 1)
		{
			$amount = ($diff >= 4)?(200):((explode('.',$diff)[0]) * 50);
			// $amount = 200;
			$data = array
			(
				'claim_id'				=> $input['claim_id'],
				'date'					=> date('Y-m-d',strtotime($input['date'])),
				'start_at'				=> $start_time,
				'end_at'				=> $end_time,
				'title'					=> $input['title'],
				'type'					=> $input['type'],
				'movements'				=> serialize($input['movements']),
				'amount'				=> $amount,
				'amount_approved'		=> 0,
				'is_admin_approve'		=> 0,
				'is_hod_approve'		=> 0,
				'hod_remarks'			=> '',
				'admin_remarks'			=> '',
				'is_delete'				=> 0,
				'delete_by'				=> 0,
			);

			$trainer_id = $this->trainer->create($data);

			if(!empty($trainer_id))
			{
				foreach ($input['attachment'] as $key => $value) 
				{
					$att = array
					(
						'claim_trainer_id'		=> $trainer_id,
						'attachment_name'		=> $value['orig_name'],
						'file_type'				=> $value['file_type'],
						'file_ext'				=> $value['file_ext'],
						'description'			=> $value['description'],
						'location'				=> 'application/storage/claim/trainer/'.$value['file_name'],
						'unique_id'				=> uniqid(),
						'type'					=> $value['file_type'],
						'is_delete'				=> 0,
					);
					$this->trainer->createAttachment($att);
				}
			}

			$data = array
			(
				'status' 	=> 'success',
				'msg'		=> 'successfully create items',
				'input'		=> $input,
			);
			echo json_encode($data);return true;

		}else{
			
			$data = array
			(
				'status' 	=> 'error',
				'msg'		=> 'Need to be more than 4 hours',
				'input'		=> $input,
			);
			echo json_encode($data);return true;
		}
	}

	function approveTrainer()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		
		$input = $this->input->post();
	
		$update = array
		(
			'is_admin_approve' 			=> $input['status'],
			'amount_approved' 			=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'				=> ($input['reason'])?$input['reason']:'',
		);
		$where = array('id' => $input['approve_id']);
		$this->trainer->updateClaim($update,$where);

		echo json_encode(array('status' => 'success', 'msg' => 'Successfully update trainer / facilitator claim status'));
	}

	function removeTrainer()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'msg'		=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$id = $this->input->post('id');
		
		$this->trainer->updateClaim(array('is_delete' => 1),array('id' => $id));
		echo json_encode(array('status' => 'success','msg' => 'Successfully remove trainer / facilitator claim'));return true;
	}

	function createOtherClaim()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$input 	= $this->input->post();
		$form 	= json_decode($input['form']);
		$attachment = $input['attachment'];

		$other_input = array
		(
			'claim_id'			=> $input['claim_id'],
			'date'				=> date('Y-m-d',strtotime($form->date)),
			'client_id'			=> 0,
			'description'		=> $form->description,
			'amount_charge'		=> 0,
			'amount_claim'		=> $form->amount_charge,
			'is_approve'		=> 0,
			'amount_approved'	=> 0,
			'approved_date'		=> date('Y-m-d'),
			'approved_by'		=> 0,
			'is_hod_approved'	=> 0,
			'approved_hod_by'	=> 0,
			'hod_remarks'		=> '',
			'admin_remarks'		=> '',
			'type'				=> $form->type_other,
			'is_delete'			=> 0,
			'delete_by'			=> 0,
		);
		$otherId = $this->other->createClaim($other_input);

		if($otherId)
		{
			$att_input = array();
			foreach ($attachment as $key => $row) {
				$container = array(
					'other_claim_id'	=> $otherId,
					'attachment_name'	=> $row['orig_name'],
					'file_type'			=> $row['file_type'],
					'file_ext'			=> str_replace('.', '', $row['file_ext']),
					'description'	 	=> $row['description'],
					'location'			=> 'storage/claim/others/'.$row['file_name'],
					'unique_id'			=> time().uniqid(),
					'type'				=> $row['file_type'],
					);
				array_push($att_input, $container);
			}
			$this->other->createAttachment($att_input);
		}

		$data 	= array
		(
			'status' 	=> 'success',
			'msg'		=> 'Successfully create other claims',
			'input'		=> $input,
			'form'		=> $form,
		);

		echo json_encode($data);return true;
	}

	function removeOther()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

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

		$this->other->removeOtherClaim($id);
		echo json_encode(array('status' => 'success'));return true;
	}

	function approveOthers()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$input = $this->input->post();


		$update = array
		(
			'is_approve' 		=> $input['status'],
			'amount_approved' 	=> $input['amount_approve'],
			'approved_date' 	=> date('Y-m-d'),
			'admin_remarks'		=> (!empty($input['reason']))?$input['reason']:'',
			'approved_by' 		=> $this->user_id
		);

		$where = array('id' => $input['approve_id']);

		$this->other->updateOtherClaim($update,$where);
		echo json_encode(array('status'=>'success','msg' => 'Successfully change other claim status'));return true;
	}

	function createTravelClaim()
	{

		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'error',
				'msg'		=> 'Failed to create mileage claim.Please log out and login again.'
			);
			echo json_encode($data);
			return true;
		}

		$main_form 					= json_decode($this->input->post('form'));
		$staff_movements 			= (!empty($this->input->post('staff_movements'))?$this->input->post('staff_movements'):null);
		$routes 					= (!empty($this->input->post('routes'))?$this->input->post('routes'):null);	
		$attachments 				= (!empty( $this->input->post('attachments'))? $this->input->post('attachments'):null);

		$input = array
		(
			'date'					=> (!empty($main_form->date))?$main_form->date:null,
			'claim_id'				=> (!empty($this->input->post('claim_id')))?$this->input->post('claim_id'):null,
			'client'				=> '',
			'task'					=> (!empty($main_form->task))?$main_form->task:null,
			'mileage_amount'		=> $this->__calculate_mileage($routes),
		);
		
		$travelId 					= $this->createTravel($input);

		if (!empty($travelId)) 
		{
			$data = array();
			$route_input = array();
			if(!empty($routes)) foreach ($routes as $key => $route) 
			{
				$r_arr = array(
					'travel_id'		=> $travelId,
					'from' 			=> $route['from'],
					'to'			=> $route['to'],
					'distance' 		=> $this->googleDistanceToKm($route['distance']),
					'vehicle_id'	=> $route['vehicle_id'],
				);
				array_push($route_input,$r_arr);
			}
			if(!empty($route_input))
			{
				$this->travel->createRoute($route_input);
			}
			$attachment_input = array();
			if(!empty($attachments)) foreach ($attachments as $key => $attachment) 
			{
				$json = json_decode($attachment);
				$a_arr = array(
					'travelling_id' 	=> $travelId,
					'attachment_name'	=> $json->orig_name,
					'file_type'			=> $json->file_type, 
					'file_ext'			=> $json->file_ext,
					'description'		=> $json->description,
					'location'			=> '/application/storage/claim/traveling/mileage/'.$json->file_name,
					'unique_id'			=> uniqid(),
					'type'				=> $json->file_type,
					'is_delete'			=> 0,
				);
				array_push($attachment_input,$a_arr);
			}
			
			if(!empty($attachment_input))
			{
				$this->travel->createAttachment($attachment_input);
			}

			$data = array
			(
				'status'	=> 'success',
				'msg'		=> 'Successfully create mileage claim',
			);
		}else
		{
			$data = array
			(
				'status' 	=> 'error',
				'msg'		=> 'Failed to create mileage claim'
			);
		}

		echo json_encode($data);return true;
	}

	function removeTravel()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

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

		$this->travel->removeTravel($id);
		echo json_encode(array('status' => 'success'));return true;
	}

	function approveTravels()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$input = $this->input->post();


		$update = array
		(
			'status' => $input['status'],
			'amount_approve' => $input['amount_approve'],
			'approved_date' => date('Y-m-d'),
			'admin_remarks'		=> (!empty($input['reason']))?$input['reason']:'',
			'approved_by' => $this->user_id
		);
		$where = array('id' => $input['approve_id']);

		$this->travel->updateTravel($update,$where);
		echo json_encode(array('status'=>'success','msg' => 'Successfully change mileage claim status'));return true;
	}

	/**
	 * version 1.0 
	 * deprecated
	 * ALLOCATION CLAIMS
	 */
	function createAllocation()
	{

		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

		$input 			=	$this->input->post();
		$bool_staff 	=	!empty($input['input']['staff_id']);
		$bool_hosp 		=	(!empty($input['input']['hospitalization_benefit']) && $input['input']['hospitalization_benefit'] != -1);
		$bool_dental 	=	(!empty($input['input']['dental_and_optical']) && $input['input']['dental_and_optical'] != -1);
		$bool_outpatient= 	(!empty($input['input']['outpatient_benefit']) && $input['input']['outpatient_benefit'] != -1);
		$bool_room		= 	(!empty($input['input']['room_package']) && $input['input']['room_package'] != -1);
		// $bool_approver	= 	(!empty($input['input']['approver_id']) && $input['input']['approver_id'] != -1);


		/**
		 * find last date
		 */
		$a_date = '01/'.$input['input']['end_date'];
		$end_of_the_month = date('t',strtotime(str_replace('/','-',$a_date)));

		$bool_start_date= 	(!empty($input['input']['start_date']) && $this->isValidDate(str_replace('/','-','01-'.$input['input']['start_date']),'d-m-Y'));
		$bool_end_date 	= 	(!empty($input['input']['end_date']) && $this->isValidDate(str_replace('/','-',$end_of_the_month.'-'.$input['input']['end_date']),'d-m-Y'));

		if($bool_staff && $bool_hosp && $bool_dental && $bool_outpatient && $bool_room && $bool_start_date && $bool_end_date)
		{

			$sizeStaff = sizeof($input['input']['staff_id']);

			if($sizeStaff == 1)
			{
				$staff_id = $input['input']['staff_id'];
				$input['input']['staff_id'] = array();
				array_push($input['input']['staff_id'],$staff_id);
			}

			$newAllocation 		= array();
			$existedAllocation 	= array();

			foreach ($input['input']['staff_id'] as $key => $staff) {

				$dental_optical_amount 	= $this->claim_type->getClaimById($input['input']['dental_and_optical']);
				$hospitalization_amount = $this->claim_type->getClaimById($input['input']['hospitalization_benefit']);
				$outpatient_amount 		= $this->claim_type->getClaimById($input['input']['outpatient_benefit']);
				$room_amount 			= $this->claim_type->getClaimById($input['input']['room_package']);

				//change this function
				$isExist = $this->allocation->fetchSingleBetweenDates($staff, str_replace('/','-','01-'.$input['input']['start_date']), str_replace('/','-',$end_of_the_month.'/'.$input['input']['end_date']), 0, 0); 
				if(!$isExist)
				{
					$insert = array(
						'user_id' 									=> $staff,
						'status'									=> $input['input']['status'],
						'created_by'								=> $this->user_id,
						'is_delete'									=> 0
					);

					$datetime1 = date_create('01-'.str_replace('/','-',$input['input']['start_date']));
					$datetime2 = date_create($end_of_the_month.'-'.str_replace('/','-',$input['input']['end_date']));
					$interval = date_diff($datetime1, $datetime2);
					
					$month =  $interval->format('%m months');

					// $d1 = new DateTime('01-'.str_replace('/','-',$input['input']['start_date']));
					// $d2 = new DateTime($end_of_the_month.'-'.str_replace('/','-',$input['input']['end_date']));
					// $month = $d1->diff($d2)->m;

					$isAllocate = $this->allocation->allocate($insert);
					
					if ($isAllocate) 
					{
						//create allocation details
						$insert_detail = array
						(
							'allocation_id'								=> $isAllocate,
							'start_date'								=> date('Y-m-d',strtotime('01-'.str_replace('/','-',$input['input']['start_date']))),
							'end_date'									=> date('Y-m-d',strtotime($end_of_the_month.'-'.str_replace('/','-',$input['input']['end_date']))),
							'month'										=> $month,
							'claim_type_dental_optical_id'				=> $input['input']['dental_and_optical'],
							'claim_type_dental_optical_amount'			=> ($dental_optical_amount->amount/12)*$month,
							'claim_type_dental_optical_prorate_amount' 	=> $dental_optical_amount->amount/12,
							'claim_type_hospitalization_id'				=> $input['input']['hospitalization_benefit'],
							'claim_type_hospitalization_amount' 		=> ($hospitalization_amount->amount),
							'claim_type_outpatient_id'					=> $input['input']['outpatient_benefit'],
							'claim_type_outpatient_amount'				=> ($outpatient_amount->amount/12)*$month,
							'claim_type_outpatient_prorate_amount'		=> $outpatient_amount->amount/12,
							'claim_type_room_package_id'				=> $input['input']['room_package'],
							'claim_type_room_package_amount'			=> ($room_amount->amount),
						);

						$isAllocateDetail = $this->allocation->allocateDetail($insert_detail);
						array_push($newAllocation, $this->allocation->fetchSingle($staff, $input['input']['start_date'], $input['input']['end_date'], 0, 0));
					}

					$data = array(
						'status'					=> 'success',
						'msg'						=> 'successfully create new allocation',
						'new_claim_allocation' 		=> $newAllocation,
						'existing_claim_allocation' => $existedAllocation
					);
				}else{
					array_push($existedAllocation, $isExist);
					$data  = array(
						'status' 		=> 'error',
						'msg'		 	=> 'allocation have already been made between dates interval',
					);
				}
			}
		}else{
			{
				$msg = '';
	
				if(!$bool_staff)$msg .= 'Staff is required';
				if(!$bool_hosp)$msg .= 'Hospitalization is required';
				if(!$bool_dental)$msg .= 'Dental & Optical is required';
				if(!$bool_outpatient)$msg .= 'Outpatient is rquired';
				if(!$bool_room)$msg .= 'Room Package is required';
				if(!$bool_start_date)$msg .= 'Start Month and Year is required';
				if(!$bool_end_date)$msg .= 'End Month And Year is required';
	
				$data['message'] = $data['message'].', '.$msg;
			}
		}
		
		echo json_encode($data);
		return true;
	}

	/**
	 * version 1.0
	 * deprecated
	 */
	function editAllocation()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}

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

		$bool_staff 	=	(!empty($input['input']['user_id']) && $input['input']['user_id'] != -1);
		$bool_hosp 		=	(!empty($input['input']['hospitalization_id']) && $input['input']['hospitalization_id'] != -1);
		$bool_dental 	=	(!empty($input['input']['dental_optical_id']) && $input['input']['dental_optical_id'] != -1);
		$bool_outpatient= 	(!empty($input['input']['outpatient_id']) && $input['input']['outpatient_id'] != -1);
		$bool_room		= 	(!empty($input['input']['room_package_id']) && $input['input']['room_package_id'] != -1);

		$a_date = '01/'.$input['input']['end_date'];
		$end_of_the_month = date('t',strtotime(str_replace('/','-',$a_date)));

		$bool_start_date= 	(!empty($input['input']['start_date']) && $this->isValidDate(str_replace('/','-','01/'.$input['input']['start_date']),'d-m-Y'));
		$bool_end_date 	= 	(!empty($input['input']['end_date']) && $this->isValidDate(str_replace('/','-',$end_of_the_month.'/'.$input['input']['end_date']),'d-m-Y'));

		$data = array
		(
				'status' 			=> 'failed',
				'message'			=> 'Unable to update data',
		);

		
		if($bool_staff && $bool_hosp && $bool_dental && $bool_outpatient && $bool_room && $bool_start_date && $bool_end_date)
		{

			$dental_optical_amount 	= $this->claim_type->getClaimById($input['input']['dental_optical_id']);
			$hospitalization_amount = $this->claim_type->getClaimById($input['input']['hospitalization_id']);
			$outpatient_amount 		= $this->claim_type->getClaimById($input['input']['outpatient_id']);
			$room_amount 			= $this->claim_type->getClaimById($input['input']['room_package_id']);

			$d1 = new DateTime('01-'.str_replace('/','-',$input['input']['start_date']));
			$d2 = new DateTime($end_of_the_month.'-'.str_replace('/','-',$input['input']['end_date']));
			$month = $d1->diff($d2)->m; 

			$where = array
			(
				'allocation_id'	=> $input['input']['id']
			);

			$update = array
			(
				'start_date' => date('Y-m-d',strtotime(str_replace('/','-','01-'.$input['input']['start_date']))),
				'end_date' => date('Y-m-d',strtotime(str_replace('/','-',$end_of_the_month.'/'.$input['input']['end_date']))),
				'month' => $month,
				'claim_type_dental_optical_id' => $input['input']['dental_optical_id'],
				'claim_type_dental_optical_amount' => $dental_optical_amount->amount,
				'claim_type_dental_optical_prorate_amount' => $dental_optical_amount->amount/12,
				'claim_type_hospitalization_id' => $input['input']['hospitalization_id'],
				'claim_type_hospitalization_amount' => $hospitalization_amount->amount,
				'claim_type_outpatient_id'	=> $input['input']['outpatient_id'],
				'claim_type_outpatient_amount' => $outpatient_amount->amount,
				'claim_type_outpatient_prorate_amount' => $outpatient_amount->amount/12,
				'claim_type_room_package_id'=> $input['input']['room_package_id'],
				'claim_type_room_package_amount'=> $room_amount->amount,
			);

			$isUpdated = $this->allocation->updateDetailAllocation($update, $where);
			
			if ($isUpdated) 
			{
				$data = array
				(
					'status' => 'success',
					'message'=> 'successfully update data for allocation : '+$input['input']['id'],
				);
			}
			
		}else
		{
			$msg = '';

			if(!$bool_staff)$msg .= 'Staff is required';
			if(!$bool_hosp)$msg .= 'Hospitalization is required';
			if(!$bool_dental)$msg .= 'Dental & Optical is required';
			if(!$bool_outpatient)$msg .= 'Outpatient is rquired';
			if(!$bool_room)$msg .= 'Room Package is required';
			if(!$bool_start_date)$msg .= 'Start Month and Year is required';
			if(!$bool_end_date)$msg .= 'End Month And Year is required';

			$data['message'] = $data['message'].', '.$msg;
		}

		echo json_encode($data);
		return true;
	}

	/**
	 * version 1.0 & version 2.0
	 */
	function removeAllocation()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}


		$update 	= array(
			'is_delete' 	=> 1,
			'deleted_by'	=> $this->user_id,
			'deleted_at'	=> date('Y-m-d G:i:s'),
		);

		$where = $this->input->post('allocation_id');
		$isRemove 	= $this->allocation->removeAllocation($where,$update);


		if($isRemove){
			$data = array(
				'status' => 'success',
				'message'=> 'successfully removed allocation'
				);
		}else{
			$data = array(
				'status' => 'failed',
				'message'=> 'unable to removed allocation'
				);
		}

		echo json_encode($data);
		return true;
	}

	function filter_panel()
	{
		$input = $this->input->post();
		$results = $this->panel->filter_claim($input['year'] , $input['month'], $input['clinic']);
		print json_encode($results);
		return true;
	}
	
	/**
	 * UTIL
	 */
	private function isValidDate($date,$format = 'd-m-Y')
	{
		$d = DateTime::createFromFormat($format, $date);
    	return $d && $d->format($format) == $date;
	}

	/**
	 * TRAVEL UTIL  
	 */
	private function amountTravel($group)
	{
		$total = 0;
		foreach($group as $key => $value)
		{
			$total += $value['amount_claim'];
		}
		return $total;
	}

	private function createTravel($input = null)
	{
		if(empty($input['date']))
		{
			return false;
		}

		$data = array
		(
			'travelling_date' 	=> (!empty($input['date']))?date('Y-m-d',strtotime($input['date'])):null,
			'claim_id'			=> (!empty($input['claim_id']))?$input['claim_id']:0,
			// 'client'			=> (!empty($input['client']))?$input['client']:null,
			'task'				=> (!empty($input['task']))?$input['task']:null,
			'mileage_amount'	=> (!empty($input['mileage_amount']))?$input['mileage_amount']:null,
			'status'			=> 0,
			'is_delete' 		=> 0,
		);

		$travel_id = $this->travel->createTravel($data);
		return $travel_id;
	}

	/**
	 * version 1.0 :
	 * recently broken not sure what cause the error
	 * start :
	 */
	private function googleDistanceToKm($gdistance)
	{
		if(strpos($gdistance,','))
		{
			$gdistance = str_replace(',','',$gdistance);
		}

		if(strpos($gdistance, 'km')){
			$distance = trim(str_replace('km','', $gdistance));
		}else if(strpos($gdistance, 'm')){
			$distance = trim(str_replace('m','', $gdistance));
			$distance = $distance/1000;
		}else{
			$distance = trim($gdistance);
		}

		return $distance;
	}

	private function groupVehicleId($routes)
	{
		$this->load->helper('file');
		$i = 0;
		$log_path = APPPATH.'/storage/log/claim/claim_group_vehicle_id.php';

		$return = array();
		foreach($routes as $key => $value)
		{
			$temp = array
			(
				'vehicle_id'	=> $value['vehicle_id'],
				'distance'		=> $this->googleDistanceToKm($value['distance']),
			);
			$temp['amount_claim'] = ($this->amountClaimTravel($temp['distance'],$temp['vehicle_id']))? $this->amountClaimTravel($temp['distance'],$temp['vehicle_id']):0;
			
			$string 	= read_file($log_path).PHP_EOL;
			$content 	= $string.'amount claim 1 ('.$i.'): '.$temp['amount_claim'].PHP_EOL.'distance: '.$temp['distance'].PHP_EOL.'vehicle id : '.$temp['vehicle_id'].PHP_EOL;
			write_file($log_path,$content);

			if(sizeof($return) <= 0)
			{
				array_push($return,$temp);
			}else
			{
				$is_vehicle_id_new = true;
				foreach($return as $key => $value)
				{
					if($value['vehicle_id'] == $temp['vehicle_id'])
					{
						$is_vehicle_id_new = false;
						$new_temp = array
						(
							'vehicle_id'	=> $value['vehicle_id'],
							'distance'		=> $this->googleDistanceToKm($value['distance'])+$temp['distance'],
						);
						$new_temp['amount_claim'] = ($this->amountClaimTravel($new_temp['distance'],$new_temp['vehicle_id']))? $this->amountClaimTravel($new_temp['distance'],$new_temp['vehicle_id']):0;
					
						$string 	= read_file($log_path).PHP_EOL;
						$content 	= $string.'amount claim 2 ('.$i.'): '.$new_temp['amount_claim'].PHP_EOL.'distance: '.$new_temp['distance'].PHP_EOL.'vehicle id : '.$new_temp['vehicle_id'].PHP_EOL;
						write_file($log_path,$content);

						// $return[$key] = $new_temp;
						array_push($return,$new_temp);
					}
				}
				if($is_vehicle_id_new)
				{
					array_push($return,$temp);
				}
			}
		}
		return $return;
	}
	
	private function amountClaimTravel($km,$vehicle)
	{
		$total = 0;
		$bal_km = $km;
		$rate = $this->travel_rate->fetchRate($vehicle);

		foreach($rate as $key => $value)
		{
			if($value->rate_km == 0 && $bal_km != 0)
			{
				$total += $bal_km * $value->rate_amount;$bal_km = 0;
			}else{
				if($value->rate_km >= $bal_km)
				{
					$total += ($bal_km * $value->rate_amount);
					$bal_km = 0;
				}else
				{
					$new_bal = $bal_km - $value->rate_km;
					if($new_bal <= 0)
					{
						$total += ($bal_km * $value->rate_amount);
						$bal_km = 0;
						break;
					}else
					{
						$total += ($value->rate_km * $value->rate_amount);
						$bal_km = $new_bal;
					}
				}
			}
		}

		return $total;
	}
	/**
	 * version 1.0
	 * end : 
	 */

	 
	/**
	 * version 2.0
	*/
	private function __calculate_mileage($routes)
	{
		$group_vehicles	 	= $this->__group_vehicle($routes);
		$total_claim = 0;
		foreach ($group_vehicles as $key => $group) 
		{
			$total_claim = $total_claim + $this->amountClaimTravel($group['distance'],$group['id']);
		}
		return $total_claim;
	}

	private function __group_vehicle($routes)
	{
		$vehicles = array();
		foreach ($routes as $key => $route) 
		{
			if(empty($vehicles))
			{
				$vehicle = array
				(
					'id' 			=> $route['vehicle_id'], 
					'distance'		=> $this->googleDistanceToKm($route['distance']),
				);
				array_push($vehicles,$vehicle);
			}else{
				$bool_create_new = true;
				foreach ($vehicles as $inner_key => $row) 
				{
					if($vehicle['id'] == $route['vehicle_id'])
					{
						$bool_create_new = false;
						$vehicles[$inner_key]['distance'] = $vehicles[$inner_key]['distance'] + $this->googleDistanceToKm($route['distance']);
					}
				}

				if($bool_create_new)
				{
					$vehicle = array
					(
						'id' 		=> $route['vehicle_id'],
						'distance' 	=> $this->googleDistanceToKm($route['distance']),
					);
					array_push($vehicles,$vehicle);
				}
			}
		}
		return $vehicles;
	}

	public function createDressing()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		// debug($this->input->post('claim_id'));
		// exit();
		$claim_id 		= $this->input->post('claim_id');
		$claim_dressing = json_decode($this->input->post('form'));

		$attachment 	= $this->input->post('attachment');
		$year 			= $this->input->post('year');
		$month 			= $this->input->post('month');
		$user 			= $this->input->post('user');
		
		$year 	= date('Y',strtotime($claim_dressing->dressing_date));
		$month 	= date('m',strtotime($claim_dressing->dressing_date));
		$year_submission = $year;

		$table_claim_dressing = array
		(
			'claim_id'	 		=> $claim_id,
			'date'				=> date('Y-m-d',strtotime($claim_dressing->dressing_date)),
			'month'				=> $month,
			'invoice_chit'		=> $claim_dressing->dressing_invoice_chit,
			'description'		=> $claim_dressing->dressing_desc,
			'amount_charge'		=> $claim_dressing->dressing_amount_charge,
			'amount_claim'		=> $claim_dressing->dressing_amount_claim,
			'is_approve'		=> 0,
			'amount_approved'	=> 0,
			'is_delete'			=> 0,
			'is_hod_approved'	=> '',
			'hod_remarks'		=> '',
			'admin_remarks'		=> '',
			'created_by'		=> $_SESSION['user']['id']
		);

		$dressing_id = $this->dressing->createDressing($table_claim_dressing);

		if(!empty($dressing_id))
		{
			//create attachments
			if(!empty($attachment))
			{	
				$batch_dressing = array();
				foreach ($attachment as $key => $att) 
				{
					$claim_dressing_attachment 	= array
					(
						'dressing_id'			 => $dressing_id,
						'attachment_name'		 => $att['orig_name'],
						'file_type'				 => $att['file_type'],
						'file_ext'				 => str_replace('.','',$att['file_ext']),
						'description'			 => $att['description'],
						'location'				 => 'storage/claim/dressing/'.$att['file_name'],
						'unique_id'				 => uniqid(),
						'type'					 => 0,
						'is_delete'				 => 0 
					);
					array_push($batch_dressing,$claim_dressing_attachment);
				}
				$this->dressing->createAttachment($batch_dressing);
			}
		}
		
		$data = array
		(
			'status'	=> 'success',
			'msg'		=> 'Successfully create Special Allowance - Dressing',
			'input'		=> $this->input->post()
		);
		echo json_encode($data);return true;	
	}

	function removeDressing()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'msg'		=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$id = $this->input->post('id');
		
		$this->dressing->updateClaim(array('is_delete' => 1),array('id' => $id));
		echo json_encode(array('status' => 'success','msg' => 'Successfully remove Special Allowance - Dressing'));return true;
	}

	function approveDressing()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$input = $this->input->post();

		$update = array
		(
			'is_approve' 		=> $input['status'],
			'amount_approved' 	=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'		=> (!empty($input['reason']))?$input['reason']:'',
			'approved_date' 	=> date('Y-m-d'),
			'approved_by' 		=> $this->user_id
		);
		$where = array('id' => $input['approve_id']);

		$this->dressing->updateClaim($update,$where);

		echo json_encode(array('status'=>'success','msg' => 'Successfully change Special Allowance - Dressing claim status'));return true;
	}

	public function createGadget()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$claim_id 		= $this->input->post('claim_id');
		$claim_gadget 	= json_decode($this->input->post('form'));

		$attachment 	= $this->input->post('attachment');
		$year 			= $this->input->post('year');
		$month 			= $this->input->post('month');
		$user 			= $this->input->post('user');
		
		$year 	= date('Y',strtotime($claim_gadget->gadget_date));
		$month 	= date('m',strtotime($claim_gadget->gadget_date));
		$year_submission = $year;

		$table_claim_gadget = array
		(
			'claim_id'	 		=> $claim_id,
			'date'				=> date('Y-m-d',strtotime($claim_gadget->gadget_date)),
			'month'				=> $month,
			'invoice_chit'		=> $claim_gadget->gadget_invoice_chit,
			'description'		=> $claim_gadget->gadget_desc,
			'amount_charge'		=> $claim_gadget->gadget_amount_charge,
			'amount_claim'		=> $claim_gadget->gadget_amount_claim,
			'is_approve'		=> 0,
			'amount_approved'	=> 0,
			'is_delete'			=> 0,
			'is_hod_approved'	=> '',
			'hod_remarks'		=> '',
			'admin_remarks'		=> '',
			'created_by'		=> $_SESSION['user']['id']
		);
		
		$gadget_id = $this->gadget->createGadget($table_claim_gadget);

		if(!empty($gadget_id))
		{
			//create attachments
			if(!empty($attachment))
			{	
				$batch_gadget = array();
				foreach ($attachment as $key => $att) 
				{
					$claim_gadget_attachment 	= array
					(
						'gadget_id'				 => $gadget_id,
						'attachment_name'		 => $att['orig_name'],
						'file_type'				 => $att['file_type'],
						'file_ext'				 => str_replace('.','',$att['file_ext']),
						'description'			 => $att['description'],
						'location'				 => 'storage/claim/gadget/'.$att['file_name'],
						'unique_id'				 => uniqid(),
						'type'					 => 0,
						'is_delete'				 => 0 
					);
					array_push($batch_gadget,$claim_gadget_attachment);
				}
				$this->gadget->createAttachment($batch_gadget);
			}
		}
		
		$data = array
		(
			'status'	=> 'success',
			'msg'		=> 'Successfully create Special Allowance - Gadget',
			'input'		=> $this->input->post()
		);
		echo json_encode($data);return true;
	}

	function removeGadget()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'msg'		=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$id = $this->input->post('id');
		
		$this->gadget->updateClaim(array('is_delete' => 1),array('id' => $id));
		echo json_encode(array('status' => 'success','msg' => 'Successfully remove Special Allowance - Gadget'));return true;
	}

	function approveGadget()
	{
		if(!$this->isValidUser)
		{
			$data = array
			(
				'status'	=> 'failed',
				'message'	=> 'invalid user token'
			);
			echo json_encode($data);
			return true;
		}
		$input = $this->input->post();

		$update = array
		(
			'is_approve' 		=> $input['status'],
			'amount_approved' 	=> ($input['status'] == 1)?$input['amount_approve']:0,
			'admin_remarks'		=> (!empty($input['reason']))?$input['reason']:'',
			'approved_date' 	=> date('Y-m-d'),
			'approved_by' 		=> $this->user_id
		);
		$where = array('id' => $input['approve_id']);

		$this->gadget->updateClaim($update,$where);

		echo json_encode(array('status'=>'success','msg' => 'Successfully change Special Allowance - Gadget claim status'));return true;
	}

}



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

?>