<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

use Paysera\PrestashopPayments\Controller\AbstractPayseraFrontController;
use Paysera\PrestashopPayments\Provider\PaymentMethodProviderInterface;
use Paysera\PrestashopPayments\Service\BillingCountryResolver;
use Paysera\PrestashopPayments\Service\CmsToolsFacade;
use Paysera\PrestashopPayments\Service\MoneyConverter;

if (!defined('_PS_VERSION_')) {
    exit;
}

class PayserapaymentsPaymentmethodsModuleFrontController extends AbstractPayseraFrontController
{
    public function init()
    {
        parent::init();
        $this->ajax = true;
    }

    public function displayAjax(): void
    {
        $requestedCountryCode = $this->get(CmsToolsFacade::class)->getValue('country_code');
        $countryCode = is_string($requestedCountryCode) && $requestedCountryCode !== ''
            ? $requestedCountryCode
            : $this->get(BillingCountryResolver::class)->resolve($this->context)
        ;

        try {
            $cart = $this->context->cart;
            $amount = null;

            if ($cart && $cart->id) {
                $moneyConverter = $this->get(MoneyConverter::class);
                $amount = $moneyConverter->createMoneyFromCart($cart);
            }

            $paymentMethodProvider = $this->get(PaymentMethodProviderInterface::class);
            $methods = $paymentMethodProvider->getPaymentMethodsForCountry($countryCode, $amount);

            $this->ajaxRender(json_encode([
                'success' => true,
                'methods' => $methods,
            ]));
        } catch (Exception $exception) {
            $this->logger()->error('Failed to fetch payment methods', [
                'error' => $exception->getMessage(),
                'code' => $exception->getCode(),
                'country_code' => $countryCode,
            ]);

            $this->ajaxRender(json_encode([
                'success' => false,
                'error' => 'Failed to fetch payment methods',
            ]));
        }
    }
}
