<?php
/**
 * BookiFlex Offline Payment Extension
 *
 * @package    BookiFlex
 * @subpackage OfflinePayment
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Extensions\OfflinePayment;

use BookiFlex\Core\Container\ServiceContainer;
use BookiFlex\Core\Contract\ExtensionInterface;
use BookiFlex\Core\Contract\Payment\PaymentGatewayManagerInterface;
use BookiFlex\Core\Contract\PluginInterface;
use BookiFlex\Extensions\OfflinePayment\Action\CancelAction;
use Payum\Core\GatewayFactoryInterface;
use Payum\Core\Payum;
use Payum\Core\Security\GenericTokenFactory;
use Payum\Offline\OfflineGatewayFactory;

defined( 'ABSPATH' ) || exit;

/**
 * Offline payment gateway.
 */
class OfflinePayment implements ExtensionInterface
{
    protected PluginInterface $plugin;

    public function init(PluginInterface $plugin): void
    {
        $this->plugin = $plugin;
        if (!self::isPaymentExtensionSupported()) {
            return;
        }

        /** @var PaymentGatewayManagerInterface $paymentGatewayManager */
        $paymentGatewayManager = $plugin->getContainer()->get(PaymentGatewayManagerInterface::class);

        $paymentGatewayManager->registerPaymentGateway(
            id: 'offline',
            name: 'Offline payment',
            supportAuthorize: false,
            gatewayFactory: fn (array $config, GatewayFactoryInterface $coreGatewayFactory) => new OfflineGatewayFactory($config, $coreGatewayFactory),
            gatewaySettingsFactory: fn () => [
                'factory'             => 'offline',
                'payum.action.cancel' => new CancelAction(),
//                'token_factory' => $this->getTokenFactory($plugin->getContainer()),
            ],
        );
    }

    private function getTokenFactory(ServiceContainer $container): GenericTokenFactory
    {
        /** @var Payum $payum */
        $payum = $container->get(Payum::class);
        return new GenericTokenFactory(
            $payum->getTokenFactory(),
            [
                'capture' => rest_url('bflex/v1/payment/offline/capture'),
                'done'    => rest_url('bflex/v1/payment/offline/done'),
            ]
        );
    }

    private static function isPaymentExtensionSupported(): bool
    {
        return class_exists('BookiFlex\Extensions\Payment\Payment');
    }

    public function getName(): string
    {
        return 'OfflinePaymentGateway';
    }

    public function getVersion(): string
    {
        return '1.0.0';
    }

    public function isCompatible(string $pluginVersion): bool
    {
        return version_compare($pluginVersion, '1.0.0', '>=');
    }
}
