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

/**
 * This class provides User Invoice functions
 *
 * @package    OSB
 * @subpackage Invoice
 * @category   Controllers/User
 * @author     Deon George
 * @copyright  (c) 2010 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
class Controller_User_Invoice extends Controller_TemplateDefault_User {
	protected $secure_actions = array(
		'download'=>TRUE,
		'list'=>TRUE,
		'view'=>TRUE,
	);

	/**
	 * Show a list of invoices
	 */
	public function action_list() {
		Block::add(array(
			'title'=>sprintf('%s: %s - %s',_('Invoices For'),$this->ao->accnum(),$this->ao->name(TRUE)),
			'body'=>Table::display(
				$this->ao->invoice->find_all(),
				25,
				array(
					'id'=>array('label'=>'ID','url'=>'user/invoice/view/'),
					'date_orig'=>array('label'=>'Date Issued'),
					'due_date'=>array('label'=>'Date Due'),
					'total(TRUE)'=>array('label'=>'Total','class'=>'right'),
					'credit_amt'=>array('label'=>'Credits','class'=>'right'),
					'payments_total(TRUE)'=>array('label'=>'Payments','class'=>'right'),
					'due(TRUE)'=>array('label'=>'Still Due','class'=>'right'),
				),
				array(
					'page'=>TRUE,
					'type'=>'select',
					'form'=>'user/invoice/view',
				)),
			));
	}

	/**
	 * View an Invoice
	 */
	public function action_view() {
		list($id,$output) = Table::page(__METHOD__);

		$io = ORM::factory('invoice',$id);

		if (! $io->loaded() OR (! Auth::instance()->authorised($io->account_id,$io->affiliate_id) AND ! in_array($this->ao->affiliate->id,$io->service_affiliates()))) {
			$this->template->content = 'Unauthorised or doesnt exist?';
			return FALSE;
		}

		$output .= View::factory($this->viewpath())
			->set('mediapath',Route::get('default/media'))
			->set('io',$io);

		Block::add(array(
			'title'=>sprintf('%s: %s - %s',_('Invoice'),$io->refnum(),$io->account->name()),
			'body'=>$output,
			));
	}

	/**
	 * Download an invoice
	 */
	public function action_download() {
		$io = ORM::factory('invoice',$this->request->param('id'));

		$this->response->body(Invoice::instance($io)->pdf()->Output(sprintf('%s.pdf',$io->refnum()),'D'));
		$this->response->headers(array('Content-Type' => 'application/pdf'));
		$this->auto_render = FALSE;
	}
}
?>