<?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 SibsPaymentAbstractModuleFrontController extends ModuleFrontController
{
    protected $payment_method = '';

    protected $template_name  = '';

    protected $payment_type   = '';

    protected $payment_brand  = '';

    protected $id_customer    = 'id_customer';

    public $ssl               = true;

    public static $prefix     = _DB_PREFIX_;

    public function setPaymentMethod($paymentMethod)
    {
        $this->payment_method = $paymentMethod;
    }

    public function getPaymentBrandCards()
    {
        $brand = Configuration::get("SIBS_{$this->getPaymentMethod()}_CARDS");

        return str_replace(',', ' ', $brand);
    }

    public function getPaymentMethod()
    {
        return $this->payment_method;
    }

    public function getTemplateName()
    {
        return "module:sibs/views/templates/front/{$this->template_name}";
    }

    public function getPaymentType()
    {
        return $this->payment_type;
    }

    public function getPaymentBrand()
    {
        return $this->payment_brand;
    }

    /**
     * load prestashop function initContent from class ModuleFrontController.
     * @return void
     */
    protected function parentInitContent()
    {
        parent::initContent();
    }

    /**
     * function init content.
     * @return void
     */
    public function initContent()
    {
        try {
            $environment_file = Sibs::getEnvironmentConfig();
            $widget_endpoints = $environment_file['widget_endpoints'];

            SibsLog::info('start render sibs form');

            $this->parentInitContent();

            $this->context->cookie->__set('sibs_paymentBrand', $this->getPaymentMethod());
            $this->context->cookie->write();
            SibsLog::info("cookie sibs_paymentBrand: {$this->context->cookie->__get('sibs_paymentBrand')}");

            $lang = $this->getLanguage();

            $transactionParameter = $this->getTransactionParameter();
            SibsLog::info('transactionParameter: ' . print_r($transactionParameter, true));

            // get checkout response
            $checkoutResult = SibsPaymentCore::getCheckoutResult($transactionParameter, $lang);
            SibsLog::info('checkoutResult: ' . print_r($checkoutResult, true));

            $response = $checkoutResult['response'];

            if (! $checkoutResult['is_valid'] || empty($response['returnStatus']['statusCode']) || $response['returnStatus']['statusCode'] !== '000') {
                throw new SibsException('ERROR_GENERAL_REDIRECT');
            }

            $paymentWidgetUrl = SibsPaymentCore::getPaymentWidgetUrl(
                $transactionParameter,
                $response['transactionID'],
                $widget_endpoints
            );
            SibsLog::info("paymentWidgetUrl: $paymentWidgetUrl");
            SibsLog::info("result transactionID: {$response['transactionID']}");

            $paymentWidgetContent = SibsPaymentCore::getResponseData(
                $paymentWidgetUrl,
                $transactionParameter['server_mode'],
                'GET',
                '',
                'json'
            );

            if (! $paymentWidgetContent['is_valid'] || SibsUtils::strContains($paymentWidgetContent['response'], 'errorDetail')) {
                throw new SibsException('ERROR_GENERAL_REDIRECT');
            }

            SibsLog::info("result transactionID: {$response['transactionID']}");

            $formConfig  = $this->getFormConfig($response, $transactionParameter, $lang);
            $formStyle   = $this->getFormStyle();
            $formContext = isset($response['formContext']) ? $response['formContext'] : null;
            $signature   = isset($response['transactionSignature']) ? $response['formContext'] : null;

            SibsLog::info("formConfig: $formConfig");
            SibsLog::info("formStyle: $formStyle");
            SibsLog::info("formContext: $formContext");
            SibsLog::info("signature: $signature");

            $responseURL = $this->context->link->getModuleLink(
                'sibs',
                'validation',
                ['payment_method' => $this->getPaymentMethod()],
                true
            );

            $templateParameters = [
                'fullname'         => "{$this->context->customer->firstname} {$this->context->customer->lastname}",
                'paymentWidgetUrl' => $paymentWidgetUrl,
                'frameTestMode'    => SibsUtils::getTestMode($this->payment_method),
                'paymentBrand'     => $this->getPaymentBrand(),
                'total'            => $this->context->cart->getOrderTotal(true, Cart::BOTH),
                'cancelUrl'        => $this->context->link->getPageLink('order', true, null, ['step' => '3']),
                'is_guest'         => $this->context->customer->is_guest,
                'responseUrl'      => $responseURL,
                'this_path'        => $this->module->getPathUri(),
                'formConfig'       => $formConfig,
                'formContext'      => $formContext,
                'signature'        => $signature,
                'formStyle'        => $formStyle,
                'this_path_ssl'    => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . "modules/{$this->module->name}/",
            ];
            SibsLog::info('templateParameters: ' . print_r($templateParameters, true));

            $this->context->smarty->assign($templateParameters);
            $this->setTemplate($this->getTemplateName());
            SibsLog::info('get template: ' . print_r($this->getTemplateName(), true));

            SibsLog::info('end render sibs form');
        } catch (SibsException $e) {
            $this->redirectWithErrorMessage($e->getErrorMessage());
        }
    }

    public function getFormConfig($response, $transactionParameter, $lang)
    {
        $redirect_url =  $this->context->link->getModuleLink(
            'sibs',
            'validation',
            [
                'payment_method' => $this->getPaymentMethod(),
                'id'             => $response['transactionID'],
            ],
            true
        );

        $amount_value    = $this->context->cart->getOrderTotal(true, Cart::BOTH);
        $amount_currency = isset($response['amount']['currency']) ? $response['amount']['currency'] : null;

        $formConfig = [
            'paymentMethodList' => SibsPaymentCore::sibs_get_payment_method_for_spg($this->getPaymentMethod()),
            'amount'            => [
                'value'    => $amount_value,
                'currency' => $amount_currency,
            ],
            'language'     => $lang,
            'redirectUrl'  => $redirect_url,
            'customerData' => $this->getCustomerData($transactionParameter),
        ];

        return json_encode($formConfig);
    }

    public function getFormStyle()
    {
        // TODO: get form style custom data
        $formStyle = [
            'layout' => 'default',
            'theme'  => 'default',
            'color'  => [
                'primary'   => '',
                'secondary' => '',
                'border'    => '',
                'surface'   => '',
                'header'    => [
                    'text'       => '',
                    'background' => '',
                ],
                'body' => [
                    'text'       => '',
                    'background' => '',
                ],
            ],
            'font' => '',
        ];

        return json_encode($formStyle);
    }

    public function getCustomerData($transactionParameter)
    {
        $customerName  = $transactionParameter['customer']['first_name'] . ' ' . $transactionParameter['customer']['last_name'];
        $customerEmail = $transactionParameter['customer']['email'];

        $customerData = [
            'customerName'  => $customerName,
            'customerEmail' => $customerEmail,
        ];

        return $customerData;
    }

    /**
     * redirect and show the error message.
     * @param  string $message
     * @return void
     */
    public function redirectWithErrorMessage($message)
    {
        $this->errors[] = $this->module->getErrorMessage($message);
        $this->redirectWithNotifications(
            $this->context->link->getPageLink('order', true, null, ['step' => '3'])
        );
    }

    /**
     * return transaction parameter to be sent to the gateway.
     * @return array
     */
    public function getTransactionParameter()
    {
        $currencyobj = new Currency((int) $this->context->cart->id_currency);
        $currency    = $currencyobj->iso_code;

        $paymentMethod                       = $this->getPaymentMethod();
        $credentials                         = SibsUtils::getCredentials();
        $customer                            = $this->getCustomerParameter();
        $payment                             = $this->getPaymentParameter($currency, $paymentMethod);
        $transactionParameter                = array_merge($credentials, $customer, $payment);
        $transactionParameter['customer_ip'] = $this->getCustomerIP();

        // added description for blik
        if ($this->getPaymentMethod() == SibsConstants::PAYMENT_METHOD_BLIK) {
            $transactionParameter['descriptor'] = Configuration::get('PS_SHOP_NAME');
        }

        return $transactionParameter;
    }

    /**
     * return all parameters that required for complete the payment.
     *
     * @param  string $currency
     * @param  string $paymentMethod
     * @return array
     */
    private function getPaymentParameter($currency, $paymentMethod)
    {
        $sibs_transactionid = date('ymd') . $this->context->cart->id;
        $this->context->cookie->__set('sibs_transactionid', $sibs_transactionid);
        $this->context->cookie->write();

        $transaction = [
            'id_transaction' => $sibs_transactionid,
            'payment_type'   => $this->getPaymentType(),
            'amount'         => $this->context->cart->getOrderTotal(true, Cart::BOTH),
            'currency'       => $currency,
            'test_mode'      => SibsUtils::getTestMode($paymentMethod),
            'payment_method' => $paymentMethod,
        ];

        return $transaction;
    }

    public function getCustomerParameter()
    {
        $customerID       = (int) $this->context->cookie->__get('id_customer');
        $address_shipping = new Address((int) $this->context->cart->id_address_delivery);
        $country_shipping = new Country($address_shipping->id_country);

        $address_billing = new Address((int) $this->context->cart->id_address_invoice);
        $country_billing = new Country($address_billing->id_country);

        $customer = [
            'customer' => [
                'first_name' => $this->context->customer->firstname,
                'last_name'  => $this->context->customer->lastname,
                'email'      => $this->context->customer->email,
                'phone'      => SibsModels::getPhoneNumber($customerID),
                'birthdate'  => $this->context->customer->birthday,
                'sex'        => ($this->context->customer->id_gender == '1') ? 'M' : 'F',
            ],
            'shipping' => [
                'street'       => $address_shipping->address1 . $address_shipping->address2,
                'city'         => $address_shipping->city,
                'zip'          => $address_shipping->postcode,
                'country_code' => $country_shipping->iso_code,
            ],
            'billing' => [
                'street'       => $address_billing->address1 . $address_billing->address2,
                'city'         => $address_billing->city,
                'zip'          => $address_billing->postcode,
                'country_code' => $country_billing->iso_code,
            ],
        ];

        return $customer;
    }

    public function getCartItems()
    {
        $percent   = 100;
        $cartItems = [];
        $carts     = $this->context->cart->getProducts();

        foreach ($carts as $cart) {
            $priceWithTax    = number_format($cart['price_without_reduction'], 2);
            $priceWithDisc   = number_format($cart['price_with_reduction'], 2);
            $priceWithoutTax = number_format($cart['price_with_reduction_without_tax'], 2);

            $discount = (($priceWithTax - $priceWithDisc) * $percent) / $priceWithTax;
            $tax      = (($priceWithDisc - $priceWithoutTax) * $percent) / $priceWithDisc;

            array_push($cart, [
                'merchant_item_id' => $cart['id_product'],
                'discount'         => $discount,
                'quantity'         => $cart['cart_quantity'],
                'name'             => $cart['name'],
                'price'            => $priceWithTax,
                'tax'              => number_format($tax, 0),
            ]);
        }

        return ['cartItems' => $cartItems];
    }

    public function getCustomerIP()
    {
        $customerIP = $_SERVER['REMOTE_ADDR'];

        return ($customerIP == '::1') ? '127.0.0.1' : $customerIP;
    }

    protected function getLanguage()
    {
        $langobj       = new Language((int) $this->context->cart->id_lang);
        $lang_iso_code = $langobj->iso_code;

        switch ($lang_iso_code) {
            case 'pl':
                $lang = $lang_iso_code;

                break;
            default:
                $lang = 'en';
        }

        return $lang;
    }

    /**
     * check if a cart not empty.
     * @return bool
     */
    public function isCartItemEmpty()
    {
        $cartItem = $this->getCartItems();

        if (empty($cartItem['cartItems'])) {
            return false;
        }

        return true;
    }
}
