<?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 FacebookCategory extends Capi
{
    /**
     * Handle request
     */
    public function handle() : array
    {
        $payload = $this->getRequest()->getParam('payload');
        
        if ($payload)
        {
            /**
             * Conetnt IDs map 
             * 
             * @var array $content_ids
             */
            $content_ids = [];
            
            /**
             * Category 
             * 
             * @var string $category
             */
            $category = '';

            /**
             * Default value is 0
             */
            $value = 0;

            if (isset($payload['ecommerce']['items']))
            {
                if (is_array($payload['ecommerce']['items']))
                {
                    foreach ((array) $payload['ecommerce']['items'] as $entity)
                    {
                        $content_ids[] = $entity['remarketingFacebookId'];
                        
                        /**
                         * Set category
                         */
                        if (isset($entity['item_category']))
                        {
                            $category = (string) $entity['item_category'];
                        }
                        elseif (isset($entity['category']))
                        {
                            $category = (string) $entity['category'];
                        }
                        else 
                        {
                            $category = __('Unassigned');
                        }

                        $value += (float) $entity['price'];
                    }
                }
                else 
                {
                    $this->logger->log('CAPI category tracking failed. Payload is incomplete:' . print_r($payload, true));
                }
            }

            if ($content_ids)
            {
                return $this->helper->getFacebookConversionsApi()->trackViewCategory($content_ids, $payload['ecommerce']['currency'], $category, $value);
            }
        }
        
        return 
        [
            'success' => false
        ];
    }
}