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

class Admin_model extends CI_Model
{

	/**
	 * Constructor
	 *
	 * @access	public
	 */
	function __construct()
	{
		parent::__construct();
	}

	// =============================
	// = ========== GET ========== =
	// =============================

	/**
	 * Get relevant user information by id
	 *
	 * @access	public
	 * @param	integer	User ID
	 */
	function get_user($id)
	{
		$this->db->select('admin.*');
		$this->db->join('d_user_groups', 'ug_user_id = id');

		$query = $this->db->get_where('admin', array('id' => $id));
		return $query->row();
	}

	// --------------------------------------------------------------------

	/**
	 * Get all users
	 *
	 * @access	public
	 */
	function get_all_users()
	{
		$this->db->select('admin.*');
		$this->db->join('d_user_groups', 'ug_group_id = group_id');

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

		return $query->result();
	}



	// =============================
	// = ========== ADD ========== =
	// =============================

	/**
	 * Add User
	 *
	 * Add user to the db
	 *
	 * @access	private
	 * @param	string	table, where
	 * @return	mixed
	 */
	function add_user($userdata)
	{
		$this->db->set($userdata);
		$this->db->insert('admin');
	}

	// ================================
	// = ========== UPDATE ========== =
	// ================================

	/**
	 * Insert New Password
	 *
	 * @access	private
	 * @param	string	password, username, salt
	 * @param	bool	force user password change
	 * @return	bool
	 */
	function update_password($password, $user_id)
	{

		$password = $this->auth->hash_password($password);

		$data = array(
				'user_password' => $password,
        );

		$this->db->where('user_id', $user_id);
		$this->db->update('d_users', $data);

		return $this->db->affected_rows() > 0;
	}

	// --------------------------------------------------------------------

	/**
	 * Update User Information
	 *
	 * @access	private
	 * @return	bool
	 */
	function update_profile($user_id)
	{

		$data = array(
			'name'		=>	$this->input->post('name'),
			'email'		=>	$this->input->post('email')
		);

		if($this->input->post('password'))
		{
			$this->update_password($this->input->post('password'), $user_id);
		}

		$this->db->where('id', $user_id);
		$this->db->update('admin', $data);

	}

	// ================================
	// = ========== DELETE ========== =
	// ================================

	/**
	 * Delete a user
	 *
	 * @access	public
	 */
	function delete($id)
	{
		$this->db->delete('admin', array('id' => $id));
	}



	/**
	 * Checks if $value for $field is already used
	 *
	 * @access	private
	 * @param	string	email
	 * @return	bool
	 */
	function check_unique($field, $value)
	{
		$this->db->select($field);
		$this->db->where($field, $value);
		$this->db->limit(1);

		return $this->db->count_all_results($this->table) > 0;
	}


}

// END user_model.php
/* Location: ./application/models/users_model.php */

