<?php
/**
 * 2007-2019 PrestaShop SA and Contributors.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/AFL-3.0
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 * @author    PrestaShop SA <contact@prestashop.com>
 * @copyright 2007-2019 PrestaShop SA and Contributors
 * @license   https://opensource.org/licenses/AFL-3.0  Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of PrestaShop SA
 */

use Sibs\SibsConstants;
use Sibs\SibsException;
use Sibs\SibsLog;
use Sibs\SibsModels;
use Sibs\SibsPaymentCore;
use Sibs\SibsUtils;

class SibsValidationModuleFrontController extends ModuleFrontController
{
    public function postProcess()
    {
        SibsLog::info('start postProcess');

        $transactionID = Tools::getValue('id');
        $credentials   = SibsUtils::getCredentials();

        SibsLog::info("transactionID: $transactionID");
        SibsLog::info('credentials: ' . print_r($credentials, true));

        $resultJson = SibsPaymentCore::getPaymentStatus($transactionID, $credentials);
        SibsLog::info('resultJson of getPaymentStatus: ' . json_encode($resultJson));

        try {
            if (! $resultJson) {
                throw new SibsException('ERROR_GENERAL_NORESPONSE');
            }

            $this->validatePaymentResponse($resultJson['response']);
        } catch (SibsException $e) {
            $this->redirectErrorResponse($e->getMessage());
        }
    }

    private function validatePaymentResponse($response)
    {
        SibsLog::info('validatePaymentResponse()');

        $returnCode    = $response['returnStatus']['statusCode'];
        $paymentStatus = $response['paymentStatus'];

        SibsLog::info("returnCode: $returnCode");
        SibsLog::info("paymentStatus: $paymentStatus");

        $transactionResult = SibsPaymentCore::getTransactionResult($returnCode, $paymentStatus);
        SibsLog::info("transactionResult: $transactionResult");

        switch($transactionResult) {
            case SibsConstants::SIBS_ACK:
                SibsLog::info('ACK payment');
                $this->doSuccessPayment($response, $paymentStatus);

                break;
            case SibsConstants::SIBS_NOK:
                throw new SibsException($returnCode);

                break;
            default:
                throw new SibsException('ERROR_UNKNOWN');
        }
    }

    public function doSuccessPayment($response, $paymentStatus)
    {
        SibsLog::info('doSuccessPayment()');

        $paymentMethodTools = Tools::getValue('payment_method');
        $paymentMethod      = $response['paymentMethod'];
        $paymentType        = $response['paymentType'];
        $id_transaction     = $response['transactionID'];
        $id_order_state     = SibsPaymentCore::sibs_convert_response_status_to_payment_status($paymentMethod, $paymentStatus);

        SibsLog::info("paymentMethodTools: $paymentMethodTools");
        SibsLog::info("paymentMethod: $paymentMethod");
        SibsLog::info("paymentType: $paymentType");
        SibsLog::info("transactionID: $id_transaction");
        SibsLog::info("id_order_state: $id_order_state");

        if ($id_order_state === SibsConstants::ORDER_STATUS_CANCELED) {
            throw new SibsException('ORDER_CANCELED');
        }

        $customer = new Customer($this->context->cart->id_customer);
        $currency = new Currency($this->context->cart->id_currency);

        $id_module          = $this->module->id;
        $id_cart            = (int) $this->context->cart->id;
        $id_customer        = $customer->id;
        $secure_key         = $customer->secure_key;
        $currency_id        = (int) $currency->id;
        $extraVars          = ['transaction_id' => $id_transaction];
        $amountPaid         = (float) $this->context->cart->getOrderTotal(true, Cart::BOTH);
        $paymentDescription = $this->module->getPaymentDescription($paymentMethodTools);
        $message            = $this->l('Paid by SIBS');

        SibsLog::info("id_module: $id_module");
        SibsLog::info("id_cart: $id_cart");
        SibsLog::info("id_customer: $id_customer");
        SibsLog::info("secure_key: $secure_key");
        SibsLog::info("id_currency: $currency_id");
        SibsLog::info('extraVars: ' . print_r($extraVars, true));
        SibsLog::info("orderTotal: $amountPaid");
        SibsLog::info("paymentDescription: $paymentDescription");
        SibsLog::info("message: $message");

        SibsModels::saveTransactionLog($id_cart, $paymentMethod, $response);

        $this->module->validateOrder(
            $id_cart,
            $id_order_state,
            $amountPaid,
            $paymentDescription,
            $message,
            $extraVars,
            $currency_id,
            false,
            $secure_key
        );
        SibsLog::info('validateOrder()');

        $id_order = $this->module->currentOrder;
        SibsLog::info("id_order: $id_order");

        SibsModels::updateTransLogId($id_order, $id_transaction);

        // SAVE PAYMENT TOKEN
        $hasToken = isset($response['token']);
        SibsLog::info('hasToken ' . var_export($hasToken, true));

        if ($hasToken) {
            $customerID = $this->context->cart->id_customer;
            $token      = $response['token'];

            SibsLog::info('customerID: ' . $customerID);
            SibsLog::info('token: ' . print_r($token, true));

            SibsModels::saveToken($customerID, $token);
        }

        SibsLog::info('end doSuccessPayment()');

        Tools::redirect(
            "index.php?controller=order-confirmation&id_cart={$id_cart}&id_module={$id_module}&id_order={$id_order}&key={$secure_key}"
        );
    }

    public function redirectErrorResponse($returnMessage)
    {
        $this->errors[] = $this->module->getErrorMessage($returnMessage);
        $this->redirectWithNotifications(
            $this->context->link->getPageLink('order', true, null, ['step' => '3'])
        );
    }
}
