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

/**
 * This class provides a order cart
 *
 * @package    Cart
 * @category   Controllers
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Controller_Cart extends Controller_TemplateDefault {
	protected $auth_required = FALSE;

	/**
	 * List the cart contents
	 */
	public function action_index() {
		$output = '';
		$co = Cart::instance();

		// If the cart is empty, we'll return here.
		if (! count($co->contents()))
			Block::add(array(
				'title'=>_('Empty Cart'),
				'body'=>_('The cart is empty')
			));

		else {
			Block::add(array(
				'title'=>_('Cart Items'),
				'body'=>Table::display(
					$co->contents(),
					NULL,
					array(
						'item()->q'=>array('label'=>'Quantity'),
						'item()->i'=>array('label'=>'Item'),
						'item()->t'=>array('label'=>'Total','class'=>'right'),
					),
					array(
						'type'=>'list',
					)
				),
			));

			$checkout = ORM::factory('Checkout')->where_active()->find_all()->as_array();

			foreach ($co->contents() as $cio)
				$checkout = array_intersect($checkout,$cio->checkout()->as_array());

			$payopt = array();
			foreach ($checkout as $cko)
				$payopt[$cko->id] = $cko->name;

			$output .= _('Total amount due for payment').' '.$co->total(TRUE);
			$output .= Form::open('checkout/before');
			$output .= Form::select('checkout_id',$payopt);
			$output .= Form::submit('submit',_('Checkout'));
			$output .= Form::close();

			Block::add(array(
				'title'=>_('Payment'),
				'body'=>$output,
			));
		}
	}

	/**
	 * Add an item to the cart
	 */
	public function action_add() {
		$cart = ORM::factory('Cart');

		$cart->session_id = Session::instance()->id();

		if ($cart->values(Request::current()->post())->check())
			$cart->save();
		else
			throw new Kohana_Exception('Unable to add to cart');

		if ($cart->saved())
			HTTP::redirect('cart/index');
		else
			throw new Kohana_Exception(_('There was a problem adding the item to the cart.'));
	}

	public function action_empty() {
		foreach (ORM::factory('Cart')->where('session_id','=',Session::instance()->id())->find_all() as $co)
			$co->delete();

		$this->template->content = _('Cart Emptied');
	}
}
?>