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

/**
 * This class provides Reseller Statement functions
 *
 * @package    Statement
 * @category   Controllers/Reseller
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Controller_Reseller_Statement extends Controller_Statement {
	protected $secure_actions = array(
		'index'=>TRUE,
		'show'=>TRUE,
	);

	public function action_index() {
		if ($x=$this->request->post('aid'))
			HTTP::redirect(URL::link('reseller','statement/show/'.$x));

		$output = Form::open();
		$output .= Form::select('aid',ORM::factory('Account')->where_authorised(Auth::instance()->get_user(),'id')
			->order_by('company','ASC')->order_by('last_name','ASC')->order_by('first_name','ASC')->list_select());
		$output .= Form::button('submit','Submit',array('class'=>'btn btn-primary'));
		$output .= Form::close();

		Block::factory()
			->title('Select Account')
			->title_icon('icon-share')
			->body($output);
	}

	/**
	 * Show a payments received
	 */
	public function action_show() {
		$ao = ORM::factory('account',$this->request->param('id'));

		if (! $ao->loaded() OR ! Auth::instance()->authorised($ao))
			throw HTTP_Exception::factory(403,'Service either doesnt exist, or you are not authorised to see it');

		$result = array();
		$total = 0;

		foreach ($ao->payment->find_all() as $o) {
			$key = $o->date_payment;

			while (isset($result[$key]))
				$key += 1;

			$result[$key] = $o;

			$total -= Currency::round($o->total());
		}

		foreach ($ao->invoice->list_active() as $o) {
			$key = $o->date_orig;

			while (isset($result[$key]))
				$key += 1;

			$result[$key] = $o;

			$total += Currency::round($o->total());
		}

		krsort($result);

		Block::factory()
			->title(sprintf('%s: %s - %s',_('Transactions For'),$ao->accnum(),$ao->name(TRUE)))
			->title_icon('icon-tasks')
			->body(View::factory('statement/user/show')->set('result',$result)->set('total',$total));
	}
}
?>
