<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Plugin\Component;

use Magento\Framework\View\LayoutInterface;

class MassAction
{
    private const MASS_ACTION_NAME = 'listing_massaction';
    
    private const ACTION_TYPES = [
        'generate' => [
            'urls' => [
                'wtai/grid/massGenerate',
                'wtai/categoriesgrid/massGenerate'
            ],
            'block' => \WriteTextAI\WriteTextAI\Block\Adminhtml\Grid\Prompt::class,
            'categoryBlock' => \WriteTextAI\WriteTextAI\Block\Adminhtml\CategoriesGrid\Prompt::class,
            'buttonBlock' => \WriteTextAI\WriteTextAI\Block\Adminhtml\Grid\GenerateButton::class,
            'childBlock' => \WriteTextAI\WriteTextAI\Block\Adminhtml\Grid\ProBadge::class
        ],
        'transfer' => [
            'urls' => [
                'wtai/grid/massTransfer',
                'wtai/categoriesgrid/massTransfer'
            ],
            'block' => \WriteTextAI\WriteTextAI\Block\Adminhtml\Grid\TransferPrompt::class,
            'categoryBlock' => \WriteTextAI\WriteTextAI\Block\Adminhtml\CategoriesGrid\TransferPrompt::class,
            'childBlock' => \WriteTextAI\WriteTextAI\Block\Adminhtml\Grid\ProBadge::class
        ],
        'keyword_analysis' => [
            'urls' => [
                'wtai/grid/massKeywordAnalysis',
                'wtai/categoriesgrid/massKeywordAnalysis'
            ],
            'block' => \WriteTextAI\WriteTextAI\Block\Adminhtml\Grid\KeywordAnalysisPrompt::class,
            'categoryBlock' => \WriteTextAI\WriteTextAI\Block\Adminhtml\CategoriesGrid\KeywordAnalysisPrompt::class
        ],
        'full_automation' => [
            'urls' => [
                'wtai/grid/massFullAutomation',
                'wtai/categoriesgrid/massFullAutomation'
            ],
            'block' => \WriteTextAI\WriteTextAI\Block\Adminhtml\Grid\FullAutomationPrompt::class,
            'categoryBlock' => \WriteTextAI\WriteTextAI\Block\Adminhtml\CategoriesGrid\FullAutomationPrompt::class,
            'childBlock' => \WriteTextAI\WriteTextAI\Block\Adminhtml\Grid\ProBadge::class
        ]
    ];

    /**
     * @var LayoutInterface
     */
    protected $layout;

    /**
     * Constructor
     *
     * @param LayoutInterface $layout
     */
    public function __construct(
        LayoutInterface $layout
    ) {
        $this->layout = $layout;
    }

    /**
     * Modify mass action popup content
     *
     * @param \Magento\Ui\Component\MassAction $subject
     * @param string $key
     * @param array $value
     * @return array
     */
    public function beforeSetData(
        \Magento\Ui\Component\MassAction $subject,
        string $key,
        array $value
    ): ?array {
        if ($key !== 'config' ||
            $subject->getName() !== self::MASS_ACTION_NAME ||
            !isset($value['actions'])
        ) {
            return null;
        }

        foreach ($value['actions'] as &$action) {
            $actionType = $action['type'] ?? '';
            $urlsToMatch = self::ACTION_TYPES[$actionType]['urls'] ?? [];
            $matchesAnyUrl = false;
            foreach ($urlsToMatch as $urlToMatch) {
                if (stripos($action['url'], $urlToMatch) !== false) {
                    $matchesAnyUrl = true;
                    break;
                }
            }

            if (!isset(self::ACTION_TYPES[$actionType]) ||
                !isset($action['confirm']['message']) ||
                !$matchesAnyUrl
            ) {
                continue;
            }

            $blockType = 'block';
            if (stripos($action['url'], 'wtai/categoriesgrid/') !== false
                && isset(self::ACTION_TYPES[$actionType]['categoryBlock'])
            ) {
                $action['confirm']['message'] = $this->createBlockContent(
                    $action,
                    'categoryBlock',
                    true
                );
            } else {
                $action['confirm']['message'] = $this->createBlockContent(
                    $action,
                    'block',
                    true
                );
            }

            if ($actionType === 'generate' && isset(self::ACTION_TYPES[$actionType]['buttonBlock'])) {
                $action['confirm']['button'] = $this->createBlockContent(
                    $action,
                    'buttonBlock'
                );
            }

            if ($actionType === 'full_automation' && isset(self::ACTION_TYPES[$actionType]['buttonBlock'])) {
                $action['confirm']['button'] = $this->createBlockContent(
                    $action,
                    'buttonBlock'
                );
            }
        }

        return [$key, $value];
    }

    /**
     * Create block content
     *
     * @param array $action
     * @param string $blockType
     * @param bool $hasChildBlock
     * @return string
     */
    private function createBlockContent(array $action, string $blockType, $hasChildBlock = false): string
    {
        $block = $this->layout->createBlock(self::ACTION_TYPES[$action['type']][$blockType]);

        if ($blockType === 'categoryBlock') {
            $block->setData('entity_type', 'category');
        }
        
        if ($hasChildBlock && isset(self::ACTION_TYPES[$action['type']]['childBlock'])) {
            $childBlock = $this->layout->createBlock(self::ACTION_TYPES[$action['type']]['childBlock']);
            $block->setChild('wtai.pro.badge.' . $action['type'], $childBlock);
        }
        
        return $block->toHtml();
    }
}
