<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Model;

use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Framework\View\Asset\Repository as AssetRepository;

/**
 * Config provider for SimplyIN payment method
 *
 * Provides configuration data to checkout
 */
class ConfigProvider implements ConfigProviderInterface
{
    public const XML_PATH_ACTIVE = 'payment/simplyin_payment/active';
    public const XML_PATH_DEFAULT_CREATE_ACCOUNT_CHECKED = 'payment/simplyin_payment/default_create_account_checked';
    public const XML_PATH_SHIPPING_METHODS = 'payment/shipping_methods/';
    public const XML_PATH_GDPR_URL_EN = 'payment/simplyin_payment/gdpr_url_en';
    public const XML_PATH_GDPR_URL_PL = 'payment/simplyin_payment/gdpr_url_pl';
    public const XML_PATH_TERMS_B2C_URL_EN = 'payment/simplyin_payment/terms_b2c_url_en';
    public const XML_PATH_TERMS_B2C_URL_PL = 'payment/simplyin_payment/terms_b2c_url_pl';
    public const XML_PATH_TERMS_B2B_URL_EN = 'payment/simplyin_payment/terms_b2b_url_en';
    public const XML_PATH_TERMS_B2B_URL_PL = 'payment/simplyin_payment/terms_b2b_url_pl';

    /**
     * @var ScopeConfigInterface
     */
    protected ScopeConfigInterface $scopeConfig;

    /**
     * @var CheckoutSession
     */
    protected CheckoutSession $checkoutSession;

    /**
     * @var PriceCurrencyInterface
     */
    protected PriceCurrencyInterface $priceCurrency;

    /**
     * @var ResolverInterface
     */
    protected ResolverInterface $localeResolver;

    /**
     * @var AssetRepository
     */
    protected AssetRepository $assetRepository;

    /**
     * Constructor
     *
     * @param ScopeConfigInterface $scopeConfig
     * @param CheckoutSession $checkoutSession
     * @param PriceCurrencyInterface $priceCurrency
     * @param ResolverInterface $localeResolver
     * @param AssetRepository $assetRepository
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        CheckoutSession $checkoutSession,
        PriceCurrencyInterface $priceCurrency,
        ResolverInterface $localeResolver,
        AssetRepository $assetRepository
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->checkoutSession = $checkoutSession;
        $this->priceCurrency = $priceCurrency;
        $this->localeResolver = $localeResolver;
        $this->assetRepository = $assetRepository;
    }

    /**
     * Retrieve assoc array of checkout configuration
     *
     * @return array
     */
    public function getConfig(): array
    {
        $quote = $this->checkoutSession->getQuote();
        $currencyCode = $quote ? $quote->getQuoteCurrencyCode() : 'PLN';

        $locale = $this->localeResolver->getLocale();
        $isPolish = str_starts_with($locale, 'pl_') || $locale === 'pl';

        return [
            'payment' => [
                'simplyin_payment' => [
                    'isActive' => $this->isActive(),
                    'shippingMethodMapping' => $this->getShippingMethodMapping(),
                    'providerSortOrder' => $this->getProviderSortOrder(),
                    'currencySymbol' => $this->priceCurrency->getCurrencySymbol(),
                    'currencyCode' => $currencyCode,
                    'isBlikAvailable' => strtoupper((string)$currencyCode) === 'PLN',
                    'logoUrl' => $this->getSimplyinLogoUrl(),
                    'p24LogoUrl' => $this->getP24LogoUrl(),
                    'defaultCreateAccountChecked' => $this->isDefaultCreateAccountChecked(),
                    'storeLocale' => $locale,
                    'isPolishLocale' => $isPolish,
                    'gdprUrl' => $this->getGdprUrl(),
                    'termsB2cUrl' => $this->getTermsB2cUrl(),
                    'termsB2bUrl' => $this->getTermsB2bUrl($isPolish)
                ]
            ]
        ];
    }

    /**
     * Get SimplyIN logo URL from local assets
     *
     * @return string
     */
    protected function getSimplyinLogoUrl(): string
    {
        return $this->assetRepository->getUrl('Simplyin_Payment::images/simplyin-logo.svg');
    }

    /**
     * Get P24 logo URL from local assets
     *
     * @return string
     */
    protected function getP24LogoUrl(): string
    {
        return '';
    }

