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

namespace Simplyin\HyvaPayment\ViewModel;

use Magento\Framework\View\Element\Block\ArgumentInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Framework\View\Asset\Repository as AssetRepository;
use Magento\Framework\UrlInterface;
use Simplyin\Payment\Model\Config\EnvironmentConfig;
use Simplyin\Payment\Service\PaymentMethodAvailability;

/**
 * CheckoutConfig ViewModel
 *
 * Provides checkout configuration data to Hyva templates including
 * API endpoints, default country code, module enabled status, logo URL,
 * and the default state for the new account checkbox.
 *
 * @see Requirements 13.4, 17.1
 */
class CheckoutConfig implements ArgumentInterface
{
    /**
     * Configuration paths from Simplyin_Payment module
     */
    private const XML_PATH_ACTIVE = 'payment/simplyin_payment/active';
    private const XML_PATH_DEFAULT_CREATE_ACCOUNT_CHECKED = 'payment/simplyin_payment/default_create_account_checked';

    /**
     * Default country code (Poland)
     */
    private const DEFAULT_COUNTRY_CODE = 'PL';

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

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

    /**
     * @var UrlInterface
     */
    private UrlInterface $urlBuilder;

    /**
     * @var EnvironmentConfig
     */
    private EnvironmentConfig $environmentConfig;

    /**
     * @var PaymentMethodAvailability
     */
    private PaymentMethodAvailability $paymentMethodAvailability;

    /**
     * Constructor
     *
     * @param ScopeConfigInterface $scopeConfig
     * @param AssetRepository $assetRepository
     * @param UrlInterface $urlBuilder
     * @param EnvironmentConfig $environmentConfig
     * @param PaymentMethodAvailability $paymentMethodAvailability
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        AssetRepository $assetRepository,
        UrlInterface $urlBuilder,
        EnvironmentConfig $environmentConfig,
        PaymentMethodAvailability $paymentMethodAvailability
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->assetRepository = $assetRepository;
        $this->urlBuilder = $urlBuilder;
        $this->environmentConfig = $environmentConfig;
        $this->paymentMethodAvailability = $paymentMethodAvailability;
    }

    /**
     * Get API endpoints for checkout operations
     *
     * Returns an array of API endpoint URLs used by the checkout process.
     * These endpoints are used by Magewire components for server-side interactions.
     *
     * @return array<string, string>
     */
    public function getApiEndpoints(): array
    {
        return [
            'checkEmail' => $this->urlBuilder->getUrl('simplyin/api/checkEmail'),
            'verifyOtp' => $this->urlBuilder->getUrl('simplyin/api/verifyOtp'),
            'submitOtp' => $this->urlBuilder->getUrl('simplyin/api/submitOtp'),
            'resendOtp' => $this->urlBuilder->getUrl('simplyin/api/resendOtp'),
            'checkPushStatus' => $this->urlBuilder->getUrl('simplyin/api/checkPushStatus'),
            'getUserData' => $this->urlBuilder->getUrl('simplyin/api/getUserData'),
            'updateUserData' => $this->urlBuilder->getUrl('simplyin/api/updateUserData'),
            'createOrder' => $this->urlBuilder->getUrl('simplyin/api/createOrder'),
            'getPaymentStatus' => $this->urlBuilder->getUrl('simplyin/api/getPaymentStatus'),
            'searchAddress' => $this->urlBuilder->getUrl('simplyin/api/searchAddress'),
            'getParcelLockers' => $this->urlBuilder->getUrl('simplyin/api/getParcelLockers'),
            'threeDSecureReturn' => $this->urlBuilder->getUrl('checkout/onepage/success'),
        ];
    }

    /**
     * Get default country code
     *
     * Returns the default country code for phone number input.
     * Defaults to Poland (PL) as per requirements.
     *
     * @return string ISO 3166-1 alpha-2 country code
     */
    public function getDefaultCountryCode(): string
    {
        return self::DEFAULT_COUNTRY_CODE;
    }

    /**
     * Check if Simplyin payment is enabled
     *
     * Reads the active configuration from the Simplyin_Payment module.
     *
     * @return bool True if Simplyin payment is enabled
     */
    public function isSimplyinEnabled(): bool
    {
        return (bool) $this->scopeConfig->getValue(
            self::XML_PATH_ACTIVE,
            ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * Check if the merchant has at least one SimplyIN payment method configured
     *
     * Backed by the shared availability service (fail-closed; returns false
     * on a successful empty result or on any error/exception/unauthenticated
     * response). Used by the checkout templates to suppress the SimplyIN branding
     * when no payment method is configured.
     *
     * @return bool True if at least one payment method is available
     */
    public function hasAvailablePaymentMethods(): bool
    {
        return $this->paymentMethodAvailability->hasAvailablePaymentMethods();
    }

    /**
     * Get Simplyin logo URL
     *
     * Returns the URL to the Simplyin logo SVG from the Simplyin_Payment module assets.
     * The logo is used in the checkout UI to indicate Simplyin integration.
     *
     * @return string URL to the Simplyin logo
     */
    public function getSimplyinLogoUrl(): string
    {
        return $this->assetRepository->getUrl('Simplyin_Payment::images/simplyin-logo.svg');
    }

    /**
     * Get default state for new account checkbox
     *
     * Returns whether the "Create Simplyin account" checkbox should be
     * checked by default during checkout. This is configurable in admin.
     *
     * @see Requirement 13.4
     * @return bool True if checkbox should be checked by default
     */
    public function isNewAccountCheckboxDefault(): 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 API base URL
     *
     * Returns the base URL for the Simplyin API.
     *
     * @return string API base URL
     */
    public function getApiBaseUrl(): string
    {
        return $this->environmentConfig->getApiBaseUrl();
    }

    /**
     * Get domain origin from web/secure/base_url or store manager
     *
     * Returns clean URL without trailing slash and without index.php
     *
     * @return string Domain origin URL
     */
    public function getDomainOrigin(): string
    {
        // First try web/secure/base_url from config
        $baseUrl = (string) $this->scopeConfig->getValue(
            'web/secure/base_url',
            ScopeInterface::SCOPE_STORE
        );
        
        // Fallback to store manager
        if (empty($baseUrl)) {
            try {
                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $storeManager = $objectManager->get(\Magento\Store\Model\StoreManagerInterface::class);
                $baseUrl = $storeManager->getStore()->getBaseUrl();
            } catch (\Exception $e) {
                return '';
            }
        }
        
        // Clean up: remove index.php and trailing slash
        $baseUrl = preg_replace('#/index\.php/?#', '/', $baseUrl);
        $baseUrl = rtrim($baseUrl, '/');
        
        return $baseUrl;
    }

    /**
     * Get checkout configuration as JSON
     *
     * Returns all checkout configuration as a JSON-encoded string
     * for use in Alpine.js components.
     *
     * @return string JSON-encoded configuration
     */
    public function getConfigJson(): string
    {
        return json_encode([
            'apiEndpoints' => $this->getApiEndpoints(),
            'defaultCountryCode' => $this->getDefaultCountryCode(),
            'isEnabled' => $this->isSimplyinEnabled(),
            'logoUrl' => $this->getSimplyinLogoUrl(),
            'newAccountCheckboxDefault' => $this->isNewAccountCheckboxDefault(),
        ], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
    }
}
