<?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\Helper\CronStatus;

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

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

    /**
     * @var CronStatus
     */
    protected $cronStatus;

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

    /**
     * Get header comment html
     *
     * @param AbstractElement $element
     * @return string
     */
    protected function _getHeaderCommentHtml($element)
    {
        if ($element->getId() === 'writetextai_settings_autotransfer') {
            if (!$this->cronStatus->isCronRunning(CronStatus::DEFAULT_CRON_MINUTES_CHECK)) {
                $html = parent::_getHeaderCommentHtml($element);
                $html .= '<div class="wtai-disabled-cron-job-message">'
                    . '<span class="wtai-icon-info"></span>'
                    . '<span class="wtai-disabled-cron-job-message-text">'
                    . __('Website cron jobs have been disabled.'
                        . ' This setting requires a cron job to function properly.'
                        . ' Please enable it to ensure proper operation.'
                        . ' You may need to contact your hosting provider or developer regarding this.')
                    . '</span>'
                    . '</div>';
                return $html;
            }
        }
        return parent::_getHeaderCommentHtml($element);
    }

    /**
     * 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;
        }
    }
}
