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

namespace WriteTextAI\WriteTextAI\Plugin\Backend\Model\Menu;

use Magento\Backend\Model\Menu\Builder as MagentoBuilder;
use Magento\Backend\Model\Menu;
use Magento\Backend\Model\Menu\ItemFactory;
use WriteTextAI\WriteTextAI\Helper\Data;
use WriteTextAI\WriteTextAI\Model\Api\CurlBuilder;
use WriteTextAI\WriteTextAI\ViewModel\Footer;

class Builder
{
    /**
     * @var ItemFactory
     */
    protected $menuItemFactory;

    /**
     * @var Data
     */
    protected $helper;

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

    /**
     * @var Footer
     */
    protected $footer;

    /**
     * Constructor.
     *
     * @param ItemFactory $menuItemFactory
     * @param Data $helper
     * @param CurlBuilder $curlBuilder
     * @param Footer $footer
     */
    public function __construct(
        ItemFactory $menuItemFactory,
        Data $helper,
        CurlBuilder $curlBuilder,
        Footer $footer
    ) {
        $this->menuItemFactory = $menuItemFactory;
        $this->helper = $helper;
        $this->curlBuilder = $curlBuilder;
        $this->footer = $footer;
    }

    /**
     * Add menu item
     *
     * @param MagentoBuilder $subject
     * @param Menu $menu
     * @param mixed $result
     * @return mixed
     */
    public function afterGetResult(
        MagentoBuilder $subject,
        Menu $menu,
        $result
    ) {
        $item = $this->menuItemFactory->create([
            'data' => [
                'id' => 'WriteTextAI_WriteTextAI::settings',
                'title' => 'Settings',
                'module' => 'WriteTextAI_WriteTextAI',
                'resource' => 'WriteTextAI_WriteTextAI::modify_defaults',
                'action' => 'wtai/settings/index',
            ]
        ]);

        if ($this->isSetupComplete()) {
            $menu->add($item, 'WriteTextAI_WriteTextAI::menu', 20);
        }

        return $result;
    }

    /**
     * Check if setup is complete
     *
     * @return bool
     */
    private function isSetupComplete()
    {
        try {
            if ($this->footer->isLoggedIn() &&
                $this->helper->isDataMapped() &&
                //$this->helper->isFinalStepDone() &&
                $this->helper->isSetupFinalized()
            ) {
                return true;
            }

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