<?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;

class Events extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;
    
    /**
     * @var \Anowave\Ec\Helper\Data
     */
    protected $helper;
    
    /**
     * Constructor
     *
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
     * @param \Anowave\Ec\Helper\Data $helper
     */
    public function __construct
    (
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Anowave\Ec\Helper\Data $helper
    )
    {
        parent::__construct($context);
        
        /**
         * Set response type factory
         *
         * @var \Magento\Framework\Controller\Result\JsonFactory
         */
        $this->resultJsonFactory = $resultJsonFactory;
        
        /**
         * Set helper
         *
         * @var \Anowave\Ec\Helper\Data
         */
        $this->helper = $helper;
    }
    
    /**
     * Execute controller
     *
     * @see \Magento\Framework\App\ActionInterface::execute()
     */
    public function execute()
    {
        $events = [];

        foreach(
        [
            'contact_event',
            'cart_update_event',
            'newsletter_event',
            'customer_register_event',
            'customer_login_event',
            'customer_logout_event',
            'apply_coupon_event',
            'cancel_coupon_event'
        ] 
        as $event)
        {
            $payload = $this->helper->dequeueEvent($event);

            if (false !== $payload)
            {
                $events[] = json_decode($payload);
            }
        }

        return $this->resultJsonFactory->create()->setData
        (
            [
                'events' => $events
            ]
        );
    }
}