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

/**
 * This class provides a order cart
 *
 * @package    Cart
 * @category   Helpers
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Cart {
	private $id = NULL;

	public function __construct($id=NULL) {
		$this->id = is_null($id) ? Session::instance()->id() : $id;
	}

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

	public function checkout() {
		$result = array();

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

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

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

		return $result;
	}

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

	public function get($mid,$item) {
		return ORM::factory('Cart')
			->where('session_id','=',$this->id)
			->and_where('module_id','=',$mid)
			->and_where('module_item','=',$item)
			->find_all();
	}

	public function id() {
		return $this->id;
	}

	public static function instance($id=NULL) {
		return new Cart($id);
	}

	public function total($format=FALSE) {
		$total = 0;

		foreach ($this->contents() as $cio)
			$total += $cio->item()->t;

		return $format ? Currency::display($total) : $total;
	}
}
?>
