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

/**
 * This class provides checkout capabilities.
 *
 * @package    Checkout
 * @category   Controllers
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Controller_Checkout extends Controller_TemplateDefault {
	protected $auth_required = FALSE;
	protected $secure_actions = array(
		'before'=>TRUE,
		'after'=>TRUE,
		'cancel'=>TRUE,
	);

	public function action_index() {
		HTTP::redirect('cart');
	}

	public function action_before() {
		// If we are not here by a POST operation, we'll redirect to the cart.
		if (! $cid=Request::current()->post('checkout_id'))
			HTTP::redirect('cart');

		$co = ORM::factory('Checkout',$cid);

		Block::add(array(
			'title'=>'Checkout',
			'body'=>$co->plugin()->before(Cart::instance()),
		));

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

	public function action_after() {
		$co = ORM::factory('Checkout',$this->request->param('id'));

		if (! $co->loaded())
			HTTP::redirect('/');

		return method_exists($co->plugin(),'after') ? $co->plugin()->after(Cart::instance()) : HTTP::redirect('/');
	}

	public function action_cancel() {
		$co = ORM::factory('Checkout',$this->request->param('id'));

		if (! $co->loaded())
			HTTP::redirect('cart');

		return method_exists($co->plugin(),'cancel') ? $co->plugin()->cancel(Cart::instance()) : HTTP::redirect('cart');
	}

	public function action_notify() {
		$test_id = FALSE;
		$co = ORM::factory('Checkout',$this->request->param('id'));

		if ((! $co->loaded() OR ! Request::current()->post()) AND ! ($test_id=Kohana::$config->load('debug')->checkout_notify))
			throw HTTP_Exception::factory(404,'Payment not found!');

		$this->auto_render = FALSE;

		$cno = ORM::factory('Checkout_Notify');

		if (! $test_id) {
			$cno->checkout_id = $co->id;
			$cno->status = 1;
			$cno->data = Request::current()->post();
			$cno->save();
		} else {
			$cno->where('id','=',$test_id)->find();
		}

		if (! $cno->loaded())
			throw HTTP_Exception::factory(500,'Unable to save!');

		// Process our Notify
		try {
			$this->response->body($cno->process());

		} catch (Exception $e) {
			$this->response->body('Received, thank you!');
		}

		$this->response->headers('Content-Type','text/plain');
		$this->response->headers('Content-Length',(string)$this->response->content_length());
		$this->response->headers('Last-Modified',time());
	}
}
?>