<?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\Adminhtml\Analytics;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use Magento\Sales\Api\OrderManagementInterface;
use Magento\Sales\Controller\Adminhtml\Order\AbstractMassAction;
use Anowave\Ec\Model\CookieManager;
use Magento\Sales\Model\Order;
use Magento\Framework\Api\SearchCriteriaBuilderFactory;
use Anowave\Ec4\Helper\Data;


class Track extends AbstractMassAction
{
	/**
	 * @var OrderManagementInterface
	 */
	protected $orderManagement;
	
	/**
	 * @var \Magento\Sales\Api\OrderRepositoryInterface
	 */
	protected $orderRepository;
	
	/**
	 * @var \Anowave\Ec\Model\Api\Measurement\Protocol
	 */
	protected $protocol;
	
	/**
	 * @var CollectionFactory
	 */
	protected $collectionFactory;
	
	/**
	 * @var \Anowave\Ec\Model\TransactionFactory
	 */
	protected $transactionFactory;
	
	/**
	 * @var \Anowave\Ec\Model\ResourceModel\Transaction\CollectionFactory
	 */
	protected $transactionCollectionFactory;

	/**
	 * @var CookieManager
	 */
	protected $cookieManager;

	protected Data $helper;
	/**
	 * @var SearchCriteriaBuilderFactory
	 */
	protected $searchCriteriaBuilderFactory;

	public function __construct
	(
		Context $context,
		Filter $filter,
		CollectionFactory $collectionFactory,
		OrderManagementInterface $orderManagement,
		\Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
		\Anowave\Ec\Model\Api\Measurement\Protocol $protocol,
	    \Anowave\Ec\Model\TransactionFactory $transactionFactory,
	    \Anowave\Ec\Model\ResourceModel\Transaction\CollectionFactory $transactionCollectionFactory,
		CookieManager $cookieManager,
		Data $helper,
		SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory

	)
	{
		parent::__construct($context, $filter);

		/**
		 * Set collection factory
		 *
		 * @var CollectionFactory
		 */
		$this->collectionFactory = $collectionFactory;

		/**
		 * Set order management
		 *
		 * @var OrderManagementInterface
		 */
		$this->orderManagement = $orderManagement;

		/**
		 * Set Measurement Protocol
		 */
		$this->protocol = $protocol;

		/**
		 * Set order repository
		 *
		 * @var \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
		 */
		$this->orderRepository = $orderRepository;

		/**
		 * Set transaction factory
		 *
		 * @var \Anowave\Ec\Model\TransactionFactory $transactionFactory
		 */
		$this->transactionFactory = $transactionFactory;

		/**
		 * @var \Anowave\Ec\Model\ResourceModel\Transaction\CollectionFactory $transactionCollectionFactory
		 */
		$this->transactionCollectionFactory = $transactionCollectionFactory;

		$this->cookieManager = $cookieManager;

		$this->helper = $helper;

		$this->searchCriteriaBuilderFactory = $searchCriteriaBuilderFactory;

	}
	
	/**
	 * Mass action
	 * 
	 * {@inheritDoc}
	 * @see \Magento\Sales\Controller\Adminhtml\Order\AbstractMassAction::massAction()
	 */
	protected function massAction(AbstractCollection $collection) 
	{
		/**
		 * Success log
		 * 
		 * @var array $success
		 */
		$success = [];
		
		/**
		 * Failure log 
		 * 
		 * @var array $failure
		 */
		$failure = [];

        /**
         * Batch preload orders in a single query
         */
        $orderIds = $collection->getAllIds();

        $preloadedOrders = [];

        if ($orderIds) 
		{
            $searchCriteriaBuilder = $this->searchCriteriaBuilderFactory->create();
            $searchCriteriaBuilder->addFilter('entity_id', $orderIds, 'in');
            $orderList = $this->orderRepository->getList($searchCriteriaBuilder->create());

            foreach ($orderList->getItems() as $order) 
			{
                $preloadedOrders[$order->getEntityId()] = $order;
            }
        }

        foreach ($preloadedOrders as $order)
        {
        	if (false !== $this->protocol->purchaseById($order->getId()))
        	{
        		$success[] = __("Transaction {$order->getIncrementId()} successfully sent to Google Analytics");

        		/**
        		 * Save track information
        		 */
        		$this->track($order);
        	}
        	else
        	{
        	    $failure[] = __("Failed to send transaction {$order->getIncrementId()}  to Google Analytics");

        	    foreach ($this->protocol->getErrors() as $error)
        	    {
        	        $failure[] = $error;
        	    }
        	}
        }
        
        foreach ($success as $message)
        {
        	$this->messageManager->addSuccessMessage($message);
        }
        
        foreach ($failure as $message)
        {
        	$this->messageManager->addErrorMessage($message);
        }
        
        $resultRedirect = $this->resultRedirectFactory->create();
        
        $resultRedirect->setPath('sales/order/index');
        
        return $resultRedirect;
    }
    
    /**
     * Track order 
     * 
     * @param Order $order
     */
    protected function track(Order $order)
    {
        $collection = $this->transactionCollectionFactory->create()->addFieldToFilter('ec_order_id', $order->getId());
          
        if (!$collection->getSize())
        {
            $transaction = $this->transactionFactory->create();
            
            /**
             * Set data
             */
            $transaction->setEcOrderId($order->getId());

			if (null !== $fpid = $this->cookieManager->getFpidCookie())
            {
                $transaction->setEcCookieFpid($fpid);
            }
            
            if (null !== $ga = $this->cookieManager->getGaCookie())
			{
				$transaction->setEcCookieGa($ga);
			}

			if (null !== $gs = $this->cookieManager->getGaSessionCookie($this->helper->getMeasurementId($order->getStoreId())))
			{
				$transaction->setEcCookieGaSession($gs);
			}
            
            if (!(php_sapi_name() == 'cli'))
            {
                if (isset($_SERVER['HTTP_USER_AGENT']))
                {
                    $transaction->setEcUserAgent($_SERVER['HTTP_USER_AGENT']);
                }
            }
        }
        else 
        {
            $transaction = $collection->getFirstitem();
        }

        $transaction->setEcTrack(\Anowave\Ec\Helper\Constants::FLAG_TRACKED);
        $transaction->setEcOrderType(\Anowave\Ec\Helper\Constants::ORDER_TYPE_BACKEND);

        $transaction->save();
    }

    protected function _isAllowed() 
    {
        return true;
    }
}