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

/**
 * This class provides a order cart
 *
 * @package    OSB
 * @subpackage Cart
 * @category   Helpers
 * @author     Deon George
 * @copyright  (c) 2010 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
class Cart {
	public static function instance() {
		return new Cart;
	}

	/**
	 * Return a list of items in the cart
	 */
	public function contents() {
		return ORM::factory('cart')
			->where('session_id','=',Session::instance()->id());
	}

	/**
	 * Print an HTML cart list
	 *
	 * @param bool $detail List a detailed cart or a summary cart
	 */
	public function cart_block() {
		// If the cart is empty, we'll return here.
		if (! $this->contents()->count_all())
			return 'The cart is empty.';

		Style::add(array(
			'type'=>'file',
			'data'=>'css/cart_blocklist.css',
			));

		$output = '<table class="cart_blocklist" border="0">';
		foreach ($this->contents()->find_all() as $item) {
			$ppa = $item->product->get_price_array();
			$pdata = Period::details($item->recurr_schedule,$item->product->price_recurr_weekday,time(),TRUE);

			$output .= View::factory('cart/block_list')
				->set('item',$item)
				->set('price_setup',$item->quantity*$ppa[$item->recurr_schedule]['price_setup'])
				->set('price_firstinvoice',$item->quantity*$ppa[$item->recurr_schedule]['price_base']*$pdata['prorata']);
		}

		$output .= '<tr class="submit">';
		$output .= sprintf('<td colspan="3">%s&nbsp;%s</td>',
			Form::button('checkout','Checkout',array('type' => 'submit')),
			Form::button('empty','Empty',array('type' => 'submit')));
		$output .= '</tr>';
		$output .= '</table>';

		return $output;
	}

	/**
	 * Test to see if the cart has some trial options
	 *
	 * @return boolean
	 */
	public function has_trial() {
		foreach ($this->contents()->find_all() as $item)
			if ($item->product->is_trial())
				return TRUE;

		return FALSE;
	}

	public function subtotal() {
		$total = 0;

		foreach ($this->contents()->find_all() as $item) {
			$ppa = $item->product->get_price_array();
			$period = Period::details($item->recurr_schedule,$item->product->price_recurr_weekday,time(),TRUE);

			$total += $item->quantity*$ppa[$item->recurr_schedule]['price_base']*$period['prorata'];
			$total += $item->quantity*$ppa[$item->recurr_schedule]['price_setup'];
		}

		return $total;
	}

	/**
	 * Calculate Tax for the cart items
	 *
	 * @return unknown_type
	 * @uses Tax
	 */
	public function tax() {
		// @todo Tax zone should come from somewhere else
		return Tax::detail(61,NULL,$this->subtotal());
	}

	public function total() {
		// @todo Tax zone should come from somewhere else
		return $this->subtotal()+Tax::total(61,NULL,$this->subtotal());
	}
}
?>
