<?php

if(!defined('_PS_VERSION_')) 
{
    exit;
}

require_once(_PS_ROOT_DIR_ . '/idealcheckout/includes/library.php');

class IdealcheckoutpaypalReturnModuleFrontController extends ModuleFrontController
{
	/**
	 * @see FrontController::initContent()
	 */
	public function initContent()
	{
		parent::initContent();
		

		if(empty($_GET['order_id']) && empty($_GET['order_code']))
		{			
			
			
		}
		else
		{
			$sOrderId = $_GET['order_id'];
			$sOrderCode = $_GET['order_code'];
			
			// Load database settings
			$aDatabaseSettings = idealcheckout_getDatabaseSettings();
			
			// Lookup transaction
			$sql = "SELECT * FROM `" . $aDatabaseSettings['table'] . "` WHERE (`order_id` = '" . idealcheckout_escapeSql($sOrderId) . "') AND (`order_code` = '" . idealcheckout_escapeSql($sOrderCode) . "') ORDER BY `id` DESC";
			$aTransaction = idealcheckout_database_getRecord($sql);
			
			// Payment succesfull
			if(in_array($aTransaction['transaction_status'], array('SUCCESS')))
			{
				// Get payment params
				$aParams = (empty($aTransaction['order_params']) ? array() : idealcheckout_unserialize($aTransaction['order_params']));
				
				Tools::redirectLink(__PS_BASE_URI__ . 'index.php?controller=order-confirmation&id_cart=' . $aParams['cart']['id'] . '&id_module='. $this->module->id .'&id_order=' . Order::getOrderByCartId(intval($aParams['cart']['id'])) . '&key=' . $this->context->customer->secure_key);				
			}
			elseif(in_array($aTransaction['transaction_status'], array('OPEN', 'PENDING')))
			{
				$sHtml .= '<p>' . idealcheckout_getTranslation(false, 'idealcheckout', 'Payment in progress.') . '</p>';
				Tools::redirectLink(__PS_BASE_URI__ . 'index.php?controller=order-detail&id_order=' . $aTransaction['order_id']);
			}
			else
			{
				// Redirect to checkout
				Tools::redirect('order&step=3');
			}
		}		
	}
}
