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

namespace WriteTextAI\WriteTextAI\ViewModel;

use WriteTextAI\WriteTextAI\Helper\Data;
use WriteTextAI\WriteTextAI\Model\Api\CurlBuilder;

class Footer implements \Magento\Framework\View\Element\Block\ArgumentInterface
{
    /**
     * @var Data
     */
    protected $helper;

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

    /**
     * @var bool
     */
    protected $isLoggedIn;

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

    /**
     * Check if logged in
     *
     * @return bool
     */
    public function isLoggedIn()
    {
        if ($this->isLoggedIn) {
            return $this->isLoggedIn;
        }

        $accountToken = $this->helper->getAccountToken();
        $region = $this->helper->getRegion();
        
        /**
         * check if account token and region is set
         * then verify account token
         */
        try {
            if ($accountToken && $region) {
                if ($this->curlBuilder->getConnectToken($accountToken)) {
                    $this->isLoggedIn = true;
                    return true;
                }
            }
        } catch (\WriteTextAI\WriteTextAI\Exception\UnauthorizedException $ue) {
            return false;
        }

        return false;
    }
}
