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

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

	/**
	 * Reconcile billing for an ADSL supplier
	 */
	public function action_billing() {
		if (! $this->request->post('sid') OR ! $_FILES)
			HTTP::redirect(URL::link('reseller','adsl/index'));

		$aso = ORM::factory('ADSL_Supplier',$this->request->post('sid'));

		// Process upload
		$files = Validation::factory($_FILES)
			->rule('csv','Upload::valid')
			->rule('csv','Upload::not_empty')
			->rule('csv','Upload::type',array(':value',array('csv')))
			->rule('csv','Upload::size',array(':value','10M'));

		$csv = NULL;
		if ($files->check())
			foreach ($files->data() as $file) {
				$csv = $aso->billing()->process($aso,$file);
				// We should only have 1 file
				break;
			}

		if (! $csv)
			throw HTTP_Exception::factory(501,'No CSV data ?');

		Block::factory()
			->title('ADSL Service Invoicing')
			->title_icon('icon-th-list')
			->body(View::factory('adsl/reseller/billing')->set('o',$csv)->set('aso',$aso));

		Block::factory()
			->title('ADSL Service Exception Charges')
			->title_icon('icon-th-list')
			->body(View::factory('adsl/reseller/billingexception')->set('o',$csv));
	}

	/**
	 * Select our primary export target
	 */
	public function action_index() {
		$output = '';

		if ($this->request->post() AND $this->request->post('sid')) {
			$aso = ORM::factory('ADSL_Supplier',$this->request->post('sid'));
			if (! $aso->loaded())
				HTTP::redirect('adsl/index');

			$c = Kohana::classname('Adsl_Billing_'.$aso->name);
			$o = new $c();

			$output .= $o->form();

			Block::factory()
				->title('Upload ADSL Supplier Invoice')
				->title_icon('icon-share')
				->body($output);

		} else {
			$output .= Form::open();
			$output .= Form::select('sid',ORM::factory('ADSL_Supplier')->list_select());
			$output .= Form::button('submit','Submit',array('class'=>'btn btn-primary'));
			$output .= Form::close();

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