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

/**
 * This class provides checkout capabilities.
 *
 * @package    OSB
 * @subpackage Checkout
 * @category   Controllers
 * @author     Deon George
 * @copyright  (c) 2010 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Controller_Checkout extends Controller_TemplateDefault {
	protected $auth_required = TRUE;
	protected $noauth_redirect = 'login/register';

	/**
	 * This is the main call to export, providing a list of items to export and
	 * setting up the page to call the export plugin when submitted.
	 */
	public function action_index() {
		if ($_POST)
			return $this->checkout();

		// @todo - this should be a global config item
		$mediapath = Route::get('default/media');

		// @todo Items in the cart dont have account_id if they were put in the cart when the user was not logged in

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

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

			// Show a list of items in the cart
			$output = '<table class="checkout_cartlist" border="0">';
			foreach (Cart::instance()->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/checkout_list')
					->set('price_firstinvoice',$item->quantity*$ppa[$item->recurr_schedule]['price_base']*$pdata['prorata'])
					->set('price_setup',$item->quantity*$ppa[$item->recurr_schedule]['price_setup'])
					->set('service_start',$pdata['date'])
					->set('service_end',$pdata['end'])
					->set('price_recurring',$item->quantity*$ppa[$item->recurr_schedule]['price_base'])
					->set('item',$item)
					->set('mediapath',$mediapath);
			}
			$output .= '</table>';

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

			$po = ORM::factory('checkout')
				->payment_options_cart();

			// @todo Country value should come from somewhere?
			Block::add(array(
				'title'=>_('Order Total'),
				'body'=>View::factory('cart/checkout_total')
					->set('cart',Cart::instance())
					->set('country',61),
			));

			$output = Form::open();
			$output .= '<table class="payment_options_box" border="0">';

			foreach ($po as $payment) {
				$output .= View::factory('checkout/payment_option')
					->set('payment',$payment);
			}

			// @todo Add Javascript to stop submission if something not selected
			$output .= '<tr><td>&nbsp;</td></tr>';
			$output .= '<tr>';
			$output .= sprintf('<td>%s</td>',Form::submit('submit',_('Submit Order')));
			$output .= '</tr>';

			$output .= '</table>';
			$output .= Form::close();

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

		// Suppress our right hand tab
		$this->template->right = ' ';
	}

	/**
	 * Process checkout
	 */
	private function checkout() {
		$invoice = ORM::factory('invoice');

		// Add our individual items to the invoice
		foreach (Cart::instance()->contents()->find_all() as $item) {
			$invoice_item = $invoice->add_item();

			$invoice_item->product_id = $item->product_id;
			$invoice_item->product_attr = $item->product_attr;
			$invoice_item->product_attr_cart = $item->product_attr;
			$invoice_item->quantity = $item->quantity;
			$invoice_item->recurring_schedule = $item->recurr_schedule;

			$ppa = $item->product->get_price_array();
			$period = Period::details($item->recurr_schedule,$item->product->price_recurr_weekday,time(),TRUE);
			// @todo rounding should be a global config
			$invoice_item->price_base = round($item->quantity*$ppa[$item->recurr_schedule]['price_base']*$period['prorata'],2);
			$invoice_item->price_setup = round($item->quantity*$ppa[$item->recurr_schedule]['price_setup'],2);
		}

		$invoice->account_id = Auth::instance()->get_user()->id;
		$invoice->type = 2; // INVOICED VIA CHECKOUT
		$invoice->status = 1; // INVOICE IS NOT CANCELLED
		$invoice->due_date = time(); // DATE INVOICE MUST BE PAID
		$invoice->billed_currency_id = 6; // @todo This should come from the site config or the currency selected
		/*
		$invoice->process_status = NULL; // TO BE PROCESSED
		$invoice->billing_status = NULL; // UNPAID
		$invoice->refund_status = NULL; // NOT REFUNDED
		$invoice->print_status = NULL; // NOT YET PRINTED
		$invoice->discount_amt = NULL; // @todo CALCULATE DISCOUNTS
		$invoice->checkout_plugin_id = NULL; // @todo Update the selected checkout plugin
		$invoice->checkout_plugin_data = NULL; // @todo Data required for the checkout plugin
		*/

		if ($invoice->check())
			$invoice->save();
		else
			throw new Kohana_Exception('Problem saving invoice - Failed check()');
	}
}
?>