<?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);

namespace Paysera\PrestashopPayments\Provider;

use Paysera\PrestashopPayments\Checker\ModuleStatusChecker;
use Paysera\PrestashopPayments\Enum\ConfigurationKey;
use Paysera\PrestashopPayments\Form\PaymentSettingsDataConfiguration;
use Paysera\PrestashopPayments\Service\AuthorizationService;
use Symfony\Component\Translation\TranslatorBagInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

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

class ReactDataProvider
{
    public function __construct(
        private AuthorizationService $authorizationService,
        private ModuleStatusChecker $moduleStatusChecker,
        private SettingsProvider $settingsProvider,
        private PaymentSettingsDataConfiguration $paymentSettingsConfig,
        private TranslatorInterface $translator,
        private UrlProvider $urlProvider
    ) {
    }

    /**
     * @return array<string, mixed>
     */
    public function getPayseraData(\PayseraPayments $module, \Context $context, string $currentPage): array
    {
        $isAuthorized = $this->authorizationService->isAuthorized();
        $connectionStatus = $this->moduleStatusChecker->getConnectionStatus($module);
        $sandboxMode = $this->settingsProvider->getSandboxMode();

        return [
            'user' => [
                'authorized' => $isAuthorized,
                'checkoutSandboxMode' => $sandboxMode,
                'connectionStatus' => $connectionStatus,
                'paymentSettings' => $this->getPaymentSettings(),
            ],
            'ajaxUrl' => $context->link->getAdminLink('AdminPayseraPaymentsAjax'),
            'currentPage' => $currentPage,
            'pluginUrl' => $module->getPathUri(),
            'i18nDomain' => \PayseraPayments::TRANSLATION_DOMAIN,
            'extra' => [
                'links' => $this->getExtraLinks(),
            ],
            'orderStatuses' => $this->getOrderStatuses($context),
            'pluginVersion' => $module->version,
            'pluginUpdateDate' => $this->getPluginUpdateDate($module, $context->language->locale ?? 'en-US'),
            'localeCode' => $context->language->locale ?? 'en-US',
            'translations' => $this->getTranslations(),
            'adminLogsUrl' => $this->urlProvider->getAdminLogsUrl(),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private function getPaymentSettings(): array
    {
        return $this->paymentSettingsConfig->getConfiguration();
    }

    /**
     * @return array<string, string>
     */
    private function getOrderStatuses(\Context $context): array
    {
        $languageId = isset($context->language) ? (int) $context->language->id : 1;
        $orderStates = \OrderState::getOrderStates($languageId);
        $statuses = [];

        foreach ($orderStates as $state) {
            $statuses[(string) $state['id_order_state']] = $state['name'];
        }

        return $statuses;
    }

    /**
     * @return array<string, string>
     */
    private function getExtraLinks(): array
    {
        return [
            'payseraWebsite' => 'https://www.paysera.com',
            'payseraSupport' => 'https://www.paysera.com/v2/en/contacts',
            'payseraDevelopers' => 'https://developers.paysera.com',
            'payseraRegistration' => 'https://www.paysera.com/v2/en/sign-up',
            'paymentSolutions' => 'https://www.paysera.com/v2/en/payment-gateway-checkout',
            'allServices' => 'https://www.paysera.com/v2/en/index',
            'faq' => 'https://www.paysera.com/v2/en/faq',
        ];
    }

    private function getPluginUpdateDate(\PayseraPayments $module, string $locale): string
    {
        $timestamp = $this->resolveLastUpdatedTimestamp($module);

        if ($timestamp === null) {
            return '';
        }

        if (class_exists(\IntlDateFormatter::class)) {
            $formatter = new \IntlDateFormatter(
                $locale,
                \IntlDateFormatter::LONG,
                \IntlDateFormatter::NONE
            );
            $formatted = $formatter->format($timestamp);

            if (is_string($formatted)) {
                return $formatted;
            }
        }

        return date('F j, Y', $timestamp);
    }

    private function resolveLastUpdatedTimestamp(\PayseraPayments $module): ?int
    {
        $storedDate = \Configuration::get(ConfigurationKey::LAST_UPDATED);

        if (is_string($storedDate) && $storedDate !== '') {
            $timestamp = strtotime($storedDate);

            if ($timestamp !== false) {
                return $timestamp;
            }
        }

        $timestamp = @filemtime($module->getLocalPath() . 'payserapayments.php');

        return $timestamp === false ? null : $timestamp;
    }

    /**
     * @return array<string, array<string, string>>
     */
    private function getPlaceholderParams(): array
    {
        return [
            'Since 2004, Paysera has been a trusted global fintech company providing comprehensive financial and payment services to clients worldwide. Our %cms_name% plugin brings enterprise-level payment processing directly to your online store.' => ['%cms_name%' => 'PrestaShop'],
            'Connect your %cms_name% store to your Paysera account' => ['%cms_name%' => 'PrestaShop'],
            'Plugin version: %pluginVersion%' => ['%pluginVersion%' => \PayseraPayments::VERSION],
            'Welcome to Paysera for %cms_name%' => ['%cms_name%' => 'PrestaShop'],
        ];
    }

    /**
     * @return array<string, string>
     */
    private function getTranslations(): array
    {
        $domain = \PayseraPayments::TRANSLATION_DOMAIN;
        $placeholders = $this->getPlaceholderParams();
        $translations = [];

        if ($this->translator instanceof TranslatorBagInterface) {
            $catalogue = $this->translator->getCatalogue();
            $domainKey = str_replace('.', '', $domain);

            foreach (array_keys($catalogue->all($domainKey)) as $key) {
                $params = $placeholders[$key] ?? [];
                $translations[$key] = $this->translator->trans($key, $params, $domain);
            }
        }

        return $translations;
    }
}
