<?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 Prestashop\Module\AddonPayments\Decorators\LegacyPaymentOption;

/**
 * Handle payment options display on checkout.
 */
class AddonpaymentsPaymentModuleFrontController extends ModuleFrontController
{
    public $ssl = _PS_USE_SSL_;

    public $display_column_left = false;

    /**
     * @var addonpayments
     */
    public $module;

    public function initContent()
    {
        $this->display_column_left = false;
        $this->display_column_right = false;

        parent::initContent();

        $cart = $this->context->cart;

        if ($cart->id !== (int) Tools::getValue('cart_id', 0)) {
            PrestaShopLogger::addLog(
                'The requested payment form does not belongs to current cart',
                3,
                0,
                'Cart',
                $cart->id
            );
            $this->redirectToPaymentStep();
        }

        if ($cart->secure_key !== Tools::getValue('secure_key', null)) {
            PrestaShopLogger::addLog('The secure key is invalid', 3, 0, 'Cart', $cart->id);
            $this->redirectToPaymentStep();
        }

        if (!$this->module->checkCurrency($cart)) {
            PrestaShopLogger::addLog('Could not handle payment form, invalid currency', 3, 0, 'Cart', $cart->id);
            $this->redirectToPaymentStep();
        }

        if (null === Tools::getValue('option', null)) {
            PrestaShopLogger::addLog('No payment option selected', 3, 0, 'Cart', $cart->id);
            $this->redirectToPaymentStep();
        }

        try {
            $options = $this->module->hookPaymentOptions(['cart' => $cart]);
            /** @var LegacyPaymentOption $selectedOption */
            $selectedOption = null;

            foreach ($options as $option) {
                if (Tools::getValue('option', null) === base64_encode($option->getModuleName())) {
                    $selectedOption = $option;
                    break;
                }
            }

            if (null === $selectedOption) {
                PrestaShopLogger::addLog('Invalid payment option selected', 3, 0, 'Cart', $cart->id);
                $this->redirectToPaymentStep();
            }

            $this->context->smarty->assign(
                [
                    'empty_cart' => 0 === ($cart->nbProducts() ?? 0),
                    'title' => $selectedOption->getCallToActionText(),
                    'form' => $selectedOption->getForm(),
                    'option_name' => $selectedOption->getModuleName(),
                    'back_link' => $this->context->link->getPageLink('order', true, null, 'step=3'),
                    'this_path' => $this->module->getPathUri(),
                    'this_path_check' => $this->module->getPathUri(),
                    'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/'
                        . $this->module->name . '/',
                ]
            );

            $this->setTemplate('payment.tpl');
        } catch (Exception $e) {
            PrestaShopLogger::addLog($e->getMessage(), 3, $e->getCode(), 'Cart', $cart->id);
            Tools::redirect('index.php?controller=order');
        }
    }

    /**
     * Redirects user back to payment method selection step.
     */
    private function redirectToPaymentStep(): void
    {
        Tools::redirect($this->context->link->getPageLink('order', true, null, 'step=3'));
    }
}
