<?php

/**
 * Copyright © Resurs Bank AB. All rights reserved.
 * See LICENSE for license details.
 */

namespace Resursbank\MerchantApi\Hook;

use Cart;
use Context;
use Product;
use Resursbank\Ecom\Module\PriceSignage\Widget\CostList;
use Resursbank\Ecom\Module\PriceSignage\Widget\CostListJs;
use Resursbank\MerchantApi\Exception\FakeContainerException;
use Resursbank\MerchantApi\Service\FakeContainer;
use Resursbank\MerchantApi\Service\PartPayment;
use Resursbank\MerchantApi\Util\Log;
use Throwable;
use Tools;
use Validate;

/**
 * Add stylesheet to header.
 */
class DisplayHeader
{
    private static $context;
    private static string $path;

    /**
     * @param Context $context
     * @param string $path
     * @return void
     * @throws FakeContainerException
     */
    public static function exec(Context $context, string $path)
    {
        self::$path = $path;
        self::$context = $context;

        self::renderCheckoutAssets();
        self::renderPartPaymentAssets();
    }

    /**
     * @return void
     */
    private static function renderCheckoutAssets(): void
    {
        if (self::$context->controller->php_self === 'order') {
            // Add checkout CSS.
            self::$context->controller->registerStylesheet(
                id: 'rb-checkout',
                relativePath: self::$path . 'views/css/front/checkout.css',
                params: [
                    // @todo version should be resolved as md5 of file content.
                    'version' => '1.0.0',
                ]
            );

            // Add checkout JS.
            self::$context->controller->registerJavascript(
                id: 'rb-checkout',
                relativePath: self::$path . 'views/js/front/checkout.js',
                params: [
                    // @todo version should be resolved as md5 of file content.
                    'version' => '1.0.0',
                ]
            );

            $dynamicCostListCss = CostList::getCss();
            self::$context->controller->registerStylesheet(
                'dynamic-cost-list-css',
                'data:text/css;base64,' . base64_encode(string: $dynamicCostListCss),
                ['media' => 'all', 'priority' => 150, 'server' => 'remote']
            );

            $costListJs = (new CostListJs(containerElDomPath: 'body'))->content;
            self::$context->controller->registerJavascript(
                'dynamic-cost-list-js',
                'data:text/javascript;base64,' . base64_encode(string: $costListJs),
                ['position' => 'head', 'priority' => 151, 'server' => 'remote']
            );

            $readMoreJsLink = self::$context->link->getModuleLink(
                module: 'resursbank',
                controller: 'readmore',
                params: ['container' => '#checkout-payment-step']
            );
            self::$context->controller->registerJavascript(
                id: 'resursbank-readmore',
                relativePath: $readMoreJsLink,
                params: ['media' => 'all', 'priority' => 152, 'server' => 'remote']
            );
        }
    }

    /**
     * @return void
     * @throws FakeContainerException
     */
    private static function renderPartPaymentAssets(): void
    {
        try {
            $config = FakeContainer::getConfig();

            if (!$config->getPartPaymentEnabled()) {
                return;
            }

            $price = null;
            $productId = (int)Tools::getValue(key: 'id_product');

            if ($productId > 0) {
                // We are on a product page, try to fetch the product price
                $product = new Product(id_product: $productId);
                if (Validate::isLoadedObject(object: $product)) {
                    // Get product price including tax (set to false if you need excl. tax)
                    $price = (float)$product->getPrice(tax: true, id_product_attribute: null, decimals: 2);
                }
            } elseif (isset(self::$context->cart) && self::$context->cart->id) {
                // We are not on a product page, fallback to cart total (checkout/cart page)
                $price = (float)self::$context->cart->getOrderTotal(true, Cart::BOTH);
            }

            // If no valid price was found, we won't be able to render the widget.
            if ($price === null || $price <= 0) {
                return;
            }

            $widget = PartPayment::getWidget(
                context: self::$context,
                amount: $price
            );

            self::$context->controller->registerJavascript(
                'rb-pp-widget',
                'data:text/javascript;base64,' . base64_encode(string: $widget->js),
                ['position' => 'head', 'priority' => 150, 'server' => 'remote']
            );

            $readMoreJsLink = self::$context->link->getModuleLink(
                module: 'resursbank',
                controller: 'readmore',
                params: ['container' => '#rb-pp-widget-container']
            );

            self::$context->controller->registerJavascript(
                id: 'resursbank-partpayment-overrides',
                relativePath: self::$path . 'views/js/front/partpayment.js'
            );

            // Read more script only related to the product page.
            if ($productId > 0) {
                self::$context->controller->registerJavascript(
                    id: 'resursbank-readmore',
                    relativePath: $readMoreJsLink,
                    params: ['media' => 'all', 'priority' => 150, 'server' => 'remote']
                );
            }
        } catch (Throwable $error) {
            Log::error(message: $error);
        }
    }
}
