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

/**
 * This class provides OSB exporting capabilities.
 *
 * @package    OSB
 * @subpackage Export
 * @category   Controllers/Affiliate
 * @author     Deon George
 * @copyright  (c) 2010 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Controller_Affiliate_Export extends Controller_TemplateDefault_Affiliate {
	protected $control_title = 'Export';
	protected $secure_actions = array(
		'index'=>TRUE,
		'export'=>TRUE,
	);

	/**
	 * Export plugins must define an export action.
	 */
	public function action_export() {
		if (empty($_POST['plugin']))
			$this->request->redirect('affiliate/export/index');

		$sc = sprintf('Export_%s',$_POST['plugin']);
		if (! class_exists($sc))
			throw new Kohana_Exception('Export Class doesnt exist for :plugin',array(':plugin'=>$_POST['plugin']));
		else
			$export = new $sc;

		// @todo: Need to limit this to affiliate acounts
		$export->export();
	}

	/**
	 * This is the main call to export, providing a list of items to export and
	 * setting up the page to call the export plugin when submitted.
	 */
	public function action_index() {
		// @todo this should come from a file list
		$TBRexportplugins = array('quicken'=>'Export to Quicken');

		// @todo: Need to limit this to affiliate acounts
		$p = ORM::factory('payment');

		if ($p->find_all()->count()) {
			Block::add(array(
				'title'=>_('Payments to Export'),
				'body'=>Table::display(
					$p->find_all(),
					25,
					array(
						'id'=>array('label'=>'ID'),
						'date_payment'=>array('label'=>'Date'),
						'checkout->display("name")'=>array('label'=>'Method'),
						'account->accnum()'=>array('label'=>'Acc Num'),
						'account->name()'=>array('label'=>'Account'),
						'total_amt'=>array('label'=>'Total','class'=>'right'),
						'balance(TRUE)'=>array('label'=>'Balance','class'=>'right'),
						'invoicelist()'=>array('label'=>'Invoices'),
					),
					array(
						'page'=>TRUE,
						'type'=>'select',
						'form'=>'affiliate/export/export',
						'hidden'=>array(
							Form::hidden('plugin','quicken'),
						),
						'button'=>array(
							Form::submit('submit',_('Export'),array('class'=>'form_button')),
						),
				)),
			));

		# Nothing to export
		} else {
			SystemMessage::add(array(
				'title'=>_('No payments to export'),
				'type'=>'info',
				'body'=>sprintf(_('There are no payments within the last %s days (since %s) to show.'),
					$daysago,date(Kohana::config('osb')->get('date_format'),$daysago*86400+time())),
			));
		}
	}
}
?>
