<?php

use Illuminate\Support\Facades\Event;
use Mtc\Plugins\Judopay\Classes\Judopay;
use Twig\TwigFunction;

function judopayConfig($key = null)
{
    $configKey = 'judopay.s'.SITE_ID;

    if (! empty($key)) {
        $configKey .= ".{$key}";
    }

    return config($configKey);
}

$twig->addFunction(new TwigFunction('judopay_assets', function () use ($twig): void {
    if (! config('judopay.enabled') || ! empty($GLOBALS['judopay_assets']))
        return;

    $GLOBALS['judopay_assets'] = true;

    echo
        $twig->render('Judopay/assets.twig', [
            'config' => [
                'merchantID' => judopayConfig('merchant_id'),
                'token' => judopayConfig('api_token'),
                'testmode' => config('judopay.testmode'),
                'urls' => [
                    'init' => '/shop/checkout/judopay/init/',
                    'payment' => '/shop/checkout/judopay/payment/',
                ],
            ],
        ])
    ;
}));

$twig->addFunction(new TwigFunction('judopay_apay_btn', function () use ($twig): void {
    if (! config('judopay.enabled'))
        return;

    echo
        $twig->render('Judopay/apay-btn.twig', [
            'merchant_id' => judopayConfig('apay.merchant_id'),
        ])
    ;
}));

$twig->addFunction(new TwigFunction('judopay_gpay_btn', function () use ($twig): void {
    if (! config('judopay.enabled'))
        return;

    echo $twig->render('Judopay/gpay-btn.twig', []);
}));

if (config('judopay.enabled')) {
    Event::listen('Order/initializePayment', '\\'.Judopay::class.'@initializePayment');

    Event::listen('refunds.get_refund_methods', function () {
        return [
            'id' => 'judopay',
            'name' => 'Judopay Refund',
            'callback' => '\\'.Judopay::class.'::handleRefund',
        ];
    });
}
