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

declare(strict_types=1);

namespace SimplyIn\Payment;

use Configuration;
use Context;
use Customer;
use Module;
use Order;
use SimplyIn\Session\SimplyInSessionInterface;
use SimplyInPayments;
use Tools;

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

final class OrderConfirmationRenderer
{
    private SimplyInSessionInterface $session;

    public function __construct(SimplyInSessionInterface $session)
    {
        $this->session = $session;
    }

    public function render(Module $module, Order $order): ?string
    {
        if (!$module->active || !Configuration::get('SIMPLYIN_PAYMENTS')) {
            return null;
        }

        $idCart = (int) $order->id_cart;
        $paymentInfo = SimplyInPayments::getPaymentInfo($idCart);
        $customer = new Customer((int) $order->id_customer);

        if ($customer->is_guest && $paymentInfo === false) {
            $this->session->clear();
        }

        if ($paymentInfo === false) {
            return null;
        }

        Context::getContext()->smarty->assign([
            'payment_info' => $paymentInfo,
            'current_url' => $this->currentUrl(),
            'module_path' => _MODULE_DIR_ . $module->name . '/',
            'payment_status' => $paymentInfo->status,
            'accent_color' => Configuration::get('SIMPLYIN_ACCENT_COLOR') ?: '#2d40f6',
        ]);

        return $module->fetch('module:simplyin/views/templates/hook/payment_return.tpl');
    }

    private function currentUrl(): string
    {
        $host = isset($_SERVER['HTTP_HOST']) ? (string) $_SERVER['HTTP_HOST'] : '';
        $uri = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '';

        return Tools::getCurrentUrlProtocolPrefix() . $host . $uri;
    }
}
