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

/**
 * This class extends Kohana's [ORM] class to create defaults for OSB.
 *
 * @package    OSB
 * @category   Helpers
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
abstract class ORM_OSB extends ORM {
	/**
	 * @var string Database to connect to
	 */
	protected $_db = 'default';

	// Rules to assist with site ID and getting next record ID for inserts.
	public function rules() {
		return array(
			'id'=>array(
				array('ORM_OSB::get_next_id',array(':model',':field')),
			),
			'site_id'=>array(
				array('ORM_OSB::set_site_id',array(':model',':field')),
			),
		);
	}

	public function config($key) {
		$mc = Config::instance()->module_config($this->_object_name);

		return empty($mc[$key]) ? '' : $mc[$key];
	}

	/**
	 * Get Next record id
	 *
	 * @param array Validate object
	 * @param string Primary Key
	 */
	final public static function get_next_id($model,$field) {
		if (! is_null($model->$field))
			return TRUE;

		$model->_changed[$field] = $field;

		$ido = ORM::factory('Module')
			->where('name','=',$model->_table_name)
			->find();

		if (! $ido->loaded())
			throw new Kohana_Exception('Problem getting record_id for :table',array(':table'=>$model->_table_name));

		$model->$field = $ido->record_id->next_id($ido->id);

		return TRUE;
	}

	public function keyget($column,$key=NULL) {
		if (is_null($key) OR ! is_array($this->$column))
			return $this->$column;
		else
			return array_key_exists($key,$this->$column) ? $this->{$column}[$key] : NULL;
	}

	final public function mid() {
		return ORM::factory('Module',array('name'=>$this->_table_name));
	}

	/**
	 * Set the site ID attribute for each row update
	 */
	final public static function set_site_id($model,$field) {
		if (! is_null($model->$field))
			return TRUE;

		$model->_changed[$field] = $field;
		$model->$field = Company::instance()->site();

		return TRUE;
	}

	/**
	 * Function help to find records that are active
	 */
	public function list_active($active=TRUE) {
		$x=($active ? $this->_where_active() : $this);

		return $x->find_all();
	}

	public function list_count($active=TRUE) {
		$x=($active ? $this->_where_active() : $this);

		return $x->find_all()->count();
	}
}
?>