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

namespace Simplyin\Payment\Controller\Api;

use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order\Payment\Transaction;
use Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface as TransactionBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Simplyin\Payment\Helper\ApiClient;
use Psr\Log\LoggerInterface;

/**
 * Check Payment Status Controller
 *
 * Checks payment status from local order data (updated by webhook)
 * Falls back to SimplyIN API if local status not available
 * Saves transaction details when payment is completed
 */
class CheckPaymentStatus implements HttpPostActionInterface, HttpGetActionInterface, CsrfAwareActionInterface
{
    use CsrfAwareApiTrait;

    /**
     * @var JsonFactory
     */
    private $resultJsonFactory;

    /**
     * @var ApiClient
     */
    private $apiClient;

    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * @var SearchCriteriaBuilder
     */
    private $searchCriteriaBuilder;

    /**
     * @var TransactionBuilder
     */
    private $transactionBuilder;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var RequestInterface
     */
    private $request;

    /**
     * Constructor
     *
     * @param JsonFactory $resultJsonFactory
     * @param ApiClient $apiClient
     * @param OrderRepositoryInterface $orderRepository
     * @param SearchCriteriaBuilder $searchCriteriaBuilder
     * @param TransactionBuilder $transactionBuilder
     * @param LoggerInterface $logger
     * @param RequestInterface $request
     */
    public function __construct(
        JsonFactory $resultJsonFactory,
        ApiClient $apiClient,
        OrderRepositoryInterface $orderRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        TransactionBuilder $transactionBuilder,
        LoggerInterface $logger,
        RequestInterface $request
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->apiClient = $apiClient;
        $this->orderRepository = $orderRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->transactionBuilder = $transactionBuilder;
        $this->logger = $logger;
        $this->request = $request;
    }

    /**
     * Execute payment status check
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultJsonFactory->create();

        try {
            $params = $this->parseRequestParams();
            $paymentId = $params['paymentId'];
            $authToken = $params['authToken'];
            $orderId = $params['orderId'];

            $this->logger->info('SimplyIN CheckPaymentStatus called', [
                'paymentId' => $paymentId,
                'orderId' => $orderId
            ]);

            // First, try to get status from local order (updated by webhook)
            $localResponse = $this->resolveLocalStatusResponse($orderId, $paymentId, $authToken);
            if ($localResponse !== null) {
                return $result->setData($localResponse);
            }

            // If no local status and no paymentId, return pending
            if (empty($paymentId)) {
                return $result->setData([
                    'success' => true,
                    'paymentId' => $paymentId,
                    'status' => 'PENDING',
                    'message' => 'Waiting for payment confirmation via webhook'
                ]);
            }

            // Fallback: Try to get status from SimplyIN API
            return $result->setData($this->resolveApiStatusResponse($paymentId, $authToken, $orderId));

        } catch (\Exception $e) {
            $this->logger->error('SimplyIN CheckPaymentStatus exception', [
                'message' => __('An unexpected error occurred. Please try again.'),
                'trace' => $e->getTraceAsString()
            ]);

            // Return PENDING on exception - don't fail the polling
            return $result->setData([
                'success' => true,
                'status' => 'PENDING',
                'message' => 'Waiting for payment confirmation'
            ]);
        }
    }

    /**
     * Parse request parameters from POST body or GET params
     *
     * @return array
     */
    private function parseRequestParams()
    {
        // Get parameters from POST body or GET params
        $data = json_decode($this->request->getContent(), true);

        if (empty($data)) {
            $data = [
                'paymentId' => $this->request->getParam('paymentId'),
                'authToken' => $this->request->getParam('authToken'),
                'orderId' => $this->request->getParam('orderId')
            ];
        }

        return [
            'paymentId' => $data['paymentId'] ?? '',
            'authToken' => $data['authToken'] ?? '',
            'orderId' => $data['orderId'] ?? ''
        ];
    }

