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

use Magento\Backend\App\Action\Context;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\JsonFactory;
use Anowave\Ec\Model\Ads;
use Magento\Framework\View\Element\BlockFactory;

class Adjust extends Action
{
    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $jsonFactory;

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

    /**
     * @var BlockFactory
     */
    protected $blockFactory;

    /**
     * Constructor 
     * 
     * @param Context $context
     * @param JsonFactory $jsonFactory
     */
    public function __construct
    (
        Context $context,
        JsonFactory $jsonFactory,
        Ads $ads,
        BlockFactory $blockFactory
    ) 
    {
        parent::__construct($context);
        
        /**
         * Set JSON factory 
         * 
         * @var JsonFactory $jsonFactory
         */
        $this->jsonFactory = $jsonFactory;
        $this->ads = $ads;
        $this->blockFactory = $blockFactory;
    }
    
	public function execute()
	{
	    $resultJson = $this->jsonFactory->create();

        $errors = [];

        $adjustment = $this->getRequest()->getParam('adjustment');

        if ($adjustment)
        {
            $this->ads->applyAdjustment((int) $this->getRequest()->getParam('order'), $adjustment);
        }

        $errors = $this->ads->getErrors();

        $alert = [];

        $errors = [];

        if ($errors)
        {
            $alert['title']   = __('Failed to send Conversion Adjustment');
            $alert['content'] = nl2br(join(PHP_EOL, $errors));
        }
        else 
        {
            $alert['title']   = __('Success');
            $alert['content'] = __('Sent Conversion Adjustment successfully');
        }

	    return $resultJson->setData(
        [
            'success' => $errors ? false : true,
            'alert'   => $alert
        ]);
	}
}