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

/**
 * Copyright © Simplyin. All rights reserved.
 */
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 Magento\Sales\Api\OrderRepositoryInterface;
use Psr\Log\LoggerInterface;

/**
 * Verify Payment controller
 *
 * Handles payment verification retry for existing Magento orders
 */
class VerifyPayment implements HttpPostActionInterface, CsrfAwareActionInterface
{
    use CsrfAwareApiTrait;

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

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

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

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

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

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

    /**
     * Execute verify payment action
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultJsonFactory->create();
        
        try {
            $data = json_decode($this->request->getContent(), true);
            
            $magentoOrderId = $data['magentoOrderId'] ?? null;
            $simplyinOrderId = $data['simplyinOrderId'] ?? null;
            $authToken = $data['authToken'] ?? '';
            $paymentData = $data['paymentData'] ?? [];

            if (!$magentoOrderId || !$simplyinOrderId) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Order ID and SimplyIN Order ID are required')
                ]);
            }

            // Load Magento order
            $order = $this->orderRepository->get($magentoOrderId);
            
            if (!$order->getId()) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Magento order not found')
                ]);
            }

            // Verify order belongs to SimplyIN payment method
            if ($order->getPayment()->getMethod() !== 'simplyin_payment') {
                return $result->setData([
                    'success' => false,
                    'message' => __('Order does not use SimplyIN payment method')
                ]);
            }

            // Check if order already has a SimplyIN order ID (from payment additional info)
            $existingSimplyinOrderId = $order->getPayment()->getAdditionalInformation('simplyin_order_id');
            if ($existingSimplyinOrderId && $existingSimplyinOrderId !== $simplyinOrderId) {
                $this->logger->warning('SimplyIN: Order ID mismatch', [
                    'magento_order_id' => $magentoOrderId,
                    'existing_simplyin_order_id' => $existingSimplyinOrderId,
                    'provided_simplyin_order_id' => $simplyinOrderId
                ]);
            }

            // Create payment link for the existing SimplyIN order
            $paymentResponse = $this->apiClient->createPaymentLink($paymentData, $authToken);

            if ($paymentResponse['success']) {
                $paymentData = $paymentResponse['data'];
                
                // Update order with payment information
                $payment = $order->getPayment();
                $payment->setAdditionalInformation('simplyin_payment_id', $paymentData['paymentId'] ?? '');
                $payment->setAdditionalInformation('simplyin_provider_payment_id', $paymentData['providerPaymentId'] ?? '');
                $payment->setAdditionalInformation('simplyin_payment_status', $paymentData['status'] ?? 'PENDING');
                $payment->setAdditionalInformation('simplyin_registered_at', $paymentData['registeredAt'] ?? '');
                $payment->setAdditionalInformation('simplyin_redirect_url', $paymentData['redirectUrl'] ?? '');
                $payment->setAdditionalInformation('simplyin_redirect_iframe_allowed', $paymentData['redirectIframeAllowed'] ?? 0);
                
                // Save order
                $this->orderRepository->save($order);
                
                return $result->setData([
                    'success' => true,
                    'payment' => $paymentData,
                    'message' => __('Payment verification initiated successfully')
                ]);
            } else {
                return $result->setData([
                    'success' => false,
                    'message' => __('Payment verification failed: ') . ($paymentResponse['error'] ?? 'Unknown Error')
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN VerifyPayment Error: ' . $e->getMessage());
            return $result->setData([
                'success' => false,
                'message' => __('An unexpected error occurred. Please try again.')
            ]);
        }
    }
}
