<?php


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

class IdealcheckoutvisaValidationModuleFrontController extends ModuleFrontController
{
    /**
     * @see FrontController::postProcess()
     */
    public function postProcess()
    {
        $oCart = $this->context->cart;
		
        if($oCart->id_customer == 0 || $oCart->id_address_delivery == 0 || $oCart->id_address_invoice == 0 || !$this->module->active) 
		{
            Tools::redirect('index.php?controller=order&step=1');
        }

        // Check that this payment option is still available in case the customer changed his address just before the end of the checkout process
        $bAuthorized = false;
		
        foreach(Module::getPaymentModules() as $aModule) 
		{
            if($aModule['name'] == 'idealcheckoutvisa') 
			{
                $bAuthorized = true;
                break;
            }
        }

        if(!$bAuthorized) 
		{
            die($this->module->l('This payment method is not available.', 'validation'));
        }
		
		$this->context->smarty->assign([
            'params' => $_REQUEST,
        ]);

        //$this->setTemplate('payment_return.tpl');

        $oCustomer = new Customer($oCart->id_customer);
		$oPaymentAddress = new Address(intval($oCart->id_address_invoice));
		$oShipmentAddress = new Address(intval($oCart->id_address_delivery));
		
        if(!Validate::isLoadedObject($oCustomer))
		{
			Tools::redirect('index.php?controller=order&step=1');
		}

        $fTotal = (float)$oCart->getOrderTotal(true, Cart::BOTH);		
        $iOrderId = (int)Order::getOrderByCartId($oCart->id);
        $oCurrency = $this->context->currency;
		

		// Load database settings
		$aDatabaseSettings = idealcheckout_getDatabaseSettings();
		
		$sLanguageCode = '';

		if(is_callable('Context::getContext'))
		{
			$oContect = Context::getContext();

			if(isset($oContect->language->iso_code))
			{
				$sLanguageCode = substr($oContect->language->iso_code, 0, 2);
			}
		}

		if(!in_array($sLanguageCode, array('nl', 'de', 'en')))
		{
			$sLanguageCode = 'nl';
		}		

		$sStoreCode = idealcheckout_getStoreCode();
		$sGatewayCode = 'visa';
		
		// $sLanguageCode = ''; // nl, de, en
		$sCountryCode = '';
		$sCurrencyCode = 'EUR';

		$sOrderId = $oCart->id;
		$sOrderCode = idealcheckout_getRandomCode(32);
		$aOrderParams = array();
		$sTransactionId = idealcheckout_getRandomCode(32);
		$sTransactionCode = idealcheckout_getRandomCode(32);
		$fTransactionAmount = $fTotal;
		
		$sReturnUrl = $this->context->link->getModuleLink('idealcheckoutvisa', 'return', array('cart_id' => $oCart->id, 'order_id' => $sOrderId, 'order_code' => $sOrderCode));

		$sTransactionDescription = idealcheckout_getTranslation($sLanguageCode, 'idealcheckout', 'Webshop order #{0}', array($sOrderId));
		$sTransactionPaymentUrl = ''; // $sRootUrl . 'modules/idealcheckoutideal/validation.php?order_id=' . $sOrderId . '&order_code=' . $sOrderCode;
		$sTransactionSuccessUrl = $sReturnUrl;
		$sTransactionPendingUrl = $sReturnUrl;
		$sTransactionFailureUrl = $sReturnUrl;


		// Store ORDER information
		$aOrderParams['cart'] = array(
			'id' => $oCart->id, 
			'secure_key' => $this->context->customer->secure_key
		);
	
		
		$aOrderParams['customer'] = array();

		$iCountryId = $oShipmentAddress->id_country;
		
		$sql = "SELECT `iso_code` FROM `" . $aDatabaseSettings['prefix'] . "country` WHERE (`id_country` = '" . idealcheckout_escapeSql($iCountryId) . "') ORDER BY `id_country` DESC LIMIT 1";
		$sIsoCode = idealcheckout_database_getRecord($sql);
		
		
		
		// Shipment data
		list($sStreetName, $sStreetNumber, $sExtension) = idealcheckout_mb_splitAddress($oShipmentAddress->address1);

		$aOrderParams['customer']['shipment_company'] = ''; // $oShipmentAddress->company;
		$aOrderParams['customer']['shipment_name'] = $oShipmentAddress->firstname . ' ' . $oShipmentAddress->lastname;
		$aOrderParams['customer']['shipment_first_name'] = $oShipmentAddress->firstname;
		$aOrderParams['customer']['shipment_last_name'] = $oShipmentAddress->lastname;
		$aOrderParams['customer']['shipment_gender'] = '';
		$aOrderParams['customer']['shipment_date_of_birth'] = '';
		$aOrderParams['customer']['shipment_phone'] = ($oShipmentAddress->phone_mobile ? $oShipmentAddress->phone_mobile : $oShipmentAddress->phone);
		$aOrderParams['customer']['shipment_email'] = $oCustomer->email;
		$aOrderParams['customer']['shipment_address'] = $oShipmentAddress->address1;
		$aOrderParams['customer']['shipment_street_name'] = $sStreetName;
		$aOrderParams['customer']['shipment_street_number'] = $sStreetNumber;
		$aOrderParams['customer']['shipment_street_number_extension'] = $sExtension;
		$aOrderParams['customer']['shipment_zipcode'] = $oShipmentAddress->postcode;
		$aOrderParams['customer']['shipment_city'] = $oShipmentAddress->city;
		$aOrderParams['customer']['shipment_country_code'] = $sIsoCode['iso_code'];
		$aOrderParams['customer']['shipment_country_name'] = $oShipmentAddress->country;

		
		$iCountryId = $oPaymentAddress->id_country;
		
		$sql = "SELECT `iso_code` FROM `" . $aDatabaseSettings['prefix'] . "country` WHERE (`id_country` = '" . idealcheckout_escapeSql($iCountryId) . "') ORDER BY `id_country` DESC LIMIT 1";
		$sIsoCode = idealcheckout_database_getRecord($sql);

		// Payment data
		list($sStreetName, $sStreetNumber, $sExtension) = idealcheckout_mb_splitAddress($oPaymentAddress->address1);

		$aOrderParams['customer']['payment_company'] = ''; // $oPaymentAddress->company;
		$aOrderParams['customer']['payment_name'] = $oPaymentAddress->firstname . ' ' . $oPaymentAddress->lastname;
		$aOrderParams['customer']['payment_first_name'] = $oPaymentAddress->firstname;
		$aOrderParams['customer']['payment_last_name'] = $oPaymentAddress->lastname;
		$aOrderParams['customer']['payment_gender'] = '';
		$aOrderParams['customer']['payment_date_of_birth'] = '';
		$aOrderParams['customer']['payment_phone'] = ($oPaymentAddress->phone_mobile ? $oPaymentAddress->phone_mobile : $oPaymentAddress->phone);
		$aOrderParams['customer']['payment_email'] = $oCustomer->email;
		$aOrderParams['customer']['payment_address'] = $oPaymentAddress->address1;
		$aOrderParams['customer']['payment_street_name'] = $sStreetName;
		$aOrderParams['customer']['payment_street_number'] = $sStreetNumber;
		$aOrderParams['customer']['payment_street_number_extension'] = $sExtension;
		$aOrderParams['customer']['payment_zipcode'] = $oPaymentAddress->postcode;
		$aOrderParams['customer']['payment_city'] = $oPaymentAddress->city;
		$aOrderParams['customer']['payment_country_code'] = $sIsoCode['iso_code'];
		$aOrderParams['customer']['payment_country_name'] = $oPaymentAddress->country;

		
		
		// Products
		$aOrderParams['products'] = array();

		$fTotalAmountIncl = 0.00;
		$fTotalAmountExcl = 0.00;

		foreach($oCart->getProducts() as $k => $aProduct)
		{
			$fPriceIncl = round($aProduct['price_wt'], 2);
			$fPriceExcl = round($aProduct['price'], 2);
			$fPriceVat = round($aProduct['price_wt'] - $aProduct['price'], 2);
			$fVatPercentage = round($aProduct['rate'], 2);

			$fQuantity = $aProduct['cart_quantity'];

			$fTotalAmountIncl += ($fPriceIncl * $fQuantity);
			$fTotalAmountExcl += ($fPriceExcl * $fQuantity);

			$aOrderParams['products'][] = array('code' => $aProduct['id_product'], 'description' => $aProduct['name'], 'quantity' => $fQuantity, 'price_incl' => $fPriceIncl, 'price_excl' => $fPriceExcl, 'vat' => $fVatPercentage);
		}

		// Shipment costs?
		$fShipmentIncl = $oCart->getTotalShippingCost();
		$fShipmentExcl = $oCart->getTotalShippingCost(NULL, false);

		if(!empty($fShipmentIncl))
		{
			$fShipmentTaxPercentage = round((($fShipmentIncl - $fShipmentExcl) / $fShipmentExcl) * 100, 0);

			$fTotalAmountIncl += $fShipmentIncl;
			$fTotalAmountExcl += $fShipmentExcl;

			$aOrderParams['products'][] = array('code' => 'SHIPPING', 'description' => 'Verzendkosten', 'quantity' => '1', 'price_incl' => $fShipmentIncl, 'price_excl' => $fShipmentExcl, 'vat' => $fShipmentTaxPercentage);
		}


		// Wrapping costs?
		$fWrappingIncl = $oCart->getOrderTotal(true, 6);
		$fWrappingExcl = $oCart->getOrderTotal(false, 6);

		if(!empty($fWrappingIncl))
		{
			$fWrappingTaxPercentage = round((($fWrappingIncl - $fWrappingExcl) / $fWrappingExcl) * 100, 0);

			$fTotalAmountIncl += $fWrappingIncl;
			$fTotalAmountExcl += $fWrappingExcl;

			$aOrderParams['products'][] = array('code' => 'WRAPPING', 'description' => 'Inpakken', 'quantity' => '1', 'price_incl' => $fWrappingIncl, 'price_excl' => $fWrappingExcl, 'vat' => $fWrappingTaxPercentage);
		}


		// Discounts?
		$aDiscount = $oCart->getDiscounts();
		
		if(is_array($aDiscount) && !empty($aDiscount))
		{
			$fPriceIncl = 0 - round($aDiscount[0]['value_real'], 2);
			$fPriceExcl = 0 - round($aDiscount[0]['value_tax_exc'], 2);
			$fTaxPercentage = round((($fPriceIncl - $fPriceExcl) / $fPriceExcl) * 100, 0);

			$fTotalAmountIncl += $fPriceIncl;
			$fTotalAmountExcl += $fPriceExcl;

			$aOrderParams['products'][] = array('code' => 'DISCOUNT', 'description' => $aDiscount[0]['description'], 'quantity' => '1', 'price_incl' => $fPriceIncl, 'price_excl' => $fPriceExcl, 'vat' => $fTaxPercentage);
		}

		$fCorrection = round($fTransactionAmount - $fTotalAmountIncl, 2);

		if($fCorrection != 0.00)
		{
			$aOrderParams['products'][] = array('code' => 'CORRECTION', 'description' => 'Correctie', 'quantity' => '1', 'price_incl' => $fCorrection, 'price_excl' => $fCorrection, 'vat' => 0);
		}

		// Insert into #_transactions
		$sql = "INSERT INTO `" . $aDatabaseSettings['table'] . "` SET 
`id` = NULL, 
`order_id` = '" . idealcheckout_escapeSql($sOrderId) . "', 
`order_code` = '" . idealcheckout_escapeSql($sOrderCode) . "', 
`order_params` = '" . idealcheckout_escapeSql(idealcheckout_serialize($aOrderParams)) . "', 
`store_code` = " . (empty($sStoreCode) ? "NULL" : "'" . idealcheckout_escapeSql($sStoreCode) . "'") . ", 
`gateway_code` = '" . idealcheckout_escapeSql($sGatewayCode) . "', 
`language_code` = " . (empty($sLanguageCode) ? "NULL" : "'" . idealcheckout_escapeSql($sLanguageCode) . "'") . ", 
`country_code` = " . (empty($sCountryCode) ? "NULL" : "'" . idealcheckout_escapeSql($sCountryCode) . "'") . ", 
`currency_code` = '" . idealcheckout_escapeSql($sCurrencyCode) . "', 
`transaction_id` = '" . idealcheckout_escapeSql($sTransactionId) . "', 
`transaction_code` = '" . idealcheckout_escapeSql($sTransactionCode) . "', 
`transaction_params` = NULL, 
`transaction_date` = '" . idealcheckout_escapeSql(time()) . "', 
`transaction_amount` = '" . idealcheckout_escapeSql($fTransactionAmount) . "', 
`transaction_description` = '" . idealcheckout_escapeSql($sTransactionDescription) . "', 
`transaction_status` = NULL, 
`transaction_url` = NULL, 
`transaction_payment_url` = " . ($sTransactionPaymentUrl ? "'" . idealcheckout_escapeSql($sTransactionPaymentUrl) . "'" : "NULL") . ", 
`transaction_success_url` = " . ($sTransactionSuccessUrl ? "'" . idealcheckout_escapeSql($sTransactionSuccessUrl) . "'" : "NULL") . ", 
`transaction_pending_url` = " . ($sTransactionPendingUrl ? "'" . idealcheckout_escapeSql($sTransactionPendingUrl) . "'" : "NULL") . ", 
`transaction_failure_url` = " . ($sTransactionFailureUrl ? "'" . idealcheckout_escapeSql($sTransactionFailureUrl) . "'" : "NULL") . ", 
`transaction_log` = NULL;";

		idealcheckout_database_query($sql);
		
		
		$iOrderState = 1000; // Awaiting payment
		$this->module->validateOrder($oCart->id, $iOrderState, $fTransactionAmount, 'Visa', 'Betaling wordt gestart', array(), false, false, $this->context->customer->secure_key);
		
	
		$sRootUrl = _PS_BASE_URL_SSL_ . __PS_BASE_URI__;
		
		// Redirect to setup.php
		Tools::redirect($sRootUrl . 'idealcheckout/setup.php?order_id=' . $sOrderId . '&order_code=' . $sOrderCode);


    }
}
