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

namespace WriteTextAI\WriteTextAI\Ui\Component\MassAction;

use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\MassAction\Filter;

/**
 * Custom Filter component that handles JSON input in addition to form data
 */
class JsonFilter extends Filter
{
    /**
     * @var bool
     */
    private $jsonParsed = false;

    /**
     * @param UiComponentFactory $factory
     * @param RequestInterface $request
     * @param FilterBuilder $filterBuilder
     */
    public function __construct(
        UiComponentFactory $factory,
        RequestInterface $request,
        FilterBuilder $filterBuilder
    ) {
        parent::__construct($factory, $request, $filterBuilder);
        $this->parseJsonIfNeeded();
    }

    /**
     * Parse JSON data from request if content type is JSON
     *
     * @return void
     */
    private function parseJsonIfNeeded()
    {
        if ($this->jsonParsed) {
            return;
        }

        $contentType = $this->request->getHeader('Content-Type');
        
        if ($contentType && strpos($contentType, 'application/json') !== false) {
            $content = $this->request->getContent();
            
            if ($content) {
                /** Remove any parameters appended after JSON by finding last closing brace */
                $lastBrace = strrpos($content, '}');
                if ($lastBrace !== false && $lastBrace < strlen($content) - 1) {
                    /** Check if there's content after the last brace (query params) */
                    $afterBrace = substr($content, $lastBrace + 1);
                    if (strpos($afterBrace, '&') === 0 || strpos($afterBrace, '?') === 0) {
                        $content = substr($content, 0, $lastBrace + 1);
                    }
                }
                
                $jsonData = json_decode($content, true);
                
                if (json_last_error() === JSON_ERROR_NONE && is_array($jsonData)) {
                    /** Set JSON data as POST values for backward compatibility */
                    foreach ($jsonData as $key => $value) {
                        $this->request->setPostValue($key, $value);
                    }
                }
            }
        }

        $this->jsonParsed = true;
    }
}
