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

/**
 * @package    lnApp
 * @subpackage Auth
 * @category   Models
 * @author     Deon George
 * @copyright  (c) 2010 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
class Model_Account extends Model_Auth_UserDefault {
	// Relationships
	protected $_has_many = array(
		'user_tokens' => array('model' => 'user_token'),
		'email_log' => array('far_key'=>'id'),
		'group' => array('through' => 'account_group'),
		'invoice' => array('far_key'=>'id'),
		'payment'=>array('far_key'=>'id'),
		'service' => array('far_key'=>'id'),
	);
	protected $_has_one = array(
		'affiliate' => array('far_key'=>'id'),
		'language'=>array('foreign_key'=>'id','far_key'=>'language_id'),
	);

	protected $_display_filters = array(
		'date_orig'=>array(
			array('Config::date',array(':value')),
		),
		'date_last'=>array(
			array('Config::date',array(':value')),
		),
		'status'=>array(
			array('StaticList_YesNo::display',array(':value')),
		),
	);

	/**
	 * Return an account name
	 */
	public function name($withcompany=FALSE) {
		if ($withcompany)
			return sprintf('%s %s%s',$this->first_name,$this->last_name,$this->company ? sprintf(' (%s)',$this->company) : '');
		else
			return sprintf('%s %s',$this->first_name,$this->last_name);
	}

	public function accnum() {
		return sprintf('%s-%04s',Config::siteid(TRUE),$this->id);
	}

	public function sortkey($withcompany=FALSE) {
		$sk = '';

		if ($withcompany AND $this->company)
			$sk .= $this->company.' ';

		return $sk.sprintf('%s %s',$this->last_name,$this->first_name);
	}

	public function title($name) {
		return StaticList_Title::form($name,$this->title);
	}

	public function currency($name) {
		return StaticList_Module::form($name,'currency',$this->currency_id,'id','name',array('status'=>'=:1'),FALSE,array('class'=>'form_button'));
	}

	public function country($name) {
		return StaticList_Module::form($name,'country',$this->country_id,'id','name',array('status'=>'=:1'),FALSE,array('class'=>'form_button'));
	}

	/**
	 * Get the groups that an account belongs to
	 */
	public function groups() {
		return $this->group->find_all();
	}

	public function isAdmin() {
		// @todo Define admins in the config file or DB
		$admins = array(ORM::factory('group',array('name'=>'Root')));

		return $this->has('group',$admins);
	}

	/**
	 * Get a list of all invoices for this account
	 */
	public function invoices() {
		return $this->invoice->distinct('id')->find_all();
	}

	/**
	 * Get a list of due invoices for this account
	 *
	 * @param int Date (in secs) to only retrieve invoices prior to this date
	 */
	public function invoices_due($date=NULL) {
		$return = array();

		foreach ($this->invoices() as $io)
			if ((is_null($date) OR $io->date_orig < $date) AND $io->due())
				$return[$io->id] = $io;

		return $return;
	}

	/**
	 * Calculate the total of invoices due for this account
	 */
	public function invoices_due_total($date=NULL,$format=FALSE) {
		$result = 0;

		foreach ($this->invoices_due($date) as $io)
			$result += $io->due();

		// @todo This shouldnt really be required
		if ($result < 0)
			throw new Kohana_Exception($result);

		return $format ? Currency::display($result) : $result;
	}

	public function log($message) {
		// Log the logout
		$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 list_active() {
		return $this->_where_active()->order_by('company,last_name,first_name')->find_all();
	}

	public function list_affiliates() {
		$return = array();

		foreach ($this->list_services() as $so)
			if (! isset($return[$so->affiliate_id]))
				$return[$so->affiliate_id] = $so->affiliate;

		return $return;
	}

	public function count_services($active=TRUE,$afid=NULL) {
		return $this->list_services($active,$afid)->count();
	}

	/**
	 * Search for accounts matching a term
	 */
	public function list_autocomplete($term,$index='id',array $limit=array()) {
		$return = array();

		$this->clear();
		$this->where_active();
		$value = 'name(TRUE)';

		// 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()
				->or_where('company','like','%'.$term.'%');

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

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

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

		foreach ($limit as $w) {
			list($k,$s,$v) = $w;

			$this->and_where($k,$s,$v);
		}

		foreach ($this->find_all() as $o)
			$return[$o->$index] = array(
				'value'=>$o->$index,
				'label'=>sprintf('ACC %s: %s',$o->id,Table::resolve($o,$value)),
			);

		return $return;
	}

	public function list_services($active=TRUE,$afid=NULL) {
		$svs = $this->service->where_active();

		if ($afid)
			$svs->where('affiliate_id','=',$afid);

		return $svs->find_all();
	}
}
?>
