<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This Model manages both the accounts that users use to login to the system, as well as the account where services are owned.
 *
 * @package    lnApp
 * @category   Models
 * @author     Deon George
 * @copyright  (c) 2014 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
abstract class lnApp_Model_Account extends Model_Auth_UserDefault {
	// Relationships
	protected $_has_many = array(
		'email_log'=>array('far_key'=>'id'),
		'group'=>array('through'=>'account_group'),
	);

	protected $_has_one = array(
		'country'=>array('foreign_key'=>'id'),
		'currency'=>array('foreign_key'=>'id'),
		'language'=>array('foreign_key'=>'id'),
	);

	protected $_display_filters = array(
		'date_orig'=>array(
			array('Site::Date',array(':value')),
		),
		'date_last'=>array(
			array('Site::Date',array(':value')),
		),
		'active'=>array(
			array('StaticList_YesNo::get',array(':value',TRUE)),
		),
	);

	protected $_form = array('id'=>'id','value'=>'name(TRUE)');

	protected $_save_message = TRUE;

	/**
	 * Our account number format
	 */
	public function accnum() {
		return sprintf('%s-%04s',Company::instance()->site(TRUE),$this->id);
	}

	public function activate_code() {
		return md5(sprintf('%s-%s-%s-%s',$this->accnum(),$this->date_orig,$this->date_last,$this->email));
	}

	public function activated() {
		return $this->verified;
	}

	/**
	 * Get the groups that an account belongs to
	 */
	public function groups() {
		$result = array();

		foreach ($this->group->where_active()->find_all() as $go)
			foreach ($go->list_parentgrps(TRUE) as $cgo)
				if (empty($result[$cgo->id]))
					$result[$cgo->id] = $cgo;

		return $result;
	}

	public function log($message) {
		if (! class_exists('Model_Account_Log'))
			return TRUE;

		// Log a message for this account
		$alo = ORM::factory('Account_Log');
		$alo->account_id = $this->id;
		$alo->ip = Request::$client_ip;
		$alo->details = $message;
		$alo->save();

		return $alo->saved();
	}

	public function isAdmin() {
		return FALSE;
	}

	/**
	 * This function will extract the available methods for this account
	 * This is used both for menu options and method security
	 */
	public function methods() {
		static $result = array();

		// @todo We may want to optimise this with some session caching.
		if ($result)
			return $result;

		foreach ($this->groups() as $go)
			foreach ($go->module_method->find_all() as $mmo)
				if (empty($result[$mmo->id]))
					$result[$mmo->id] = $mmo;

		Sort::MAsort($result,'module->name,menu_display');

		return $result;
	}

	/**
	 * Return an account name
	 */
	public function name() {
		return trim(sprintf('%s %s',$this->first_name,$this->last_name));
	}

	/**
	 * Return a token valid for this user
	 */
	public function token($token_expire,$module,$method,$uses) {
		return $this->id.':'.md5(sprintf('%s-%s',$this->accnum(),$this->date_last));
	}

	/**
	 * Search for accounts matching a term
	 */
	public function list_autocomplete($term,$index,$value,array $label,array $limit=array(),array $options=NULL) {
		$ao = Auth::instance()->get_user();

		$this->clear();
		$this->where_active();

		// Build our where clause
		// First Name, Last name
		if (preg_match('/\ /',$term)) {
			list($fn,$ln) = explode(' ',$term,2);

			$this->where_open()
				->where('first_name','like','%'.$fn.'%')
				->and_where('last_name','like','%'.$ln.'%')
				->where_close();

		} elseif (is_numeric($term)) {
			$this->where('id','like','%'.$term.'%');

		} elseif (preg_match('/\@/',$term)) {
			$this->where('email','like','%'.$term.'%');

		} else {
			$this->where_open()
				->or_where('first_name','like','%'.$term.'%')
				->or_where('last_name','like','%'.$term.'%')
				->or_where('email','like','%'.$term.'%')
				->where_close();
		}

		// Restrict results to authorised accounts
		// @todo

		return parent::list_autocomplete($term,$index,$value,$label,$limit,$options);
	}
}
?>
