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

/**
 * This class provides Reseller ADSL Service 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_Service_Adsl extends Controller_Service {
	protected $secure_actions = array(
		'list'=>TRUE,
	);

	private function consoltraffic($period) {
		$result = array();

		$periodstart = mktime(0,0,0,date('m',$period),1,date('Y',$period)-1);

		$t = ORM::factory('Service_Plugin_Adsl_Traffic')
			->select(array('date_format(date,\'%y-%m\')','month'))
			->selectsummetric()
			->join('service__adsl','INNER')
			->on('service__adsl.service_username','=','service_plugin_adsl_traffic.service')
			->on('service__adsl.site_id','=','service_plugin_adsl_traffic.site_id')
			->join('service','INNER')
			->on('service__adsl.service_id','=','service.id')
			->on('service__adsl.site_id','=','service.site_id')
			->where_authorised($this->ao,'service.account_id')
			->and_where('date','>=',date('Y-m-d',$periodstart))
			->and_where('date','<=',date('Y-m-d',strtotime('last day of '.date('M Y',$period))))
			->group_by('date_format(date,\'%Y-%m\')');

		foreach ($t->find_all() as $to)
			foreach ($to->traffic_data() as $metric => $v)
				$result[$metric][$to->month] = $v;

		return $result;
	}

	public function action_list() {
		$highchart = HighChart::factory('Combo');
		$highchart->title(sprintf('Monthly DSL traffic usage as at %s',date('Y-m-d',strtotime('yesterday'))));
		$highchart->ymetric('MB');

		$c = 0;
		foreach ($this->consoltraffic(time()) as $k => $details) {
			$highchart->series('column','yl')
				->name($k)
				->data($details)
				->index($c)
				->order($c++*-1); // This is a kludge to get around highcharts rendering from the bottom up.

			$highchart->autopie($k);
		}

		Block::factory()
			->body((string)$highchart);

		Block::factory()
			->title('ADSL Services')
			->title_icon('icon-th-list')
			->body(Table::factory()
				->jssort('adsl')
				->data(ORM::factory('Service')->where_authorised($this->ao)->list_byplugin('ADSL'))
				->columns(array(
					'id'=>'ID',
					'name()'=>'Service',
					'plugin()->ipaddress()'=>'IP Address',
					'product->plugin()->supplier_plan->speed'=>'Speed',
					'product->plugin()->allowance(array(),TRUE,TRUE,TRUE)'=>'Allowance',
					'plugin()->traffic_month(strtotime("yesterday"),TRUE,TRUE)'=>'This Month',
					'plugin()->traffic_month(strtotime("first day of last month"),TRUE,TRUE)'=>'Last Month',
					'recur_schedule'=>'Billing',
					'price(TRUE,TRUE)'=>'Price',
					'account->accnum()'=>'Cust ID',
					'account->name()'=>'Customer',
					'date_next_invoice'=>'Next Invoice',
					'due(TRUE)'=>'Due Invoices',
				))
				->prepend(array(
					'id'=>array('url'=>URL::link('user','service/view/')),
				))
			);
	}
}
?>
