<?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/
 */

declare(strict_types=1);

namespace Anowave\Ec\Ui\Component\Listing\Column;

use \Magento\Sales\Api\OrderRepositoryInterface;
use \Magento\Framework\View\Element\UiComponent\ContextInterface;
use \Magento\Framework\View\Element\UiComponentFactory;
use \Magento\Ui\Component\Listing\Columns\Column;
use \Magento\Framework\Api\SearchCriteriaBuilder;
use Anowave\Ec\Model\System\Config\Source\Consent\Classification;

class CurrentConsent extends Column
{
    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;
    
    /**
     * @var SearchCriteriaBuilder
     */
    protected $searchCriteria;
    
    /**
     * @var \Anowave\Ec\Model\ResourceModel\Transaction\CollectionFactory
     */
    protected $transactionsFactory;
    
    /**
     * @var \Magento\Framework\View\Element\BlockFactory
     */
    protected $blockFactory;

    /**
     * @var Classification
     */
    protected $classification;

    /**
     * Constructor 
     * 
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param OrderRepositoryInterface $orderRepository
     * @param SearchCriteriaBuilder $criteria
     * @param \Anowave\Ec\Model\ResourceModel\Transaction\CollectionFactory $transactionsFactory
     * @param array $components
     * @param array $data
     */
    public function __construct
    (
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        OrderRepositoryInterface $orderRepository,
        SearchCriteriaBuilder $criteria,
        \Anowave\Ec\Model\ResourceModel\Transaction\CollectionFactory $transactionsFactory,
        \Magento\Framework\View\Element\BlockFactory $blockFactory,
        Classification $classification,
        array $components = [],
        array $data = []
    ) 
    {
        /**
         * Set OrderRepositoryInterface
         * 
         * @var OrderRepositoryInterface $orderRepository
         */
        $this->orderRepository = $orderRepository;
        
        /**
         * Set SearchCriteriaBuilder
         * 
         * @var SearchCriteriaBuilder $searchCriteria
         */
        $this->searchCriteria  = $criteria;
        
        /**
         * Set transactions factory
         * 
         * @var \Anowave\Ec\Model\ResourceModel\Transaction\CollectionFactory $transactionsFactory
         */
        $this->transactionsFactory = $transactionsFactory;

        /**
		 * Set block factory 
		 * 
		 * @var \Magento\Framework\View\Element\BlockFactory $blockFactory
		 */
		$this->blockFactory = $blockFactory;

        /**
         * Set classification
         * 
         * @var Classification
         */
        $this->classification = $classification;

        
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }
    
    /**
     * Prepare data source
     * 
     * @param array $dataSource
     * @return array
     */
    public function prepareDataSource(array $dataSource) : array
    {
        $classification = [];

        foreach($this->classification->toOptionArray() as $option)
        {
            $classification[$option['value']] = $option['label']->__toString();
        }

        if (isset($dataSource['data']['items'])) 
        {
            foreach ($dataSource['data']['items'] as & $item) 
            {
                if (!isset($item['consent']) || !$item['consent'])
                {
                    $item['ec_consent_uuid'] = json_encode
                    (
                        [
                            'No consent cookie detected' => true
                        ]
                    );
                }
                else 
                {
                    $consent = json_decode($item['consent'], true);

                    $map = [];

                    foreach($classification as $segment => $value)
                    {
                        if ($segment)
                        {
                            if (array_key_exists($segment, $consent))
                            {
                                $key = sprintf('%s Granted', $value, $consent[$segment]);

                                $map[$key] = $consent[$segment];
                            }
                            else 
                            {
                                $key = sprintf('%s Declined', $value, false);

                                $map[$key] = false;
                            }
                        }  
                    }
                    
                    $item['ec_consent_uuid'] = json_encode($map);
                }
            }
        }
        
        return $dataSource;
    }
    
    /**
     * Apply sorting
     */
    protected function applySorting()
    {
        $sorting = $this->getContext()->getRequestParam('sorting');
        
        if (!empty($sorting['field']) && !empty($sorting['direction']) && $sorting['field'] === $this->getName() && in_array(strtoupper($sorting['direction']), ['ASC', 'DESC'], true))
        {
            $this->getContext()->getDataProvider()->addOrder('ec_consent_uuid',strtoupper($sorting['direction']));
        }
    }
}