<?php

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

namespace Resursbank\MerchantApi\Hook;

use Context;
use Resursbank\MerchantApi\Exception\FakeContainerException;
use Resursbank\MerchantApi\Service\FakeContainer;
use Resursbank\MerchantApi\Service\PartPayment;
use Resursbank\MerchantApi\Util\Log;
use Throwable;

/**
 * Displays part payment widget.
 */
class DisplayPartPayment
{
    /**
     * Initializes part payment widget on product pages.
     *
     * @param Context $context
     * @param mixed $product
     * @param string $path
     * @return string
     * @throws FakeContainerException
     */
    public static function exec(Context $context, mixed $product, string $path): string
    {
        $config = FakeContainer::getConfig();

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

        if ($context->controller->php_self === 'product') {
            try {
                $amount = $product['price_amount'];
                $widget = PartPayment::getWidget(
                    context: $context,
                    amount: $amount
                );

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

        return '';
    }
}