    /**
     * Resolve a response array from the SimplyIN API fallback
     *
     * @param string $paymentId
     * @param string $authToken
     * @param string $orderId
     * @return array
     */
    private function resolveApiStatusResponse($paymentId, $authToken, $orderId)
    {
        $response = $this->apiClient->getPaymentStatus($paymentId, $authToken);

        if (!$response['success']) {
            $this->logger->warning('SimplyIN CheckPaymentStatus: API call failed, returning PENDING', [
                'paymentId' => $paymentId,
                'error' => $response['error'] ?? 'Unknown error'
            ]);

            // Don't return error - return PENDING status instead
            // The webhook will update the order when payment is confirmed
            return [
                'success' => true,
                'paymentId' => $paymentId,
                'status' => 'PENDING',
                'message' => 'Waiting for payment confirmation'
            ];
        }

        $status = $response['status'] ?? 'PENDING';
        $responseData = $response['data'] ?? [];

        // Map API status to our standard statuses
        $mappedStatus = $this->mapApiStatus($status);

        // If payment is COMPLETED/PAID, save transaction details to order
        if ($mappedStatus === 'COMPLETED' && $orderId) {
            $this->saveTransactionDetails($orderId, $paymentId, $responseData);
        }

        // Extract additional info from response
        $errorMessage = '';
        if ($mappedStatus === 'FAILED') {
            $errorMessage = $this->resolveApiErrorMessage($responseData);
        }

        return [
            'success' => true,
            'paymentId' => $paymentId,
            'status' => $mappedStatus,
            'errorMessage' => $errorMessage,
            'data' => $responseData
        ];
    }

    /**
     * Resolve the error message for a failed payment from response data
     *
     * @param array $responseData
     * @return mixed
     */
    private function resolveApiErrorMessage($responseData)
    {
        return $responseData['errorMessage']
            ?? $responseData['error']
            ?? $responseData['failureReason']
            ?? __('Payment was declined');
    }

    /**
     * Resolve a ready response from local order status (local-first precedence)
     *
     * @param string $orderId
     * @param string $paymentId
     * @param string $authToken
     * @return array|null Ready response array, or null to continue to API
     */
    private function resolveLocalStatusResponse($orderId, $paymentId, $authToken)
    {
        if (!$orderId) {
            return null;
        }

        $localStatus = $this->getLocalOrderPaymentStatus($orderId);
        if (!$localStatus) {
            return null;
        }

        $this->logger->info('SimplyIN CheckPaymentStatus: Found local status', [
            'orderId' => $orderId,
            'status' => $localStatus['status']
        ]);

        // If local status is PAID/COMPLETED, check if transaction details are already saved
        if (in_array($localStatus['status'], ['COMPLETED', 'PAID', 'SUCCESS'])) {
            // Try to save transaction details if not yet saved (needs API data)
            if ($paymentId) {
                $this->saveTransactionDetailsIfNeeded($orderId, $paymentId, $authToken);
            }
            return $localStatus;
        }

        // If local status is FAILED/REJECTED, return immediately
        if (in_array($localStatus['status'], ['FAILED', 'REJECTED', 'CANCELLED', 'CANCELED'])) {
            return $localStatus;
        }

        // For PENDING status, check if order state indicates completion
        if ($localStatus['orderState'] === \Magento\Sales\Model\Order::STATE_PROCESSING ||
            $localStatus['orderState'] === \Magento\Sales\Model\Order::STATE_COMPLETE) {
            $localStatus['status'] = 'COMPLETED';
            // Try to save transaction details if not yet saved
            if ($paymentId) {
                $this->saveTransactionDetailsIfNeeded($orderId, $paymentId, $authToken);
            }
            return $localStatus;
        }

        return null;
    }

