<?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
 */

use SimplyIn\Session\PrestashopSessionAdapter;
use SimplyIn\Session\SimplyInSessionInterface;

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

class SimplyInValidationModuleFrontController extends ModuleFrontController
{
    public bool $account_created = false;

    public ?SimplyInSessionInterface $simplyin_session = null;

    public function postProcess()
    {
        $this->simplyin_session = new PrestashopSessionAdapter($this->context->cookie, $this->context->cart);
        $cart = $this->context->cart;

        if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
            Tools::redirect('index.php?controller=order&step=1');
        }

        if (!$cart->id) {
            Tools::redirect('index.php?controller=order&step=1');
        }

        $authorized = false;
        foreach (Module::getPaymentModules() as $module) {
            if ($module['name'] == 'simplyin') {
                $authorized = true;

                break;
            }
        }

        if (!Configuration::get('SIMPLYIN_PAYMENTS')) {
            $authorized = false;
        }

        if (!$authorized) {
            exit($this->module->getTranslator()->trans('This payment method is not available.', [], 'Modules.Simplyin.Shop'));
        }

        $customer = new Customer($cart->id_customer);
        if (!Validate::isLoadedObject($customer)) {
            Tools::redirect('index.php?controller=order&step=1');
        }

        $currency = $this->context->currency;

        $this->module->validateOrder(
            $cart->id,
            (int) Configuration::get('SIMPLYIN_PAYMENT_STATUS_PENDING'),
            0,
            $this->module->displayName,
            null,
            [],
            (int) $currency->id,
            false,
            $customer->secure_key,
        );

        $order = Order::getByCartId($cart->id);

        $placementResult = $this->placeOrderSimplyIn($order);
        $this->account_created = $placementResult->accountCreated;
        $this->module->updateOrderState($order, (int) Configuration::get('SIMPLYIN_PAYMENT_STATUS_PENDING'), 'markAsPending');

        $redirect_url = $this->context->link->getPageLink(
            'order-confirmation',
            true,
            null,
            [
                'id_cart' => $cart->id,
                'id_module' => $this->module->id,
                'id_order' => $this->module->currentOrder,
                'key' => $customer->secure_key,
            ],
        );

        $this->createPaymentSimplyIn($cart, $redirect_url);
        Tools::redirect($redirect_url);
    }

    public function placeOrderSimplyIn($order): \SimplyIn\Checkout\OrderPlacementResult
    {
        $service = new \SimplyIn\Checkout\OrderPlacementService(
            $this->simplyin_session,
            new \SimplyIn\Checkout\LegacyCheckoutApi($this->module->apiClient),
            new \SimplyIn\Checkout\LegacyOrderDataFetcher(),
            new \SimplyIn\Checkout\PrestaShopCustomerEmailProvider(),
            new \SimplyIn\Checkout\LegacyEmailCache(),
        );

        return $service->placeOrder($order);
    }

    public function getAuthToken()
    {
        return $this->simplyin_session->get('simplyin_auth_token', false);
    }

    public function createPaymentSimplyIn($cart, $redirect_url)
    {
        $order = Order::getByCartId($cart->id);
        $sessionAdapter = $this->simplyin_session;

        $service = new \SimplyIn\Payment\PaymentCreationService(
            $sessionAdapter,
            new \SimplyIn\Payment\LegacyPaymentApi($this->module->apiClient),
            new \SimplyIn\Payment\LegacyPaymentRecorder(),
            new \SimplyIn\Payment\OrderStateUpdater(),
            new \SimplyIn\Checkout\PaymentMethodDataBuilder($sessionAdapter),
        );

        $result = $service->createPayment(
            $cart,
            $order,
            (string) $this->context->customer->firstname,
            (string) $this->context->customer->lastname,
            (string) $this->context->customer->email,
            (string) $this->module->getCustomerEmail(),
            (bool) $this->context->customer->is_guest,
            (bool) $this->account_created,
            $redirect_url,
            $this->context->link->getModuleLink($this->module->name, 'webhook', [], true),
        );

        if ($result->externalRedirectUrl !== null) {
            header('Location: ' . $result->externalRedirectUrl);
            session_write_close();
            exit;
        }
    }
}
