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

/**
 * This class provides User Service functions
 *
 * @package    Service
 * @category   Controllers/User
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Controller_User_Service extends Controller_Service {
	protected $secure_actions = array(
		'ajaxmanage'=>TRUE,
		'list'=>TRUE,
		'view'=>TRUE,
	);

	/**
	 * This ajax functions obtains the manage button login/password for this service
	 */
	public function action_ajaxmanage() {
		$so = ORM::factory('Service',$this->request->param('id'));
		$k = Session::instance()->get_once('manage_button');
		$amo = $so->plugin(isset($_REQUEST['t']) ? $_REQUEST['t'] : '');

		$o = array(
			'u'=>$amo->username() ? $amo->username() : strtolower($amo->name()),
			'p'=>(! $k OR ! $this->request->is_ajax() OR ! $so->loaded() OR ! isset($_REQUEST['k']) OR $k != $_REQUEST['k']) ? Random::char() : $amo->password(),
		);

		$this->response->headers('Content-Type','application/json');
		$this->response->body(json_encode($o));
	}

	/**
	 * Show a list of services
	 */
	public function action_list() {
		Block::factory()
			->title(sprintf('Services for Account: %s',$this->ao->accnum()))
			->title_icon('icon-th-list')
			->body(Table::factory()
				->jssort('services')
				->data($this->ao->service->find_all())
					->columns(array(
						'id'=>'ID',
						'service_name()'=>'Service',
						'recur_schedule'=>'Billing',
						'price(TRUE,TRUE)'=>'Price',
						'status'=>'Active',
					))
					->prepend(array(
						'id'=>array('url'=>URL::link('user','service/view/')),
					))
			);
	}

	public function action_view() {
		list($id,$output) = Table::page(__METHOD__);

		$so = ORM::factory('Service',$id);

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

		$output .= View::factory('service/user/view')
			->set('o',$so);

		Block::factory()
			->title(sprintf('%s: %s',$so->id(),$so->service_name()))
			->title_icon('icon-list-alt')
			->body($output);
	}
}
?>