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

use Magento\Checkout\Controller\Cart\CouponPost;
use Magento\Quote\Model\Quote;
use Magento\Customer\Model\SessionFactory;
use Magento\Customer\Model\Session;
use Magento\Checkout\Model\Session as CheckoutSession;
use Anowave\Ec\Helper\Json;
use Magento\SalesRule\Model\CouponFactory;

class Coupon
{
    protected Quote $quote;
    protected SessionFactory $sessionFactory;
    protected Session $session;
    protected Json $jsonHelper;
    protected CouponFactory $couponFactory;
    protected CheckoutSession $checkoutSession;

    /**
     * Constructor
     */
    public function __construct
    (
        Quote $quote,
        SessionFactory $sessionFactory,
        Json $jsonHelper,
        CouponFactory $couponFactory,
        CheckoutSession $checkoutSession
    )
    {

        $this->sessionFactory = $sessionFactory;
        $this->jsonHelper = $jsonHelper;
        $this->couponFactory = $couponFactory;
        $this->checkoutSession = $checkoutSession;

        $this->session = $this->sessionFactory->create();

        $this->quote = $this->checkoutSession->getQuote();
    }

    public function beforeExecute(CouponPost $context)
    {
        /**
         * Get applied coupon code
         */
        $couponCode = $context->getRequest()->getParam('remove') == 1 ? '' : trim($context->getRequest()->getParam('coupon_code', ''));

        /**
         * Get previously applied coupon code
         */
        $previousCouponCode = (string) $this->quote->getCouponCode();

        $codeLength = strlen($couponCode);

        if (!strlen($couponCode) && !strlen($previousCouponCode)) 
        {
            return false;
        }

        $event = [];

        if (!$couponCode)
        {
            $this->session->setCancelCouponEvent($this->jsonHelper->encode(
            [
                'event' 			=>    'cancelCouponCode',
                'eventCategory' 	=> __('Coupon'),
                'eventAction' 		=> __('Apply'),
                'eventLabel' 		=> (string) $previousCouponCode
            ]));
        }
        else 
        {
            $codeLength = strlen($couponCode);

            $isCodeLengthValid = $codeLength && $codeLength <= \Magento\Checkout\Helper\Cart::COUPON_CODE_MAX_LENGTH;

            if ($codeLength > 0 && $isCodeLengthValid)
            {
                try 
                {
                    $coupon = $this->couponFactory->create()->load($couponCode,'code');

                    if ($coupon->getId())
                    {
                        $this->session->setApplyCouponEvent($this->jsonHelper->encode(
                        [
                            'event' 			=>    'applyCouponCode',
                            'eventCategory' 	=> __('Coupon'),
                            'eventAction' 		=> __('Apply'),
                            'eventLabel' 		=> (string) $couponCode
                        ]));
                    }
                }
                catch (\Exception $e)
                {

                }
            }
        }
    }
}