<?php

/**
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

require_once dirname(__FILE__) . '/../../models/SimplyInPoint.php';

use SimplyIn\Payment\RetryOrderResolver;
use SimplyIn\Session\PrestashopSessionAdapter;
use SimplyIn\Session\SimplyInSessionInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

class SimplyinPaymentAjaxModuleFrontController extends ModuleFrontController
{
    public ?SimplyInSessionInterface $simplyin_session = null;

    public function __construct()
    {
        parent::__construct();
        $this->module = Module::getInstanceByName('simplyin');
        $this->simplyin_session = new PrestashopSessionAdapter($this->context->cookie, $this->context->cart);
        if (!Tools::isSubmit('ajax')) {
            exit;
        }
    }

    public function initContent()
    {
        parent::initContent();
    }

    public function displayAjax()
    {

        $this->checkAjaxToken();
        if (Tools::isSubmit('action')) {
            $actions = [
                'selectPaymentMethod' => 'selectPaymentMethodPaymentAjaxAction',
                'enterBlikCode' => 'enterBlikCodePaymentAjaxAction',
                'checkOrderStatus' => 'checkOrderStatusPaymentAjaxAction',
                'checkRetryDecision' => 'checkRetryDecisionPaymentAjaxAction',
            ];
            $action = (string) Tools::getValue('action');
            if (isset($actions[$action])) {
                $result = json_encode($this->{$actions[$action]}());
                session_write_close();
                exit($result);
            }
            session_write_close();
            exit(json_encode(['error' => 'Invalid action']));

        }
        session_write_close();
        exit(json_encode(['error' => 'No action specified']));

    }

    public function checkAjaxToken()
    {
        $token = Tools::getValue('ajax_token');
        if (!hash_equals((string) $this->module->getAjaxToken(), (string) $token)) {
            exit(json_encode(['error' => 'Invalid token']));
        }
        $cart_token = Tools::getValue('cart_token');
        $id_cart = Tools::getValue('id_cart');
        $id_cart = $id_cart ? (int) $id_cart : false;
        if (!hash_equals((string) $this->module->getCartToken($id_cart), (string) $cart_token)) {
            exit(json_encode(['error' => 'Invalid cart token']));
        }
    }

    public function selectPaymentMethodPaymentAjaxAction()
    {
        $store = new \SimplyIn\Checkout\PaymentSelectionStore($this->simplyin_session);
        $store->storeSelection(
            (string) Tools::getValue('payment_type'),
            (string) Tools::getValue('payment_id'),
            (string) Tools::getValue('payment_provider'),
            (string) Tools::getValue('provider_image'),
            (string) Tools::getValue('logo'),
            (string) Tools::getValue('card_name'),
            (string) Tools::getValue('last_digits'),
            (string) Tools::getValue('card_provider'),
            (string) Tools::getValue('ott'),
            (bool) Tools::getValue('card_save'),
        );

        return ['success' => true];
    }

    public function enterBlikCodePaymentAjaxAction()
    {
        $store = new \SimplyIn\Checkout\PaymentSelectionStore($this->simplyin_session);
        if ($this->simplyin_session->get('simplyin_payment_type') !== 'blik') {
            $store->clearBlikCode();

            return;
        }
        $store->storeBlikCode((string) Tools::getValue('blik_code'));

        return ['success' => true];
    }

    public function checkOrderStatusPaymentAjaxAction()
    {
        exit(json_encode($this->module->checkPaymentAjax()));
    }

    /**
     * Re-answers the same pay-again decision {@see \SimplyIn\Payment\OrderRetryRenderer} renders
     * elsewhere, for the live payment-status poll to catch up on a definitive failure without a page
     * reload. Authorized the same way `paymentretry` authorizes resubmitting a payment for this order,
     * in addition to the cart-agnostic pair `checkAjaxToken()` above already required.
     */
    public function checkRetryDecisionPaymentAjaxAction()
    {
        $order = RetryOrderResolver::resolve(
            $this->module,
            (int) Tools::getValue('id_order'),
            (string) Tools::getValue('retry_token'),
        );
        if ($order === null) {
            return ['html' => null];
        }

        return ['html' => $this->module->orderRetryRenderer->render($this->module, $order)];
    }
}
