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

class Model_basic_pay extends CI_Model {

	public function fetchBasicPay($user_id = null, $latest = false,$profiling_id = null)
	{
		//inner query
		$this->db->select('MAX(a.profiling_id)');
		$this->db->from('user__basic_pay a');
		$this->db->where('a.is_delete',0);
		if($user_id) $this->db->where('a.user_id',$user_id);
		$max = $this->db->get_compiled_select();

		//outer query
		$this->db->select('a.*,
							b.action_efective_date,
							c.type as action_type,
							d.grade, d.level');
		
		$this->db->where('a.is_delete',0);
		if($user_id) $this->db->where('a.user_id',$user_id);
		if($latest) $this->db->where("a.profiling_id IN ($max)");
		if($profiling_id) $this->db->where('a.profiling_id',$profiling_id);

		$this->db->join('user__profiling b','b.id = a.profiling_id','left');
		$this->db->join('_ref__action_type c','c.id = b.action_type_id','left');
		$this->db->join('company__position d','d.id = a.staff_grade_id','left outer');

		$query = $this->db->get('user__basic_pay a');

		// return $query->num_rows();
		return ($query->num_rows() > 0)?$query->result():null;
	}

	public function createBasicPay($input)
	{
		$this->db->insert('user__basic_pay',$input);
		return $this->db->insert_id();
	}

	public function updateBasicPay($input,$id = null, $profiling_id = null)
	{
		$this->db->set($input);
		if($id) $this->db->where('id',$id);
		if($profiling_id) $this->db->where('profiling_id',$profiling_id);
		$this->db->update('user__basic_pay');
	}

	public function getBasicPay($user_id,$month = null,$year = null)
	{
		if(empty($month))$month = date('m');
		if(empty($year))$year = date('Y');

		$this->db->select('a.amount');
		$this->db->where('a.user_id',$user_id);
		$this->db->where('b.action_efective_date <= ',$year.'-'.$month.'-01');
		$this->db->join('user__profiling b','b.id = a.profiling_id','left',false);
		$this->db->order_by('b.action_efective_date DESC');
		$this->db->limit(1);

		$query = $this->db->get('user__basic_pay a');

		return (!empty($query->result()))?$query->result()[0]->amount:0;
	}
}
?>