<?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\MerchantApi\Exception\FakeContainerException;
use Resursbank\MerchantApi\Service\FakeContainer;
use Resursbank\MerchantApi\Service\PartPayment;
use Resursbank\MerchantApi\Util\Log;
use Throwable;
use Tools;
use Validate;

/**
 * Initializes part payment widget on all pages for usage in quick view.
 */
class DisplayFooter
{
    /**
     * @param Context $context
     * @return string
     * @throws FakeContainerException
     */
    public static function exec(Context $context): string
    {
        $config = FakeContainer::getConfig();

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

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

            if ($productId > 0) {
                // We are on a product page, get product price
                $product = new Product($productId);
                if (Validate::isLoadedObject($product)) {
                    $price = (float) $product->getPrice(true, null, 2);
                }
            } elseif (isset($context->cart) && $context->cart->id) {
                // Fallback to cart total (used on checkout/cart pages)
                $price = (float) $context->cart->getOrderTotal(true, Cart::BOTH);
            }

            // If no valid price, do not render widget
            if ($price === null || $price <= 0) {
                return '';
            }

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

            return '<style>' . $widget->css . $widget->readMore->css . '</style>' .
                '<div id="rb-pp-flexible-widget-container" style="display:none;">' . $widget->content .
                '</div>';
        } catch (Throwable $error) {
            Log::error(message: $error);
        }

        return '';
    }
}
