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

namespace WriteTextAI\WriteTextAI\Block\Adminhtml\System\Config\Form;

use Magento\Config\Block\System\Config\Form\Fieldset as MagentoFieldset;
use Magento\Backend\Block\Context;
use Magento\Backend\Model\Auth\Session;
use Magento\Framework\View\Helper\Js as JsHelper;
use Magento\Framework\View\Helper\SecureHtmlRenderer;
use Magento\Framework\Data\Form\Element\AbstractElement;
use WriteTextAI\WriteTextAI\Helper\Data as Helper;
use WriteTextAI\WriteTextAI\Model\Api\CurlBuilder;
use WriteTextAI\WriteTextAI\ViewModel\TemplateSettings;

class FieldsetLength extends MagentoFieldset
{
    /**
     * @var Helper
     */
    protected $helper;

    /**
     * @var CurlBuilder
     */
    protected $curlBuilder;

    /**
     * @var TemplateSettings
     */
    protected $templateSettings;

    /**
     * Constructor
     *
     * @param Context $context
     * @param Session $authSession
     * @param JsHelper $jsHelper
     * @param Helper $helper
     * @param CurlBuilder $curlBuilder
     * @param TemplateSettings $templateSettings
     * @param array $data
     * @param SecureHtmlRenderer|null $secureRenderer
     */
    public function __construct(
        Context $context,
        Session $authSession,
        JsHelper $jsHelper,
        Helper $helper,
        CurlBuilder $curlBuilder,
        TemplateSettings $templateSettings,
        array $data = [],
        ?SecureHtmlRenderer $secureRenderer = null
    ) {
        $this->helper = $helper;
        $this->curlBuilder = $curlBuilder;
        $this->templateSettings = $templateSettings;
        parent::__construct(
            $context,
            $authSession,
            $jsHelper,
            $data,
            $secureRenderer
        );
    }

    /**
     * Get header comment html
     *
     * @param AbstractElement $element
     * @return string
     */
    protected function _getHeaderCommentHtml($element)
    {
        $equivalentField = [
            'description' => 'product_description',
            'excerpt' => 'short_product_description',
            'category_description' => 'category_description',

        ];
        $fieldData = $element->getData();
        $fieldId = isset($fieldData['original_data']['id']) ? $fieldData['original_data']['id'] : null;
        if (!$fieldId) {
            return parent::_getHeaderCommentHtml($element);
        }
        $currentTemplateSettings = $this->templateSettings->getCurrentTemplateSettings($equivalentField[$fieldId]);
        
        $html = parent::_getHeaderCommentHtml($element);
        $html .= '<div class="messages">';
        $html .= '<div class="message message-warning warning">';
        $html .= '<div data-ui-id="messages-message-warning">';
        $html .= __('Target length is not considered when you use a template.'
        . ' To set up and assign templates to this webshop,'
        . ' go to your <a href="https://platform.writetext.ai/webshops"'
        . ' target="_blank">platform.writetext.ai</a> account.');
        $html .= '</div>';
        $html .= '</div>';
        $html .= '</div>';
        return $html;
    }

    /**
     * Render fieldset html
     *
     * @param AbstractElement $element
     * @return string
     */
    public function render(AbstractElement $element)
    {
        $html = '';

        if ($element->getId() === 'writetextai_settings_general') {
            $setupUrl = $this->getUrl('wtai/setup/index');
            $importantText = sprintf('<strong>%s </strong>', __("Important:"));
            $setupText = sprintf(
                __("Please complete the <a href=\"%s\">setup</a> process to use this extension."),
                $setupUrl
            );
            $html = '<p class="wtai-config">' . $importantText . '<span>' . $setupText . '</span></p>';
        }

        if (!$this->isSetupComplete()) {
            return $html;
        }

        return parent::render($element);
    }

    /**
     * Check if setup is complete
     *
     * @return bool
     */
    private function isSetupComplete()
    {
        try {
            $accountToken = $this->helper->getAccountToken();

            if ($accountToken &&
                $this->curlBuilder->getConnectToken($accountToken) &&
                $this->helper->getRegion() &&
                $this->helper->isDataMapped() &&
                //$this->helper->isFinalStepDone() &&
                $this->helper->isSetupFinalized()
            ) {
                return true;
            }

            return false;
        } catch (\WriteTextAI\WriteTextAI\Exception\UnauthorizedException $e) {
            return false;
        }
    }
}
