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

/**
 * User_model — admin accounts and authentication lookups.
 */
#[\AllowDynamicProperties]
class User_model extends MY_Model {

	protected $table = 'users';
	protected $order_by = 'name ASC';

	/** Find an active user by email (used at login). */
	public function by_email($email)
	{
		return $this->get_by(array('email' => $email, 'is_active' => 1));
	}

	/** Record a successful login timestamp. */
	public function mark_login($id)
	{
		return $this->db->where('id', $id)
			->update($this->table, array('last_login' => date('Y-m-d H:i:s')));
	}

	/** Check whether an email is already taken (optionally excluding an ID). */
	public function email_exists($email, $exclude_id = NULL)
	{
		$this->db->where('email', $email);
		if ($exclude_id) $this->db->where('id !=', $exclude_id);
		return $this->db->count_all_results($this->table) > 0;
	}

	/** Update a user's password (hashes the plain value). */
	public function set_password($id, $plain)
	{
		return $this->update($id, array(
			'password' => password_hash($plain, PASSWORD_BCRYPT),
		));
	}
}
