<?php

declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Template;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use WriteTextAI\WriteTextAI\Model\ApiManager;

class HasImage extends Action
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::generate';

    /**
     * @var ApiManager
     */
    private $apiManager;

    /**
     * Constructor
     *
     * @param Context $context
     * @param ApiManager $apiManager
     */
    public function __construct(
        Context $context,
        ApiManager $apiManager
    ) {
        parent::__construct($context);
        $this->apiManager = $apiManager;
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);

        try {
            $templateIds = $this->getRequest()->getParam('template_ids');
            if (!is_array($templateIds)) {
                $templateIds = [];
            }

            $templateIds = array_values(array_filter(array_map('strval', $templateIds), static function ($v) {
                return $v !== '';
            }));

            $data = [];
            foreach ($templateIds as $templateId) {
                $hasImage = false;
                try {
                    $apiResponse = $this->apiManager->getTempatesHasImage($templateId);
                    $hasImage = $this->extractHasGeneratedImageBlocks($apiResponse);
                } catch (\Exception $e) {
                    $hasImage = false;
                }

                $data[$templateId] = $hasImage;
            }

            $result->setData([
                'success' => true,
                'data' => $data
            ]);

            return $result;
        } catch (\Exception $e) {
            $message = $e->getMessage();
            if (!$message) {
                $message = (string) __('A system error has occurred. Please try again.');
            }

            $result->setData([
                'success' => false,
                'message' => $message
            ]);

            return $result;
        }
    }

    /**
     * Extract hasGeneratedImageBlocks from a potentially nested API response.
     *
     * @param mixed $apiResponse
     */
    private function extractHasGeneratedImageBlocks($apiResponse): bool
    {
        if (!is_array($apiResponse)) {
            return false;
        }

        if (array_key_exists('hasGeneratedImageBlocks', $apiResponse)) {
            return (bool) $apiResponse['hasGeneratedImageBlocks'];
        }

        foreach ($apiResponse as $value) {
            if (is_array($value)) {
                $found = $this->extractHasGeneratedImageBlocks($value);
                if ($found) {
                    return true;
                }
            }
        }

        return false;
    }
}
