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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Grid;

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

class GetPingStatus extends Action
{
    /**
     * @var ApiManager
     */
    protected $apiManager;

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

    /**
     * Execute
     *
     * @return Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);

        $pingData = $this->pingApi();
        $message = sprintf("<p>%s</p>",__("We’re having trouble connecting to your webshop right now."));
        $message .= "<ul class='wtai-padding-left'>";
        $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'>";
        $message .= sprintf("<li>%s</li>",__("WriteText.ai IPs: {{WTA_IP_LIST}}"));
        $message .= sprintf("<li>%s</li>",__("User agent: WriteTextAI"));
        $message .= "</ul>";
        if ($pingData['success'] === true) {
            $response->setData([
                'success' => true,
                'pingData' => $pingData,
                'message' => __('Success ping')
            ]);
        } else {
            $implodeIpList = "";
            if (isset($pingData['ipWhiteList']) && count($pingData['ipWhiteList']) > 0) {
                $implodeIpList = implode(", ", $pingData['ipWhiteList']);
            }
            $message = str_replace("{{WTA_IP_LIST}}", $implodeIpList, $message);
            $response->setData([
                'success' => false,
                'pingData' => $pingData,
                'message' => $message
            ]);
        }

        return $response;
    }

    /**
     * Ping API
     *
     * @return array
     */
    public function pingApi()
    {
        try {
            return $this->apiManager->pingApi();
        } catch (\WriteTextAI\WriteTextAI\Exception\UnauthorizedException $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

}
