<?php
/**
 * 2007-2021 PrestaShop
 *
 * 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:
 * http://opensource.org/licenses/afl-3.0.php
 * 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-2021 PrestaShop SA
 * @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 */

// @codingStandardsIgnoreStart
/* @noinspection AutoloadingIssuesInspection */
/* @noinspection PhpMultipleClassDeclarationsInspection */
/* @noinspection PhpIllegalPsrClassPathInspection */
/* @noinspection PhpDeprecationInspection */
/* @noinspection ReturnTypeCanBeDeclaredInspection */
// @codingStandardsIgnoreEnd

use ComerciaGlobalPayments\AddonPayments\SDK\Api\EPGJs;
use Prestashop\Module\AddonPayments\Operations\Authorize;
use Prestashop\Module\AddonPayments\Services\ApiFactory;

/**
 * Handles payment authorization.
 */
class AddonpaymentsAuthorizeModuleFrontController extends ModuleFrontController
{
    public function initContent()
    {
        if (addonpayments::is17()) {
            parent::initContent();

            return;
        }

        if (null === Tools::getValue('action', null)) {
            $this->throwError();
        }

        $action = 'displayAjax' . ucfirst(Tools::getValue('action'));

        if (!method_exists($this, $action)) {
            $this->throwError();
        }

        $this->{$action}();
    }

    /**
     * Throws a bad request error.
     */
    private function throwError(): void
    {
        $this->ajaxDie(
            json_encode(
                [
                    'status' => 'error',
                    'message' => $this->module->l('Bad request'),
                ]
            )
        );
    }

    /**
     * Handle authorization requests for quickpay operations.
     *
     * The authorization is derived through the /auth endpoint of EPGJs API.
     *
     * @throws \PrestaShopException
     */
    public function displayAjaxQuickpay(): void
    {
        $token = (new Authorize())(
            Tools::getValue('customerId'),
            $this->context->currency->iso_code,
            $this->context->country->iso_code,
            !$this->context->customer->isLogged(),
            Tools::getValue('operationType')
        );

        $this->ajaxDie(
            json_encode(
                [
                    'instanceId' => Tools::getValue('instanceId'),
                    'url' => EPGJs::getEndpoints(ApiFactory::isLive())['base'],
                    'paymentSolution' => Tools::getValue('paymentSolution'),
                    'token' => $token,
                    'validUntil' => (time() * 1000) + ApiFactory::getTokenValidityThreshold(),
                ]
            )
        );
    }

    /**
     * Handle authorization requests for quickpay operations.
     *
     * The authorization is derived through the /auth endpoint of EPGJs API.
     *
     * @throws \PrestaShopException
     */
    public function displayAjaxAllPaysol(): void
    {
        $idAddress = $this->context->cart->id_address_invoice;
        $address = new Address($idAddress);
        $idCountry = $address->id_country;
        $country = new Country($idCountry);

        $token = (new Authorize())(
            Tools::getValue('customerId'),
            $this->context->currency->iso_code,
            $country->iso_code,
            !$this->context->customer->isLogged(),
            Tools::getValue('operationType')
        );

        $this->ajaxDie(
            json_encode(
                [
                    'instanceId' => Tools::getValue('instanceId'),
                    'url' => EPGJs::getEndpoints(ApiFactory::isLive())['base'],
                    'token' => $token,
                    'validUntil' => (time() * 1000) + ApiFactory::getTokenValidityThreshold(),
                ]
            )
        );
    }

    public function displayAjaxBanner()
    {
        $token = (new Prestashop\Module\AddonPayments\Operations\Authorize())(
            ApiFactory::getCustomerIdFromContext($this->context),
            $this->context->currency->iso_code,
            $this->context->country->iso_code,
            !$this->context->customer->isLogged()
        );
        $tokenValidity = (time() * 1000) + ApiFactory::getTokenValidityThreshold();

        $this->ajaxDie(
            json_encode(
                [
                    'token' => $token,
                    'tokenValidity' => $tokenValidity,
                ]
            )
        );
    }

}
