<?php

namespace TbiBank\FusionPay\Controller\Api;

// Use statements for necessary Magento classes
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Checkout\Model\Session as CheckoutSession;

class GetLastOrderId extends Action
{
    /**
     * @var JsonFactory
     */
    protected $jsonResultFactory;

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

    /**
     * Constructor
     *
     * @param Context $context
     * @param JsonFactory $jsonResultFactory Factory for creating JSON response objects
     * @param CheckoutSession $checkoutSession Session object to retrieve last order ID
     */
    public function __construct(
        Context $context,
        JsonFactory $jsonResultFactory,
        CheckoutSession $checkoutSession
    ) {
        parent::__construct($context);
        $this->jsonResultFactory = $jsonResultFactory;
        $this->checkoutSession = $checkoutSession;
    }

    /**
     * Execute method for the controller action
     * 
     * This method retrieves the last order ID from the checkout session
     * and returns it in a JSON response format.
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        // Create a JSON result object
        $result = $this->jsonResultFactory->create();
        
        // Retrieve the last order ID from the checkout session
        $lastOrderId = $this->checkoutSession->getLastOrderId();
        
        // Set the last order ID in the response data
        $result->setData(['orderID' => $lastOrderId]);
        
        return $result;
    }
}