    /**
     * Check if SimplyIN payment is active
     *
     * @return bool
     */
    protected function isActive(): bool
    {
        return (bool) $this->scopeConfig->getValue(
            self::XML_PATH_ACTIVE,
            ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * Check if create account checkbox should be checked by default
     *
     * @return bool
     */
    protected function isDefaultCreateAccountChecked(): bool
    {
        // Config value 1 = "checkbox is NOT selected by default" → return false
        // Config value 0 = checkbox IS selected by default → return true
        $configValue = (bool) $this->scopeConfig->getValue(
            self::XML_PATH_DEFAULT_CREATE_ACCOUNT_CHECKED,
            ScopeInterface::SCOPE_STORE
        );
        return !$configValue;
    }

    /**
     * Get GDPR/Privacy Policy URL (locale-agnostic)
     *
     * @return string
     */
    protected function getGdprUrl(): string
    {
        $url = (string)$this->scopeConfig->getValue(self::XML_PATH_GDPR_URL_PL, ScopeInterface::SCOPE_STORE);
        if (empty($url)) {
            $url = (string)$this->scopeConfig->getValue(self::XML_PATH_GDPR_URL_EN, ScopeInterface::SCOPE_STORE);
        }

        if (empty($url)) {
            return 'https://simply.in/privacy-policy/';
        }

        return $url;
    }

    /**
     * Get Terms B2C URL (locale-agnostic)
     *
     * @return string
     */
    protected function getTermsB2cUrl(): string
    {
        $url = (string)$this->scopeConfig->getValue(self::XML_PATH_TERMS_B2C_URL_PL, ScopeInterface::SCOPE_STORE);
        if (empty($url)) {
            $url = (string)$this->scopeConfig->getValue(self::XML_PATH_TERMS_B2C_URL_EN, ScopeInterface::SCOPE_STORE);
        }

        if (empty($url)) {
            return 'https://simply.in/terms-b2c/';
        }

        return $url;
    }

    /**
     * Get Terms B2B URL based on locale
     *
     * @param bool $isPolish
     * @return string
     */
    protected function getTermsB2bUrl(bool $isPolish): string
    {
        $configPath = $isPolish ? self::XML_PATH_TERMS_B2B_URL_PL : self::XML_PATH_TERMS_B2B_URL_EN;
        $url = (string)$this->scopeConfig->getValue($configPath, ScopeInterface::SCOPE_STORE);

        if (empty($url)) {
            return $isPolish
                ? 'https://www.simply.in/terms-b2b'
                : 'https://www.simply.in/en/terms-b2b';
        }

        return $url;
    }

    /**
     * Get shipping method mapping configuration
     *
     * @return array
     */
    protected function getShippingMethodMapping(): array
    {
        $mapping = [];

        $providerConfigMapping = [
            'inpost' => 'inpost_paczkomat',
            'dpd' => 'dpd_pickup',
            'dhl' => 'dhl_box_pop',
            'orlen' => 'orlen_punkty',
            'ups' => 'ups_pickup',
            'default_courier' => 'default_courier'
        ];

        foreach ($providerConfigMapping as $providerKey => $configKey) {
            $value = $this->scopeConfig->getValue(
                self::XML_PATH_SHIPPING_METHODS . $configKey,
                ScopeInterface::SCOPE_STORE
            );

            if (!empty($value) && $value !== 'none') {
                $mapping[$providerKey] = $value;
            }
        }

        return $mapping;
    }

    /**
     * Get provider sort order configuration
     *
     * @return array
     */
    protected function getProviderSortOrder(): array
    {
        $sortOrder = [];

        $providerSortOrderMapping = [
            'inpost' => 'inpost_paczkomat_sort_order',
            'dpd' => 'dpd_pickup_sort_order',
            'dhl' => 'dhl_box_pop_sort_order',
            'orlen' => 'orlen_punkty_sort_order',
            'ups' => 'ups_pickup_sort_order'
        ];

        foreach ($providerSortOrderMapping as $providerKey => $configKey) {
            $value = $this->scopeConfig->getValue(
                self::XML_PATH_SHIPPING_METHODS . $configKey,
                ScopeInterface::SCOPE_STORE
            );

            $sortOrder[$providerKey] = !empty($value) ? (int)$value : 999;
        }

        return $sortOrder;
    }
}
