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

/**
 * OSB Route to Market
 *
 * @package    OSB
 * @category   Models
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Model_RTM extends ORM_OSB {
	protected $_belongs_to = array(
		'account' => array(),
	);
	protected $_has_many = array(
		'customer' => array('model'=>'account','far_key'=>'id','foreign_key'=>'rtm_id'),
		'agent' => array('model'=>'rtm','far_key'=>'id','foreign_key'=>'parent_id'),
		'supplier' => array('model'=>'rtm','far_key'=>'parent_id','foreign_key'=>'id'),
	);

	public function agents(Model_RTM $rtmo) {
		$result = array($rtmo);

		foreach ($rtmo->agents_direct() as $artmo)
			$result = Arr::merge($result,$rtmo->agents($artmo));

		return $result;
	}

	public function agents_direct() {
		return $this->agent->find_all();
	}

	public function customers(Model_RTM $rtmo) {
		// If our RTM is NULL, then we are our only customer.
		if (is_null($rtmo->id))
			return (array(Auth::Instance()->get_user()));

		$result = array();

		foreach ($rtmo->agents_direct() as $artmo)
			$result = Arr::merge($result,$rtmo->customers($artmo));

		foreach ($rtmo->customers_direct() as $ao)
			array_push($result,$ao);

		return $result;
	}

	public function customers_direct() {
		return $this->customer->find_all();
	}

	public function peers() {
		$result = array();

		foreach (ORM::factory('RTM')->where('id','=',$this->id)->find_all() as $rtmo)
			array_push($result,$rtmo->account);

		return $result;
	}

	public function suppliers(Model_RTM $rtmo) {
		$result = array($rtmo);

		foreach ($rtmo->suppliers_direct() as $srtmo)
			$result = Arr::merge($result,$rtmo->suppliers($srtmo));

		return $result;
	}

	public function suppliers_direct() {
		return $this->supplier->find_all();
	}

}
?>
