<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Plugin;

use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\App\Action\Action;
use WriteTextAI\WriteTextAI\ViewModel\Premium;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Response\Http;
use WriteTextAI\WriteTextAI\WtaiTrait\PremiumDataTrait;

class TotalCreditsPlugin
{
    use PremiumDataTrait;

    /**
     * @var Premium
     */
    protected $premium;

    /**
     * @var ResultFactory
     */
    protected $resultFactory;

    /**
     * @var Http
     */
    protected $httpResponse;

    /**
     * Constructor
     *
     * @param Premium $premium
     * @param ResultFactory $resultFactory
     * @param Http $httpResponse
     */
    public function __construct(
        Premium $premium,
        ResultFactory $resultFactory,
        Http $httpResponse
    ) {
        $this->premium = $premium;
        $this->resultFactory = $resultFactory;
        $this->httpResponse = $httpResponse;
    }

    /**
     * After execute
     *
     * @param Action $subject
     * @param ResultInterface $result
     *
     * @return ResultInterface
     */
    public function afterExecute(Action $subject, $result)
    {
        $request = $subject->getRequest();
        
        // Define allowed controllers/actions where the plugin should run
        $allowedControllers = [
            'wtai/grid/massFullAutomation',
            'wtai/grid/massGenerate',
            'wtai/grid/massKeywordAnalysis', 
            'wtai/grid/cancel',
            'wtai/grid/retry',
            'wtai/grid/getCredits',
            'wtai/edit/generate',
            'wtai/categories/edit_generate',
            'wtai/edit/keywordsOptimization_update',
            'wtai/edit/index',
            'wtai/categories/edit_index'
        ];
        
        $currentPath = $request->getModuleName() . '/' . $request->getControllerName() . '/' . $request->getActionName();

        if ($result instanceof \Magento\Framework\Controller\Result\Json &&
            $request->getModuleName() === 'wtai' &&
            $request->getRouteName() === 'wtai' &&
            in_array($currentPath, $allowedControllers)
        ) {
            $result->renderResult($this->httpResponse);
            $responseData = json_decode($this->httpResponse->getContent(), true);

            $credits = $this->collectPremiumData(true);

            $newResponse = $this->resultFactory->create(ResultFactory::TYPE_JSON);
            $newResponse->setData(array_merge($responseData, $credits));
            return $newResponse;
        }

        return $result;
    }
}
