<?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\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Simplyin\Payment\Helper\ApiClient;
use Psr\Log\LoggerInterface;

/**
 * Get payment methods controller
 *
 * Retrieves available payment methods from SimplyIN
 */
class GetPaymentMethods implements HttpPostActionInterface, CsrfAwareActionInterface
{
    use CsrfAwareApiTrait;

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

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

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

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

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

    /**
     * Execute get payment methods action
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultJsonFactory->create();
        
        try {
            // Get authToken from request if provided
            //$data = json_decode($this->request->getContent(), true);
            //$authToken = $data['authToken'] ?? '';

            // Call Simply.IN API to get payment methods
            $response = $this->apiClient->getPaymentMethods();

            if ($response['success']) {
                $paymentMethods = $response['data'] ?? [];
                
                return $result->setData([
                    'success' => true,
                    'paymentMethods' => $paymentMethods,
                    'message' => __('Payment methods retrieved successfully')
                ]);
            } else {
                return $result->setData([
                    'success' => false,
                    'message' => $response['error'] ?? __('Failed to get payment methods')
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN GetPaymentMethods: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            return $result->setData([
                'success' => false,
                'message' => __('An unexpected error occurred. Please try again.')
            ]);
        }
    }
}
