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

namespace WriteTextAI\WriteTextAI\ViewModel;

use WriteTextAI\WriteTextAI\Model\ApiManager;

use WriteTextAI\WriteTextAI\Model\OptionSource\Filter\Fields;
use Magento\Framework\App\CacheInterface;

class TemplateSettings implements \Magento\Framework\View\Element\Block\ArgumentInterface
{

    public const TEMPLATE_SETTINGS_CACHE_KEY = 'writetext_ai_template_settings';

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

    /**
     * @var CacheInterface
     */
    protected $cache;

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

    /**
     * Constructor
     *
     * @param ApiManager $apiManager
     */
    public function __construct(
        ApiManager $apiManager,
        CacheInterface $cache
    ) {
        $this->apiManager = $apiManager;
        $this->cache = $cache;
    }

    /**
     * Get current template settings
     *
     * @param string $specificField
     *
     * @return array
     */
    public function getCurrentTemplateSettings($specificField = null)
    {
        $fieldConfig = [
            'page_title' => Fields::PAGE_TITLE,
            'page_description' => Fields::PAGE_DESCRIPTION,
            'product_description' => Fields::PRODUCT_DESCRIPTION,
            'short_product_description' => Fields::EXCERPT,
            'open_graph' => Fields::OPEN_GRAPH,
            'category_page_title' => Fields::CATEGORY_PAGE_TITLE,
            'category_page_description' => Fields::CATEGORY_PAGE_DESCRIPTION,
            'category_description' => Fields::CATEGORY_DESCRIPTION
        ];

        $templateSettings = $this->cache->load(self::TEMPLATE_SETTINGS_CACHE_KEY);
        
        if (!$templateSettings) {
            $templateSettings = $this->apiManager->getCurrentTemplateSettings();
            $templateSettings = json_encode($templateSettings);
            $this->cache->save($templateSettings, self::TEMPLATE_SETTINGS_CACHE_KEY);
        }
        $templateSettings = json_decode($templateSettings, true);

        if ($templateSettings) {
            if ($specificField) {
                if (isset($templateSettings[$fieldConfig[$specificField]])) {
                    return $templateSettings[$fieldConfig[$specificField]]['selections'];
                }
            } else {
                return $templateSettings;
            }
        }

        return [];
    }
}
