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

/**
* User_Model
*/
class User_Model extends CI_Model
{
	
	public $table = 'user';

	public function __construct()
	{
		parent::__construct();

		$config['upload_path']          = './uploads/';
        $config['allowed_types']        = 'jpg';
        $config['max_size']             = 1024;
        $config['encrypt_name']			= true;

        $this->load->library('upload', $config);
	}

	public function insert()
	{

		if ( ! $this->upload->do_upload('profile_img'))
		{
			return false;
		}


		$data = array(
			'f_name' => $this->input->post('f_name'),
			'l_name' => $this->input->post('l_name'),
			'email' => $this->input->post('email'),
			'username' => $this->input->post('username'),
			'password' => $this->input->post('password'),
			'phone_no' => $this->input->post('phone_no'),
			'address' => $this->input->post('address'),
			'city' => $this->input->post('city'),
			'profile_img' => $this->upload->data('file_name'),
			'active' => 1,
			'role_ID' => $this->input->post('role_id')
			);

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

	public function get($user_ID = null)
	{
		if($user_ID==null){
			$query = $this->db->select('*')
					->from($this->table)
					->where('active','1')
					->join('user_role',$this->table.'.role_ID=user_role.role_ID')
					->get();
			return $query->result();
		}
		$query = $this->db->select('*')
					->from($this->table)
					->where('user_ID', $user_ID)
					->where('active','1')
					->join('user_role',$this->table.'.role_ID=user_role.role_ID')
					->get();
		return $query->row();
	}

	public function update ()
	{
		$profile_img = $this->input->post('old_profile_img');


		if ( ! $this->upload->do_upload('profile_img')) {
			 return false;
		} else {
			$profile_img = $this->upload->data('file_name');
			unlink("./uploads/" . $this -> input -> post('old_profile_img'));
		}
		

		$data = array(
			'f_name' => $this->input->post('f_name'),
			'l_name' => $this->input->post('l_name'),
			'email' => $this->input->post('email'),
			'username' => $this->input->post('username'),
			'password' => $this->input->post('password'),
			'phone_no' => $this->input->post('phone_no'),
			'address' => $this->input->post('address'),
			'city' => $this->input->post('city'),
			'profile_img' => $profile_img,
			);

		$this->db->where('user_ID',$this->input->post('user_ID'));
		return $this->db->update($this->table,$data);
	}

	public function delete($user_ID)
	{
		$this->db->where('user_ID',$user_ID);
		return $this->db->update($this->table,array('active'=>0));
	}

}