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

class Model_claim_meal extends CI_Model {

	function fetchMeals($user_id = null,$claim_id = null,$year = null,$month = null)
	{
		$this->db->select('a.*');
		if($user_id)$this->db->where('b.user_id',$user_id);
		if($claim_id)$this->db->where('a.claim_id',$claim_id);
		if($year)$this->db->where('b.year',$year);
		if($month)$this->db->where('b.month',$month);
		$this->db->where('a.is_delete',0);
		
		if($user_id || $year || $month) $this->db->join('hr__claim b','b.id = a.claim_id');

		$query = $this->db->get('hr__claim_meals a');
		$results = $query->result();
		
		if(!empty($results))
		{
			foreach ($results as $key => $result) 
			{
				$movement = $this->db->select('a.*,b.date,b.description,b.destination,c.movementType')
				->where('a.meals_id',$result->id)
				->where('a.is_delete',0)
				->join('hr__movement_group b','b.id = a.movement_id')
				->join('hr__movement_type c','c.id = b.movementType')
				->get('hr__claim_meals_movement a')->result();
				$results[$key]->movements = $movement;
			}
		}
		return ($query->result())?$query->result():null;
	}

	function fetchSingleMeal($user_id = null,$claim_id = null,$year = null,$month = null)
	{
		$dentals = $this->fetchMeals($user_id,$claim_id,$year,$month);
		return ($dentals)?$dentals[0]:null;
	}

	function createClaim($input)
	{
		$this->db->insert('hr__claim_meals',$input);
		return $this->db->insert_id();
	}

	function createAttachment($input)
	{
		return ($this->db->insert_batch('hr__claim_meal_attachment',$input))?true:false;
	}

	function updateMeal($input,$where = array())
	{
		$this->db->set($input);
		foreach ($where as $key => $wh) {
			$this->db->where($key,$wh);
		}

		$this->db->update('hr__claim_meals');
	}

	function removeMeal($id)
	{
		$data 	= array('is_delete' => 1);
		$where 	= array('id' => $id);
		$this->updateMeal($data,$where);	
	}

	function getAttachment($meal_id)
	{
		$this->db->where('is_delete',0);
		$this->db->where('meal_claim_id',$meal_id);
		$query = $this->db->get('hr__claim_meal_attachment');
		return ($query->num_rows())?$query->result():null;
	}

}
?>