<?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\Plugin\Order;

use Anowave\Ec\Model\Ads;
use Anowave\Ec\Model\QueueFactory;
use Anowave\Ec\Model\CookieManager;

class PlaceAfter
{
    /**
     * @var \Anowave\Ec\Model\TransactionFactory
     */
    protected $transactionFactory;
    
    /**
     * @var \Anowave\Ec\Model\Api\Measurement\Protocol
     */
    protected $protocol;
    
    /**
     * @var \Anowave\Ec\Helper\Data
     */
    protected $helper;
    
    /**
     * @var \Anowave\Ec\Model\Logger
     */
    protected $logger;

    /**
     * @var Ads
     */
    protected $ads;

    /**
     * QueueFactory
     */
    protected $queueFactory;

    protected CookieManager $cookieManager;
    
    /**
     * Constructor 
     * 
     * @param \Anowave\Ec\Model\TransactionFactory $transactionFactory
     * @param \Anowave\Ec\Model\Api\Measurement\Protocol $protocol
     * @param \Anowave\Ec\Helper\Data $helper
     * @param \Anowave\Ec\Model\Logger $logger
     */
    public function __construct
    (
        \Anowave\Ec\Model\TransactionFactory $transactionFactory,
        \Anowave\Ec\Model\Api\Measurement\Protocol $protocol,
        \Anowave\Ec\Helper\Data $helper,
        \Anowave\Ec\Model\Logger $logger,
        Ads $ads,
        QueueFactory $queueFactory,
        CookieManager $cookieManager
    )
    {
        /**
         * Set transaction factory 
         * 
         * @var \Anowave\Ec\Model\TransactionFactory $transactionFactory
         */
        $this->transactionFactory = $transactionFactory;
        
        /**
         * Set protocol
         *
         * @var \Anowave\Ec\Model\Api\Measurement\Protocol $protocol
         */
        $this->protocol = $protocol;
        
        /**
         * Set helper
         *
         * @var \Anowave\Ec\Helper\Data $helper
         */
        $this->helper = $helper;
        
        /**
         * Set logger 
         * 
         * @var \Anowave\Ec\Model\Logger $logger
         */
        $this->logger = $logger;

        /**
         * Set Google Ads API
         */
        $this->ads = $ads;

        /**
         * Set queue factory 
         * 
         * @var QueueFactory
         */
        $this->queueFactory = $queueFactory;

        $this->cookieManager = $cookieManager;
    }

    
    /**
     * @param \Magento\Sales\Api\OrderManagementInterface $orderManagementInterface
     * @param \Magento\Sales\Model\Order\Interceptor $order
     * @return $order
     */
    public function afterPlace(\Magento\Sales\Api\OrderManagementInterface $orderManagementInterface , $order)
    {
        $transaction = $this->transactionFactory->create();
        
        $transaction->setData
        (
            [
                'ec_track'    => \Anowave\Ec\Helper\Constants::FLAG_PLACED,
                'ec_order_id' => (int) $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->getStore()->getId()
        )))
        {
            $transaction->setEcCookieGaSession($gs);
        }

        if (isset($_COOKIE[\Anowave\Ec\Helper\Constants::COOKIE_CONSENT_UUID]))
        {
            $transaction->setEcConsentUuid($_COOKIE[\Anowave\Ec\Helper\Constants::COOKIE_CONSENT_UUID]);
            $transaction->setEcConsentId
            (
                $this->helper->getConsentId($_COOKIE[\Anowave\Ec\Helper\Constants::COOKIE_CONSENT_UUID])
            );
        }
        
        if (!(php_sapi_name() == 'cli')) 
        {
            if (isset($_SERVER['HTTP_USER_AGENT']))
            {
                $transaction->setEcUserAgent($_SERVER['HTTP_USER_AGENT']);
            }
        }

        try 
        {
            $transaction->setConsent()->save();
        }
        catch (\Exception $e) {}
        
        
        /**
         * Track order on placed
         */
        if ($this->helper->useMeasurementProtocolOnlyPlaced())
        {
            if (false !== $this->protocol->purchaseById($order->getId()))
            {
                try 
                {
                    $transaction->setData('ec_track', \Anowave\Ec\Helper\Constants::FLAG_TRACKED);
                    $transaction->save();
                }
                catch (\Exception $e)
                {
                    $this->logger->info('Failed to set server-side transaction flag to tracked.');
                }
                
                $this->logger->log("ORDER ID ({$order->getIncrementId()}) tracked to GA4 successfully.");
            }
            else 
            {
                $this->logger->log("Failed to track {$order->getId()} to GA4.");
            }
        }

        if ($this->helper->useAdwordsGoogleAdsApiAdjustment())
        {
            try 
            {
                $queue = $this->queueFactory->create();

                $queue->setQueueOrderId($order->getId());
                $queue->save();
            }
            catch (\Exception $e)
            {
                $this->logger->log("Failed to queue ({$order->getIncrementId()}) for Enhanced Conversion");
            }
        }
        
       return $order;
    }
}