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

class Model_bank extends CI_Model {

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

		//outer query
		$this->db->select('a.*,
							b.name,
							c.action_efective_date,
							d.type as action_type,
							e.id as attachment_id, e.attachment_name,e.location,e.file_type,e.file_ext,e.mask_id,');

		if($staff_id) $this->db->where('a.user_id',$staff_id);
		if($latest) $this->db->where("a.profiling_id IN ($max)");
		if($profiling_id) $this->db->where('a.profiling_id',$profiling_id);

		$this->db->where('a.is_delete',0);
		$this->db->join('_ref__bank b','b.id = a.bank_id');
		$this->db->join('user__profiling c','c.id = a.profiling_id','left');
		$this->db->join('_ref__action_type d','d.id = c.action_type_id','left');
		$this->db->join('user__bank_detail_attachment e','e.bank_detail_id = a.id and e.is_delete = 0','left');

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

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

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

	public function editBank($input,$id)
	{
		$this->db->set($input);
		$this->db->where('id',$id);
		if($this->db->update('user__bank_detail'))
		{
			return $id;
		}else
		{
			return null;
		}

	}

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

	public function updateAttachment($data,$id)
	{
		//get and update if null create new one
		$this->db->where('bank_detail_id',$id);
		$result = $this->db->get('user__bank_detail_attachment')->result();
		
		if(!empty($result))
		{
			//update 
			$this->db->where('bank_detail_id',$id);
			if($this->db->update('user__bank_detail_attachment',$data))
			{
				return $id;
			}else
			{
				return null;
			}
			
		}else{
			//create new
			if($id = $this->createAttachment($data))
			{
				return $id;
			}
			else
			{
				return null;
			}
		}
	}
}
?>