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

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

use Magento\Config\Block\System\Config\Form as MagentoForm;
use WriteTextAI\WriteTextAI\ViewModel\Premium;
use WriteTextAI\WriteTextAI\ViewModel\Popups;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Registry;
use Magento\Framework\Data\FormFactory;
use Magento\Config\Model\Config\Factory;
use Magento\Config\Model\Config\Structure;
use Magento\Config\Block\System\Config\Form\Fieldset\Factory as FieldsetFactory;
use Magento\Config\Block\System\Config\Form\Field\Factory as FieldFactory;
use Magento\Config\Model\Config\Reader\Source\Deployed\SettingChecker;
use WriteTextAI\WriteTextAI\Model\ApiManager;
use Magento\Framework\Message\ManagerInterface;

class Form extends MagentoForm
{
    /**
     * @var Premium
     */
    protected $premium;

    /**
     * @var Popups
     */
    protected $popups;

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

    /**
     * @var ManagerInterface
     */
    protected $messageManager;

    /**
     * @param Premium $premium
     * @param Popups $popups
     * @param Context $context
     * @param Registry $registry
     * @param FormFactory $formFactory
     * @param Factory $configFactory
     * @param Structure $configStructure
     * @param FieldsetFactory $fieldsetFactory
     * @param FieldFactory $fieldFactory
     * @param array $data
     * @param SettingChecker $settingChecker
     * @param ApiManager $apiManager
     * @param ManagerInterface $messageManager
     */
    public function __construct(
        Premium $premium,
        Popups $popups,
        ApiManager $apiManager,
        ManagerInterface $messageManager,
        Context $context,
        Registry $registry,
        FormFactory $formFactory,
        Factory $configFactory,
        Structure $configStructure,
        FieldsetFactory $fieldsetFactory,
        FieldFactory $fieldFactory,
        array $data = [],
        ?SettingChecker $settingChecker = null
    ) {
        $this->premium = $premium;
        $this->popups = $popups;
        $this->apiManager = $apiManager;
        $this->messageManager = $messageManager;
        parent::__construct(
            $context,
            $registry,
            $formFactory,
            $configFactory,
            $configStructure,
            $fieldsetFactory,
            $fieldFactory,
            $data,
            $settingChecker
        );
    }

    /**
     * @inheritdoc
     */
    public function _toHtml()
    {
        if (!$this->premium->getHasProAccess()
            && $this->premium->getMembershipType() === Premium::MEMBERSHIP_TYPE_FREE_TRIAL) {
            $block = $this->_layout->createBlock(\WriteTextAI\WriteTextAI\Block\Adminhtml\Popups\EndTrial::class);
            $block->addData([
                'premium' => $this->premium,
                'popups' => $this->popups
            ]);
            $html = $block->toHtml();
            return $html;
        }

        $html = parent::_toHtml();
        $pingData = $this->apiManager->pingApi();
        if ($pingData['success'] === false) {
            
            $message = '<div class="messages">';
            $message .= '<div class="message message-error error">';
            $message .= '<div class="message-container">';
            $message .= sprintf("<p>%s</p><br>",__("We’re having trouble connecting to your webshop right now."));
            $message .= "<ul class='wtai-padding-left' style='padding-left: 20px'>";
            $message .= sprintf(
                "<li>%s</li>",
                __("Go to System > Extensions > Integrations, open writetextai_integration,"
                    ." and verify that WriteText AI Rest API is selected.")
            );
            $message .= sprintf(
                "<li>%s</li>",
                __("Check for any module or extension that may have disabled the REST API.")
            );
            $message .= sprintf(
                "<li>%s</li>",
                __("Verify that there are no firewall or security settings blocking external API requests.")
            );
            $message .= sprintf(
                "<li>%s</li>",
                __("Contact your hosting provider, and verify if IP restrictions are enabled.")
            );
            $message .= "</ul>";
            $message .= sprintf("<p>%s</p>",__("If needed, whitelist the following:"));
            $message .= "<ul class='wtai-padding-left' style='padding-left: 20px'>";
            $message .= sprintf("<li>%s</li>",__("WriteText.ai IPs: {{WTA_IP_LIST}}"));
            $message .= sprintf("<li>%s</li>",__("User agent: WriteTextAI"));
            $message .= "</ul>";
             if (isset($pingData['ipWhiteList']) && count($pingData['ipWhiteList']) > 0) {
                $implodeIpList = implode(", ", $pingData['ipWhiteList']);
                $message = str_replace("{{WTA_IP_LIST}}", $implodeIpList, $message);
            }
            $message .= '</div>';
            $message .= '</div>';
            $message .= '</div>';
            $html = $message." ".$html;
        }

        $html .= '<script type="text/javascript">
            require([
                "jquery",
                "jquery/ui"
            ], function ($) {
                $(document).ready(function () {
                    $("#messages .messages .message").each(function () {
                        var $this = $(this);
                        var $span = $("<span class=\"action-close\"></span>");

                        $span.on("click", function () {
                            $this.fadeOut();
                        });
                        
                        $this.append($span);
                    });
                });
            });
        </script>';
        
        return $html;
    }
}
