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

/**
* User Resource Model
*/
class User_Resource_Model extends CI_Model
{
	public $table = 'user_resource_type';
	
	function __construct()
	{
		parent::__construct();
	}

	public function insert()
	{
		$data = array(
			'user_resource_type_name' 	=> $this->input->post('user_resource_type_name'),
			'role_ID'					=> $this->input->post('user_role')
			);

		return $this->db->insert($this->table,$data);
	}

	public function get($user_resource_type_ID = NULL)
	{
		if($user_resource_type_ID !== NULL){
			$query = $this->db->get_where($this->table, array('user_resource_type_ID'=>$user_resource_type_ID));
			return $query->row();
		}
		$query = $this->db->get($this->table);
		return $query->result();
	}

	public function update()
	{
		$data = array(
			'user_resource_type_name' => $this->input->post('user_resource_type_name')
			);
		$this->db->where('user_resource_type_ID',$this->input->post('user_resource_type_ID'));
		return $this->db->update($this->table, $data);
	}

	public function delete($user_resource_type_ID)
	{
		$this->db->trans_start();
		$this->db->delete('user_resource_data', array('resource_type'=>$user_resource_type_ID));
		$this->db->delete($this->table, array('user_resource_type_ID'=>$user_resource_type_ID));
		$this->db->trans_complete();
		return ($this->db->trans_status()==TRUE)? $this->db->trans_status():FALSE;
	}

	public function getUserResourceTypes($role_ID)
	{
		$query = $this->db->get_where($this->table,array('role_ID'=>$role_ID));
		return $query->result();
	}

	public function getUserResourceData($user_ID)
	{
		$query = $this->db->get_where('user_resource_data', array('user_ID',$user_ID));
		return $query->result();
	}

	public function setUserResourceData()
	{
		$user_resource_data = $this->input->post('user_resource');

		$this->db->trans_start();
		foreach($user_resource_data as $key=>$resource){
			$query = $this->db->get_where('user_resource_data',array('user_ID' => $this->input->post('user_ID'),'resource_type'=>$key));
			if($query->row()){
				$this->db->update('user_resource_data',array('resource_data'=>$resource),array('user_resource_data_ID'=>$query->row()->user_resource_data_ID));
			} else {
				$data = array(
					'user_ID' => $this->input->post('user_ID'),
					'resource_type'=>$key,
					'resource_data'=>$resource
				);
				$this->db->insert('user_resource_data',$data);
			}
		}
		$this->db->trans_complete();
		
		return ($this->db->trans_status()==TRUE)? $this->db->trans_status():FALSE;
	}
}