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

class Model_user_license extends CI_Model {

	public function fetchLicense($id = null, $user_id = null, $license_no = null, $latest = false,$profiling_id = null)
	{
		//inner query 
		$this->db->select('MAX(profiling_id)');
		$this->db->from('user__license ',false);
		if($id) $this->db->where('id',$id);
		if($user_id) $this->db->where('user_id',$user_id);
		$max = $this->db->get_compiled_select();

		//outer query
		$this->db->select('a.*,
							b.id as attachment_id,b.attachment_name,b.location,b.file_type,b.file_ext,b.mask_id,
							c.action_efective_date,
                            d.type as action_type');
		
		if($id) $this->db->where('a.id',$id);
		if($user_id) $this->db->where('a.user_id',$user_id);
		if($license_no) $this->db->where('a.license_no',$license_no);
		if($latest) $this->db->where("a.profiling_id IN (".$max.")",'',false);
		if($profiling_id) $this->db->where('a.profiling_id',$profiling_id);

		$this->db->join('user__license_attachment b','b.license_id = a.id and b.is_delete = 0','left');
		$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->where('a.is_delete',0);
		$query = $this->db->get('user__license a');

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

	public function createLicense($input = array())
	{
		$data = array
		(
			'user_id' 					=> $input['user_id'],
			'profiling_id'				=> $input['profiling_id'],
			'profession'				=> $input['profession'],
			'license_no'				=> $input['license_no'],
			'license_body_authority'	=> $input['license_body_authority'],
			'register_date' 			=> (!empty($input['register_date']))?$input['register_date']:null,
			'renewal_date'				=> (!empty($input['renewal_date']))?$input['renewal_date']:null,
			'next_renewal_date'			=> (!empty($input['next_renewal_date']))?$input['next_renewal_date']:null,
			'is_delete'					=> 0
		);

		$this->db->insert('user__license',$data);

		return $this->db->insert_id();
	}

	public function editLicense($input,$id)
	{
		$this->db->set($input);
		$this->db->where('id',$id);
		$this->db->update('user__license');

		return true;
	}

}
?>