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

declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Block\Adminhtml\Setup;

use Magento\Backend\Block\Template\Context;
use WriteTextAI\WriteTextAI\Helper\Data;
use WriteTextAI\WriteTextAI\Model\GenerateOptionsManager;
use WriteTextAI\WriteTextAI\Model\ApiManager;
use WriteTextAI\WriteTextAI\Model\SettingManager;
use WriteTextAI\WriteTextAI\Model\Config\Source\ProductAttributes;
use WriteTextAI\WriteTextAI\Helper\Categories\Fields as CategoryFields;

class Index extends \Magento\Backend\Block\Template
{
    /**
     * @var \WriteTextAI\WriteTextAI\Helper\Data
     */
    protected $helper;
    
    /**
     * @var \WriteTextAI\WriteTextAI\Model\GenerateOptionsManager
     */
    protected $generateOptionsManager;

    /**
     * @var bool
     */
    protected $isloggedIn = false;

    /**
     * @var array
     */
    protected $account = [];

    /**
     * @var \WriteTextAI\WriteTextAI\Model\ApiManager
     */
    protected $apiManager;

    /**
     * @var \WriteTextAI\WriteTextAI\Model\SettingManager
     */
    protected $settingManager;

    /**
     * @var \WriteTextAI\WriteTextAI\Helper\Categories\Fields
     */
    protected $categoryFields;

    /**
     * Constructor
     *
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \WriteTextAI\WriteTextAI\Helper\Data $helper
     * @param \WriteTextAI\WriteTextAI\Model\GenerateOptionsManager $generateOptionsManager
     * @param \WriteTextAI\WriteTextAI\Model\ApiManager $apiManager
     * @param \WriteTextAI\WriteTextAI\Model\SettingManager $settingManager
     * @param \WriteTextAI\WriteTextAI\Helper\Categories\Fields $categoryFields
     * @param array $data
     */
    public function __construct(
        Context $context,
        Data $helper,
        GenerateOptionsManager $generateOptionsManager,
        ApiManager $apiManager,
        SettingManager $settingManager,
        CategoryFields $categoryFields,
        array $data = []
    ) {
        $this->helper = $helper;
        $this->generateOptionsManager = $generateOptionsManager;
        $this->apiManager = $apiManager;
        $this->settingManager = $settingManager;
        $this->categoryFields = $categoryFields;
        parent::__construct($context, $data);
    }

    /**
     * Set is logged in
     *
     * @param bool $isloggedIn
     * @return void
     */
    public function setIsLoggedIn($isloggedIn)
    {
        $this->isloggedIn = $isloggedIn;
    }

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

    /**
     * Get rules
     *
     * @return array
     */
    public function getRules()
    {
        return $this->settingManager->getSettings('rules');
    }

    /**
     * Get disallowed combinations
     *
     * @return array
     */
    public function getDisallowedCombinations()
    {
        return $this->settingManager->getSettings('disallowedCombinations');
    }

    /**
     * Get login/register url
     *
     * @return string
     */
    public function getLoginRegisterUrl()
    {
        $region = $this->apiManager->getRegion();
        $params = [
            'redirect' => 'true',
            'callback_url' => $this->getUrl('wtai/setup/callback'),
            'platform' => 'Magento',
            'region' => $region,
            'verification_url' => $this->getBaseUrl()
        ];

        return $this->helper->getApiAuthUrl() . '?' . http_build_query($params);
    }

    /**
     * Get current step
     *
     * @return int
     */
    public function getCurrentStep()
    {
        $step = 1;

        $conditions = [
            $this->isLoggedIn(),
            $this->isDataMapped(),
            //$this->helper->isFinalStepDone()
        ];

        foreach ($conditions as $condition) {
            if ($condition) {
                $step++;
            } else {
                break;
            }
        }

        return $step;
    }

    /**
     * Get step css class
     *
     * @param int $step
     *
     * @return string
     */
    public function getStepClass($step)
    {
        $class = '';
        $currentStep = $this->getCurrentStep();
        
        switch ($step) {
            case $step > $currentStep:
                break;
                
            case $step == $currentStep:
                $class = 'wtai-active';
                break;

            case $step < $currentStep:
                $class = 'wtai-completed';
                break;
        }

        return $class;
    }

    /**
     * Get data mapping fields
     *
     * @return array
     */
    public function getDataMappingFields()
    {
        return $this->helper->getDataMappingFields();
    }

    /**
     * Get category data mapping fields
     *
     * @return array
     */
    public function getCategoryDataMappingFields()
    {
        return $this->helper->getCategoryDataMappingFields('category_description');
    }

    /**
     * Get data mapping attributes selection
     *
     * @return array
     */
    public function getDataMappingAttributesSelection()
    {
        return $this->helper->getTextTypeAttributes();
    }