    /**
     * Map API status to standard status
     *
     * @param string $apiStatus
     * @return string
     */
    private function mapApiStatus($apiStatus)
    {
        $statusMap = [
            'PAID' => 'COMPLETED',
            'COMPLETED' => 'COMPLETED',
            'SUCCESS' => 'COMPLETED',
            'CONFIRMED' => 'COMPLETED',
            'APPROVED' => 'COMPLETED',
            'REJECTED' => 'FAILED',
            'FAILED' => 'FAILED',
            'CANCELLED' => 'FAILED',
            'CANCELED' => 'FAILED',
            'DECLINED' => 'FAILED',
            'ERROR' => 'FAILED',
            'PENDING' => 'PENDING',
            'PROCESSING' => 'PENDING',
            'WAITING' => 'PENDING',
            'IN_PROGRESS' => 'PENDING',
        ];

        $upperStatus = strtoupper($apiStatus);
        return $statusMap[$upperStatus] ?? 'PENDING';
    }

    /**
     * Get payment status from local Magento order
     *
     * @param string $orderId Order entity ID or increment ID
     * @return array|null
     */
    private function getLocalOrderPaymentStatus($orderId)
    {
        try {
            $order = null;

            // Try to load by entity ID first
            if (is_numeric($orderId)) {
                try {
                    $order = $this->orderRepository->get($orderId);
                } catch (\Exception $e) { // phpcs:ignore Magento2.CodeAnalysis.EmptyBlock.DetectedCatch -- intentional: order may not exist by entity ID, fall through to increment-ID lookup below
                    // Not found by entity ID
                }
            }

            // Try to load by increment ID
            if (!$order) {
                $searchCriteria = $this->searchCriteriaBuilder
                    ->addFilter('increment_id', $orderId)
                    ->create();
                $orders = $this->orderRepository->getList($searchCriteria);
                if ($orders->getTotalCount() > 0) {
                    $items = $orders->getItems();
                    $order = reset($items);
                }
            }

            if (!$order) {
                return null;
            }

            // Get payment status from order payment additional info
            $payment = $order->getPayment();
            $simplyinStatus = null;
            $webhookReceived = null;
            
            if ($payment) {
                $simplyinStatus = $payment->getAdditionalInformation('simplyin_payment_status');
                $webhookReceived = $payment->getAdditionalInformation('simplyin_webhook_received');
            }

            // Map order state to payment status
            $orderState = $order->getState();
            $status = $this->resolveLocalOrderStatus($simplyinStatus, $orderState);

            return [
                'success' => true,
                'status' => $status,
                'orderId' => $order->getIncrementId(),
                'orderState' => $orderState,
                'simplyinStatus' => $simplyinStatus,
                'webhookReceived' => $webhookReceived,
                'source' => 'local'
            ];

        } catch (\Exception $e) {
            $this->logger->warning('SimplyIN CheckPaymentStatus: Failed to get local status', [
                'orderId' => $orderId,
                'error' => $e->getMessage()
            ]);
            return null;
        }
    }

    /**
     * Map SimplyIN/order state to a payment status string
     *
     * @param string|null $simplyinStatus
     * @param string|null $orderState
     * @return string
     */
    private function resolveLocalOrderStatus($simplyinStatus, $orderState)
    {
        // Check if payment was marked as PAID by webhook
        if ($simplyinStatus === 'PAID' || $simplyinStatus === 'COMPLETED' || $simplyinStatus === 'SUCCESS') {
            return 'COMPLETED';
        }
        if (in_array($simplyinStatus, ['FAILED', 'REJECTED', 'CANCELLED', 'CANCELED'])) {
            return 'FAILED';
        }

        return $this->resolveLocalOrderStatusByState($orderState);
    }

    /**
     * Map order state to a payment status string
     *
     * @param string|null $orderState
     * @return string
     */
    private function resolveLocalOrderStatusByState($orderState)
    {
        if ($orderState === \Magento\Sales\Model\Order::STATE_PROCESSING ||
            $orderState === \Magento\Sales\Model\Order::STATE_COMPLETE) {
            // Order was updated to processing (likely by webhook)
            return 'COMPLETED';
        }
        if ($orderState === \Magento\Sales\Model\Order::STATE_CANCELED) {
            return 'FAILED';
        }
        if ($orderState === \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT ||
            $orderState === \Magento\Sales\Model\Order::STATE_NEW) {
            // Order is still pending - payment might be processing
            return 'PENDING';
        }

        return 'PENDING';
    }

