<?php
/**
 * @module  Autogedal_SeoCanonical
 * @author  Autogedal
 * @licence OSL 3.0
 */

namespace Autogedal\SeoCanonical\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Store\Model\ScopeInterface;

class Config extends AbstractHelper
{
    const XML_PATH_ENABLED = 'seo_canonical/seo_canonical/enabled';
    const XML_PATH_CATEGORY_CONFIG = 'seo_canonical/seo_canonical/category_config';

    /**
     * @var Json
     */
    protected $jsonSerializer;

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

    /**
     * Check if module is enabled
     *
     * @param int|null $storeId
     * @return bool
     */
    public function isEnabled($storeId = null)
    {
        return (bool)$this->scopeConfig->getValue(
            self::XML_PATH_ENABLED
        );
    }

    /**
     * Get category configurations
     *
     * @param int|null $storeId
     * @return array
     */
    public function getCategoryConfigurations($storeId = null)
    {
        $configValue = $this->scopeConfig->getValue(
            self::XML_PATH_CATEGORY_CONFIG,
            ScopeInterface::SCOPE_STORE,
            $storeId
        );

        if (empty($configValue)) {
            return [];
        }

        $configArray = $this->jsonSerializer->unserialize($configValue);

        if (!is_array($configArray)) {
            return [];
        }

        $configurations = [];
        foreach ($configArray as $row) {
            if (!isset($row['category_id']) || !isset($row['marca_attribute'])
                || !isset($row['model_attribute']) || !isset($row['caroserie_attribute'])) {
                continue;
            }

            $configurations[] = [
                'category_id' => (int)$row['category_id'],
                'marca_attribute_id' => (int)$row['marca_attribute'],
                'model_attribute_id' => (int)$row['model_attribute'],
                'caroserie_attribute_id' => (int)$row['caroserie_attribute']
            ];
        }

        return $configurations;
    }
}