    /**
     * Get data mapping attributes selection
     *
     * @return array
     */
    public function getCategoryDataMappingAttributesSelection()
    {
        return $this->helper->getCateoryTextTypeAttributes();
    }

    /**
     * Get save url
     *
     * @return string
     */
    public function getSaveUrl()
    {
        return $this->getUrl('wtai/setup/save');
    }

    /**
     * Get mapped fields value
     *
     * @return array
     */
    public function getMappedAttributes()
    {
        return $this->helper->getMappingSettings();
    }

    /**
     * Get category mapped fields value
     *
     * @return array
     */
    public function getCategoryMappedAttributes()
    {
        return $this->categoryFields->getMappingSettings();
    }

    /**
     * Get default mapping
     *
     * @return array
     */
    public function getDefaultMapping()
    {
        return [
            'page_title' => 'meta_title',
            'page_description' => 'meta_description',
            'product_description' => 'description',
            'short_product_description' => 'short_description',
            'open_graph' => ''
        ];
    }

    /**
     * Get default mapping
     *
     * @return array
     */
    public function getCategoryDefaultMapping()
    {
        return $this->categoryFields->getDefaultMapping();
    }

    /**
     * Check if at least 1 data is mapped in step 2
     *
     * @return boolean
     */
    public function isDataMapped()
    {
        return $this->helper->isDataMapped();
    }

    /**
     * Get tones
     *
     * @return array
     */
    public function getTones()
    {
        return $this->generateOptionsManager->getOptions('tones');
    }

    /**
     * Get styles
     *
     * @return array
     */
    public function getStyles()
    {
        return $this->generateOptionsManager->getOptions('styles');
    }

    /**
     * Get audience
     *
     * @return array
     */
    public function getAudience()
    {
        return $this->generateOptionsManager->getOptions('audience');
    }

    /**
     * Get attributes
     *
     * @return array
     */
    public function getAttributes()
    {
        $attributes = $this->generateOptionsManager->getOptions('attributes');

        /**
         * Customization in data since we need to move product research data under the thumbnail
         */
        foreach ($attributes as $key => $attribute) {
            if ($attribute['value'] == ProductAttributes::PRODUCT_RESEARCH_DATA_ATTRIBUTE_CODE) {
                unset($attributes[$key]);
                break;
            }
        }
        
        $productResearchData = [
            'id' => ProductAttributes::PRODUCT_RESEARCH_DATA_ATTRIBUTE_CODE,
            'value' => ProductAttributes::PRODUCT_RESEARCH_DATA_ATTRIBUTE_CODE,
            'label' => __('Product Research'),
            'default' => true
        ];
        array_splice($attributes, 2, 0, [$productResearchData]);
        /**
         * End of customization
         */
        return $attributes;
    }

    /**
     * Get current url
     *
     * @return string
     */
    public function getCurrentUrl()
    {
        return $this->getBaseUrl();
    }

    /**
     * Get description min
     *
     * @return string
     */
    public function getDescriptionMin()
    {
        return $this->helper->getDescriptionSettings('min');
    }

    /**
     * Get description max
     *
     * @return string
     */
    public function getDescriptionMax()
    {
        return $this->helper->getDescriptionSettings('max');
    }

    /**
     * Get excerpt min
     *
     * @return string
     */
    public function getExcerptMin()
    {
        return $this->helper->getExcerptSettings('min');
    }

    /**
     * Get excerpt max
     *
     * @return string
     */
    public function getExcerptMax()
    {
        return $this->helper->getExcerptSettings('max');
    }

    /**
     * Get category description min
     *
     * @return string
     */
    public function getCategoryDescriptionMin()
    {
        return $this->helper->getCategoryDescriptionSettings('min');
    }

    /**
     * Get category description max
     *
     * @return string
     */
    public function getCategoryDescriptionMax()
    {
        return $this->helper->getCategoryDescriptionSettings('max');
    }

    /**
     * Get current host
     *
     * @return string
     */
    public function getCurrentHost()
    {
        $url = str_replace(
            ['http://', 'https://'],
            '',
            $this->getCurrentUrl()
        );

        return rtrim($url, '/');
    }

    /**
     * Check if custom open graph is enabled
     *
     * @return bool
     */
    public function getCustomOpenGraph()
    {
        return $this->helper->getCustomOpenGraph();
    }
    
    /**
     * Show freemium banner
     *
     * @return bool
     */
    public function showFreemiumBanner()
    {
        if (!empty($this->account)) {
            $account = $this->account;
        } else {
            $account = $this->apiManager->getAccount();
        }

        return $account['account']['company']['eligibleForFreePremiumCredits'] ?? false;
    }

    /**
     * Get freemium credits
     *
     * @return int
     */
    public function getFreemiumCredits()
    {
        if (!empty($this->account)) {
            $account = $this->account;
        } else {
            $account = $this->apiManager->getAccount();
        }

        return $account['account']['company']['freePremiumCredits'] ?? 110;
    }
}
