<?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\Premium;

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

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

    /**
     * @var Premium
     */
    protected $premium;

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

        parent::__construct(
            $context,
            $authSession,
            $jsHelper,
            $data,
            $secureRenderer
        );
    }

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

    /**
     * Get footer html
     *
     * @param AbstractElement $element
     * @return string
     */
    protected function _getFooterHtml($element)
    {
        $html = parent::_getFooterHtml($element);
        $html .= '<div class="wtai-custom-header" style="' . $this->getCustomHeaderStyling() . '">';
        $html .= '<span> ' . __('API access') . '</span>';
        $html .= '</div>';
        $html .= '<div class="wtai-custom-header-text">';
        $html .= sprintf('<p>%s</p>', __('WriteText.ai automatically creates integration'
            . ' credentials under <em>System > Extensions > Integrations</em> to maintain continuous '
            . 'communication with your webshop. These credentials enable background'
            . ' processing for bulk actions, allowing you to close your browser while'
            . ' operations continue and to handle up to 5000 products at once.'));
        $html .= sprintf('<p>%s</p>', __('If the integration credentials are deleted, WriteText.ai'
            . ' will regenerate them automatically to ensure an uninterrupted connection.'));
        $html .= '</div>';
        return $html;
    }

    /**
     * Get custom header styling
     *
     * @return string
     */
    private function getCustomHeaderStyling()
    {
        return "clear: both; color: #303030; cursor: pointer; display: block; "
            . "font-size: 1.7rem; font-weight: 600; letter-spacing: .025em; padding: 1.9rem 2.8rem 1.9rem 0;";
    }

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