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

/**
 * OSB Setup Model
 *
 * This module must remain in applications/ as it is used very early in the
 * OSB initialisation.
 *
 * @package    OSB
 * @category   Models
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Model_Setup extends ORM_OSB {
	// Setup doesnt use the update column
	protected $_updated_column = FALSE;

	protected $_has_one = array(
		'account'=>array('foreign_key'=>'id','far_key'=>'admin_id'),
		'country'=>array('foreign_key'=>'id','far_key'=>'country_id'),
		'language'=>array('foreign_key'=>'id','far_key'=>'language_id'),
	);

	protected $_save_message = TRUE;

	// Validation rules
	public function rules() {
		$x = Arr::merge(parent::rules(), array(
			'url' => array(
				array('not_empty'),
				array('min_length', array(':value', 8)),
				array('max_length', array(':value', 127)),
				array('url'),
			),
		));

		// This module doesnt use site_id.
		unset($x['site_id']);

		return $x;
	}

	/**
	 * Get/Set Module Configuration
	 *
	 * @param $key Module name.
	 * @param $value Values to store. If NULL, retrieves the value stored, otherwise stores value.
	 */
	public function module_config($key,array $value=NULL) {
		// If we are not loaded, we dont have any config.
		if (! $this->loaded() OR (is_null($value) AND ! $this->module_config))
			return array();

		$mo = ORM::factory('Module',array('name'=>$key));

		if (! $mo->loaded())
			throw new Kohana_Exception('Unknown module :name',array(':name'=>$key));

		$mc = $this->module_config ? $this->module_config : array();

		// If $value is NULL, we are a getter
		if ($value === NULL)
			return empty($mc[$mo->id]) ? array() : $mc[$mo->id];

		// Store new value
		$mc[$mo->id] = $value;
		$this->module_config = $mc;

		return $this;
	}

	public function module_config_id($key=NULL) {
		$result = array();

		foreach (array_keys($this->module_config) as $mid) {
			if (is_null($key) OR $key == $mid) {
				$result[$mid] = array(
					'object'=>ORM::factory('Module',$mid),
					'data'=>$this->module_config[$mid],
				);

				// If we are just after our key, we can continue here
				if ($key AND $key==$mid)
					break;
			}
		}

		return $result;
	}

	/**
	 * Get/Set our Site Configuration from the DB
	 *
	 * @param $key Key
	 * @param $value Values to store. If NULL, retrieves the value stored, otherwise stores value.
	 */
	public function site_details($key,array $value=NULL) {
		if (! in_array($key,array('name','address1','address2','city','state','pcode','phone','fax','email','faqurl')))
			throw new Kohana_Exception('Unknown Site Configuration Key :key',array(':key'=>$key));

		// If $value is NULL, we are a getter
		if ($value === NULL)
			return empty($this->site_details[$key]) ? '' : $this->site_details[$key];

		// Store new value
		$sc[$key] = $value;

		return $this;
	}
}
?>
