<?php
/**
 * Magento 2 Google Analytics 4 (GA4) GTM
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Anowave license that is
 * available through the world-wide-web at this URL:
 * https://www.anowave.com/license-agreement/
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category 	Anowave
 * @package 	Anowave_Ec
 * @copyright 	Copyright (c) 2026 Anowave (https://www.anowave.com/)
 * @license  	https://www.anowave.com/license-agreement/
 */
 
namespace Anowave\Ec\Controller\Index;

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\App\Request\InvalidRequestException;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Anowave\Ec\Logger\Logger;
use Anowave\Ec\Model\TransactionRepository;


class State extends Action implements CsrfAwareActionInterface, HttpPostActionInterface, HttpGetActionInterface
{

	 /**
     * @var JsonFactory
     */
    protected JsonFactory $jsonFactory;

	protected $orderRepository;
    protected $searchCriteriaBuilder;
	protected $logger;
	protected $transactionRepository;
    /**
     * Constructor
     */
	public function __construct
	(
		Context $context,
		JsonFactory $jsonFactory,
		OrderRepositoryInterface $orderRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
		Logger $logger,
		TransactionRepository $transactionRepository
	)
	{
		parent::__construct($context);

		$this->jsonFactory = $jsonFactory;
		$this->orderRepository = $orderRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
		$this->logger = $logger;
		$this->transactionRepository = $transactionRepository;
	}

	/**
	 * Execute controller
	 *
	 * @see \Magento\Framework\App\ActionInterface::execute()
	 */
	public function execute()
	{ 
        $payload = $this->_request->getParams();

		
		$increment_id = $payload['payload']['ecommerce']['purchase']['transaction_id'];

		try 
		{
			$order = $this->getOrder($increment_id);

			if ($order)
			{
				$transaction = $this->transactionRepository->getByOrderId($order->getId());

				$transaction->setEcPayload
				(
					json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
				);

				try 
				{
					$this->transactionRepository->save($transaction);
				}
				catch (\Exception $e)
				{
					$this->logger->critical($e->getMessage());
				}
			}
			else 
			{
				$this->logger->warning('Order not found', [$increment_id]);
			}
			
		}
		catch (\Exception $e)
		{
			$this->logger->critical($e->getMessage());
		}

		$resultJson = $this->jsonFactory->create();
		
		return $resultJson->setData(
        [
            'state' => 1
        ]);
	}

	private function getOrder(string $increment_id)
    {
        return $this->orderRepository->getList
		(
			$this->searchCriteriaBuilder
				->addFilter('increment_id', $increment_id, 'eq')
				->setPageSize(1)
				->create()
		)
		->getFirstItem() ? : null;
    }
	
	/**
	 * Create CSRF Exception
	 *
	 * {@inheritDoc}
	 * @see \Magento\Framework\App\CsrfAwareActionInterface::createCsrfValidationException()
	 */
	public function createCsrfValidationException(RequestInterface $request): ? InvalidRequestException
	{
	    return null;
	}
	
	/**
	 * Validate for CSRF
	 *
	 * {@inheritDoc}
	 * @see \Magento\Framework\App\CsrfAwareActionInterface::validateForCsrf()
	 */
	public function validateForCsrf(RequestInterface $request): ? bool
	{
	    return true;
	}
}