    /**
     * Save transaction details if not already saved
     *
     * Calls the API to get full payment data and saves transaction to order
     *
     * @param string $orderId
     * @param string $paymentId
     * @param string $authToken
     * @return void
     */
    private function saveTransactionDetailsIfNeeded($orderId, $paymentId, $authToken)
    {
        try {
            $order = $this->loadOrder($orderId);
            if (!$order) {
                $this->logger->warning('SimplyIN CheckPaymentStatus: saveTransactionDetailsIfNeeded - order not found', [
                    'orderId' => $orderId
                ]);
                return;
            }
            
            if (!$order->getPayment()) {
                $this->logger->warning('SimplyIN CheckPaymentStatus: saveTransactionDetailsIfNeeded - no payment object', [
                    'orderId' => $orderId
                ]);
                return;
            }

            // Check if transaction already exists
            $existingTxnId = $order->getPayment()->getAdditionalInformation('simplyin_transaction_id');
            if ($existingTxnId) {
                $this->logger->info('SimplyIN CheckPaymentStatus: Transaction already saved', [
                    'orderId' => $orderId,
                    'transactionId' => $existingTxnId
                ]);
                return;
            }

            $this->logger->info('SimplyIN CheckPaymentStatus: Transaction not yet saved, fetching from API', [
                'orderId' => $orderId,
                'paymentId' => $paymentId,
                'authToken' => !empty($authToken) ? 'present' : 'empty'
            ]);

            // Call API to get full payment data
            $response = $this->apiClient->getPaymentStatus($paymentId, $authToken);
            
            $this->logger->info('SimplyIN CheckPaymentStatus: getPaymentStatus API response', [
                'success' => $response['success'] ?? false,
                'status' => $response['status'] ?? '',
                'hasData' => !empty($response['data'])
            ]);
            
            if ($response['success']) {
                $responseData = $response['data'] ?? [];
                $status = $response['status'] ?? '';
                $mappedStatus = $this->mapApiStatus($status);

                $this->logger->info('SimplyIN CheckPaymentStatus: Mapped status', [
                    'rawStatus' => $status,
                    'mappedStatus' => $mappedStatus
                ]);

                if ($mappedStatus === 'COMPLETED') {
                    $this->saveTransactionDetails($orderId, $paymentId, $responseData);
                } else {
                    $this->logger->info('SimplyIN CheckPaymentStatus: Status not COMPLETED, skipping transaction save', [
                        'mappedStatus' => $mappedStatus
                    ]);
                }
            } else {
                $this->logger->warning('SimplyIN CheckPaymentStatus: API call failed in saveTransactionDetailsIfNeeded', [
                    'error' => $response['error'] ?? 'Unknown'
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN CheckPaymentStatus: saveTransactionDetailsIfNeeded exception', [
                'orderId' => $orderId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    }

    /**
     * Save payment transaction details to order
     *
     * @param string $orderId Order entity ID or increment ID
     * @param string $paymentId SimplyIN payment ID
     * @param array $paymentData Payment data from API response
     * @return void
     */
    private function saveTransactionDetails($orderId, $paymentId, $paymentData)
    {
        try {
            $order = $this->loadOrder($orderId);
            
            if (!$order) {
                $this->logger->warning('SimplyIN CheckPaymentStatus: Cannot save transaction - order not found', [
                    'orderId' => $orderId
                ]);
                return;
            }

            $payment = $order->getPayment();
            if (!$payment) {
                $this->logger->warning('SimplyIN CheckPaymentStatus: Cannot save transaction - no payment object', [
                    'orderId' => $orderId
                ]);
                return;
            }

            // Check if transaction already exists
            $existingTxnId = $payment->getAdditionalInformation('simplyin_transaction_id');
            if ($existingTxnId) {
                $this->logger->info('SimplyIN CheckPaymentStatus: Transaction already saved', [
                    'orderId' => $orderId,
                    'transactionId' => $existingTxnId
                ]);
                return;
            }

            $details = $this->populatePaymentAdditionalInformation($payment, $paymentId, $paymentData);
            $providerPaymentId = $details['providerPaymentId'];
            $paymentMethodId = $details['paymentMethodId'];
            $paymentProviderType = $details['paymentProviderType'];
            $amount = $details['amount'];
            $currency = $details['currency'];
            $providerDisplayName = $details['providerDisplayName'];
            $paymentMethodName = $details['paymentMethodName'];

            // Set transaction ID on payment
            $payment->setTransactionId($providerPaymentId);
            $payment->setLastTransId($providerPaymentId);

            // Create payment transaction record
            $transaction = $this->transactionBuilder
                ->setPayment($payment)
                ->setOrder($order)
                ->setTransactionId($providerPaymentId)
                ->setAdditionalInformation($this->buildTransactionRawDetails($details))
                ->setFailSafe(true)
                ->build(Transaction::TYPE_CAPTURE);

            $transaction->setIsClosed(true);
            $payment->addTransactionCommentsToOrder(
                $transaction,
                __(
                    'Payment verified via SimplyIN. Provider: %1, Method: %2, Transaction ID: %3',
                    $providerDisplayName,
                    $paymentMethodName,
                    $providerPaymentId
                )
            );

            // Update order state to processing if still pending
            if ($order->getState() === \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT ||
                $order->getState() === \Magento\Sales\Model\Order::STATE_NEW) {
                $order->setState(\Magento\Sales\Model\Order::STATE_PROCESSING);
                $order->setStatus(\Magento\Sales\Model\Order::STATE_PROCESSING);
            }

            // Save order with payment and transaction
            $this->orderRepository->save($order);


            $this->logger->info('SimplyIN CheckPaymentStatus: Transaction details saved', [
                'orderId' => $order->getIncrementId(),
                'transactionId' => $providerPaymentId,
                'paymentMethod' => $paymentMethodId,
                'provider' => $paymentProviderType,
                'amount' => $amount,
                'currency' => $currency
            ]);

        } catch (\Exception $e) {
            $this->logger->error('SimplyIN CheckPaymentStatus: Failed to save transaction details', [
                'orderId' => $orderId,
                'paymentId' => $paymentId,
                'error' => $e->getMessage()
            ]);
        }
    }

    /**
     * Extract derived transaction details and write them to the payment object.
     *
     * Pure data preparation + payment additional-information writes; performed
     * before the transaction is built. Does not register or save the transaction.
     *
     * @param \Magento\Sales\Api\Data\OrderPaymentInterface $payment
     * @param string $paymentId
     * @param array $paymentData
     * @return array Derived values used to build the transaction record
     */
    private function populatePaymentAdditionalInformation($payment, $paymentId, $paymentData)
    {
        // Extract transaction details from payment data
        $ids = $this->extractTransactionIds($paymentId, $paymentData);
        $providerPaymentId = $ids['providerPaymentId'];
        $merchantPaymentId = $ids['merchantPaymentId'];
        $paymentMethodId = $ids['paymentMethodId'];
        $paymentProviderType = $ids['paymentProviderType'];

        $amounts = $this->extractTransactionAmounts($paymentData);
        $paymentProviderId = $amounts['paymentProviderId'];
        $amount = $amounts['amount'];
        $currency = $amounts['currency'];
        $status = $amounts['status'];

        // Get provider display information
        $providerInfo = $this->getPaymentProviderInfo($paymentProviderType);
        $providerDisplayName = $providerInfo['name'];

        // Save payment additional information
        $payment->setAdditionalInformation('simplyin_payment_id', $merchantPaymentId);
        $payment->setAdditionalInformation('simplyin_provider_payment_id', $providerPaymentId);
        $payment->setAdditionalInformation('simplyin_payment_method', $paymentMethodId);
        $payment->setAdditionalInformation('simplyin_payment_provider', $paymentProviderType);
        $payment->setAdditionalInformation('simplyin_payment_provider_name', $providerDisplayName);
        $payment->setAdditionalInformation('simplyin_payment_provider_id', $paymentProviderId);
        $payment->setAdditionalInformation('simplyin_payment_status', $status);
        $payment->setAdditionalInformation('simplyin_payment_amount', $amount);
        $payment->setAdditionalInformation('simplyin_payment_currency', $currency);
        $payment->setAdditionalInformation('simplyin_transaction_id', $providerPaymentId);
        $payment->setAdditionalInformation('simplyin_status_checked_at', date('Y-m-d H:i:s'));

        // Get payment method display name
        $paymentMethodName = $this->getPaymentMethodDisplayName($paymentMethodId);
        $payment->setAdditionalInformation('simplyin_payment_method_name', $paymentMethodName);

        return [
            'providerPaymentId' => $providerPaymentId,
            'merchantPaymentId' => $merchantPaymentId,
            'paymentMethodId' => $paymentMethodId,
            'paymentProviderType' => $paymentProviderType,
            'amount' => $amount,
            'currency' => $currency,
            'status' => $status,
            'providerDisplayName' => $providerDisplayName,
            'paymentMethodName' => $paymentMethodName,
        ];
    }

    /**
     * Extract transaction identifier fields from payment data
     *
     * @param string $paymentId
     * @param array $paymentData
     * @return array
     */
    private function extractTransactionIds($paymentId, $paymentData)
    {
        return [
            'providerPaymentId' => $paymentData['providerPaymentId'] ?? $paymentId,
            'merchantPaymentId' => $paymentData['merchantPaymentId'] ?? $paymentId,
            'paymentMethodId' => $paymentData['paymentMethodId'] ?? 'card',
            'paymentProviderType' => $paymentData['paymentProviderType'] ?? 'simplyin',
        ];
    }

    /**
     * Extract transaction amount/status fields from payment data
     *
     * @param array $paymentData
     * @return array
     */
    private function extractTransactionAmounts($paymentData)
    {
        return [
            'paymentProviderId' => $paymentData['paymentProviderId'] ?? '',
            'amount' => $paymentData['amount'] ?? 0,
            'currency' => $paymentData['currency'] ?? 'PLN',
            'status' => $paymentData['status'] ?? 'PAID',
        ];
    }

    /**
     * Build the transaction RAW_DETAILS additional-information payload
     *
     * @param array $details Derived transaction values
     * @return array
     */
    private function buildTransactionRawDetails($details)
    {
        return [Transaction::RAW_DETAILS => [
            'SimplyIN Payment ID' => $details['merchantPaymentId'],
            'Provider Payment ID' => $details['providerPaymentId'],
            'Payment Method' => $details['paymentMethodName'],
            'Payment Provider' => $details['providerDisplayName'],
            'Amount' => number_format($details['amount'] / 100, 2) . ' ' . $details['currency'],
            'Status' => $details['status'],
            'Verified At' => date('Y-m-d H:i:s')
        ]];
    }

    /**
     * Load order by entity ID or increment ID
     *
     * @param string $orderId
     * @return \Magento\Sales\Api\Data\OrderInterface|null
     */
    private function loadOrder($orderId)
    {
        $order = null;

        // Try to load by entity ID first
        if (is_numeric($orderId)) {
            try {
                $order = $this->orderRepository->get($orderId);
            } catch (\Exception $e) { // phpcs:ignore Magento2.CodeAnalysis.EmptyBlock.DetectedCatch -- intentional: order may not exist by entity ID, fall through to increment-ID lookup below
                // Not found by entity ID
            }
        }

        // Try to load by increment ID
        if (!$order) {
            $searchCriteria = $this->searchCriteriaBuilder
                ->addFilter('increment_id', $orderId)
                ->create();
            $orders = $this->orderRepository->getList($searchCriteria);
            if ($orders->getTotalCount() > 0) {
                $items = $orders->getItems();
                $order = reset($items);
            }
        }

        return $order;
    }

    /**
     * Get payment provider display information
     *
     * @param string $providerType Provider type from API (e.g., 'payu', 'przelewy24', 'stripe')
     * @return array Provider info with name and logo URL
     */
    private function getPaymentProviderInfo($providerType)
    {
        $providers = [
            'payu' => [
                'name' => 'PayU',
                'logo' => 'https://static.payu.com/images/mobile/logos/pbl_payu.png'
            ],
            'przelewy24' => [
                'name' => 'Przelewy24',
                'logo' => 'https://www.przelewy24.pl/themes/starter/images/logo.svg'
            ],
            'p24' => [
                'name' => 'Przelewy24',
                'logo' => 'https://www.przelewy24.pl/themes/starter/images/logo.svg'
            ],
            'stripe' => [
                'name' => 'Stripe',
                'logo' => 'https://stripe.com/img/v3/home/twitter.png'
            ],
            'adyen' => [
                'name' => 'Adyen',
                'logo' => 'https://www.adyen.com/dam/jcr:a0a3e3a0-3e3e-4e3e-8e3e-3e3e3e3e3e3e/adyen-logo.svg'
            ],
            'tpay' => [
                'name' => 'Tpay',
                'logo' => 'https://tpay.com/img/logo.svg'
            ],
            'dotpay' => [
                'name' => 'Dotpay',
                'logo' => 'https://www.dotpay.pl/img/logo.svg'
            ],
            'blik' => [
                'name' => 'BLIK',
                'logo' => 'https://blik.com/themes/starter/images/logo.svg'
            ],
            'espago' => [
                'name' => 'Espago',
                'logo' => 'https://espago.com/images/logo.svg'
            ],
            'saferpay' => [
                'name' => 'Saferpay (Worldline)',
                'logo' => 'https://www.saferpay.com/images/logo.svg'
            ],
            'worldline' => [
                'name' => 'Worldline',
                'logo' => 'https://worldline.com/images/logo.svg'
            ],
            'simplyin' => [
                'name' => 'SimplyIN',
                'logo' => ''
            ]
        ];

        $providerKey = strtolower($providerType);
        
        if (isset($providers[$providerKey])) {
            return $providers[$providerKey];
        }

        // Return formatted provider type if not in mapping
        return [
            'name' => ucfirst($providerType),
            'logo' => ''
        ];
    }

    /**
     * Get payment method display name
     *
     * @param string $methodId Payment method ID from API
     * @return string Display name
     */
    private function getPaymentMethodDisplayName($methodId)
    {
        $methods = [
            'card' => 'Credit/Debit Card',
            'credit_card' => 'Credit Card',
            'debit_card' => 'Debit Card',
            'blik' => 'BLIK',
            'bank_transfer' => 'Bank Transfer',
            'online_transfer' => 'Online Transfer',
            'pbl' => 'Pay-by-Link',
            'apple_pay' => 'Apple Pay',
            'google_pay' => 'Google Pay',
            'paypal' => 'PayPal',
            'klarna' => 'Klarna',
            'ideal' => 'iDEAL',
            'sofort' => 'Sofort',
            'giropay' => 'Giropay',
            'eps' => 'EPS',
            'bancontact' => 'Bancontact',
            'p24' => 'Przelewy24',
            'sepa' => 'SEPA Direct Debit',
            'saved_card' => 'Saved Card',
            'one_click' => 'One-Click Payment'
        ];

        $methodKey = strtolower($methodId);
        
        if (isset($methods[$methodKey])) {
            return $methods[$methodKey];
        }

        // Return formatted method ID if not in mapping
        return ucwords(str_replace(['_', '-'], ' ', $methodId));
    }
}
