<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_Faqs
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */

namespace Mageplaza\Faqs\Model;

use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\DataObject;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Magento\Store\Model\Store;
use Mageplaza\Faqs\Helper\Data;
use Mageplaza\Faqs\Model\ResourceModel\Article\Collection;
use Mageplaza\Faqs\Model\ResourceModel\Article\CollectionFactory;
use Mageplaza\Faqs\Model\ResourceModel\Tag as TagResourceModel;
use Mageplaza\Faqs\Model\ResourceModel\Tag\CollectionFactory as TagCollectionFactory;

/**
 * @method Tag setName($name)
 * @method Tag setDescription($description)
 * @method Tag setEnabled($enabled)
 * @method mixed getName()
 * @method mixed getDescription()
 * @method mixed getEnabled()
 * @method Tag setCreatedAt(string $createdAt)
 * @method string getCreatedAt()
 * @method Tag setUpdatedAt(string $updatedAt)
 * @method string getUpdatedAt()
 * @method Tag setArticlesIds(array $data)
 * @method Tag setIsChangedArticleList(bool $flag)
 * @method Tag setIsArticleGrid(bool $flag)
 * @method Tag setAffectedArticleIds(array $ids)
 * @method bool getIsArticleGrid()
 * @method array getArticlesIds()
 */
class Tag extends AbstractModel
{
    /**
     * Cache tag
     *
     * @var string
     */
    const CACHE_TAG = 'mageplaza_faqs_tag';

    /**
     * Cache tag
     *
     * @var string
     */
    protected $_cacheTag = 'mageplaza_faqs_tag';

    /**
     * Event prefix
     *
     * @var string
     */
    protected $_eventPrefix = 'mageplaza_faqs_tag';

    /**
     * Article Collection
     *
     * @var Collection
     */
    public $articleCollection;

    /**
     * Article Collection Factory
     *
     * @var CollectionFactory
     */
    public $articleCollectionFactory;

    /**
     * @var TagCollectionFactory
     */
    public $tagCollectionFactory;

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

    /**
     * Tag constructor.
     *
     * @param Context $context
     * @param Registry $registry
     * @param CollectionFactory $articleCollectionFactory
     * @param TagCollectionFactory $tagCollectionFactory
     * @param Data $helperData
     * @param AbstractResource|null $resource
     * @param AbstractDb|null $resourceCollection
     * @param array $data
     */
    public function __construct(
        Context $context,
        Registry $registry,
        CollectionFactory $articleCollectionFactory,
        TagCollectionFactory $tagCollectionFactory,
        Data $helperData,
        AbstractResource $resource = null,
        AbstractDb $resourceCollection = null,
        array $data = []
    ) {
        $this->articleCollectionFactory = $articleCollectionFactory;
        $this->tagCollectionFactory     = $tagCollectionFactory;
        $this->helperData               = $helperData;

        parent::__construct($context, $registry, $resource, $resourceCollection, $data);
    }

    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init(TagResourceModel::class);
    }

    /**
     * Get identities
     *
     * @return array
     */
    public function getIdentities()
    {
        return [self::CACHE_TAG . '_' . $this->getId()];
    }

    /**
     * @param string $value
     * @param string $storeId
     *
     * @return DataObject
     */
    public function loadByStoreIds($value, $storeId)
    {
        $collections = $this->getCollection()
            ->addFieldToFilter('url_key', ['eq' => $value])
            ->addFieldToFilter('store_ids', ['finset' => $storeId]);

        if (!$collections->getSize()) {
            $collections = $this->getCollection()
                ->addFieldToFilter('url_key', ['eq' => $value])
                ->addFieldToFilter('store_ids', ['finset' => Store::DEFAULT_STORE_ID]);
        }

        return $collections->getFirstItem();
    }

    /**
     * @param array $storeIds
     * @param string $identifier
     *
     * @return bool
     */
    public function getIsUniqueFormToStores($storeIds, $identifier)
    {
        $conditions = [];

        foreach ($storeIds as $storeId) {
            $conditions[] = [
                ['eq' => 0],
                ['finset' => $storeId]
            ];
        }

        $customForms = $this->getCollection()->addFieldToFilter('tag_id', ['neq' => $this->getId()])
            ->addFieldToFilter('url_key', $identifier);
        if ($storeIds[0] === "0" && $customForms->getSize()) {
            return false;
        }

        $customForms = $this->getCollection()->addFieldToFilter('tag_id', ['neq' => $this->getId()])
            ->addFieldToFilter('url_key', $identifier)
            ->addFieldToFilter('store_ids', $conditions);

        if (!$customForms->getSize()) {
            return true;
        }

        return false;
    }

    /**
     * @return Collection
     */
    public function getSelectedArticlesCollection()
    {
        if ($this->articleCollection === null) {
            $collection = $this->articleCollectionFactory->create();
            $collection->join(
                $this->getResource()->getTable('mageplaza_faqs_article_tag'),
                'main_table.article_id=' . $this->getResource()->getTable('mageplaza_faqs_article_tag') .
                '.article_id AND ' . $this->getResource()->getTable('mageplaza_faqs_article_tag') . '.tag_id="'
                . $this->getId() . '"',
                ['*']
            );
            $this->articleCollection = $collection;
        }

        return $this->articleCollection;
    }

    /**
     * @return array
     */
    public function getArticleIds()
    {
        if (!$this->hasData('article_ids')) {
            $ids = $this->getResource()->getArticleIds($this);
            $this->setData('article_ids', $ids);
        }

        return (array) $this->_getData('article_ids');
    }

    /**
     * @return bool|string
     */
    public function getUrl()
    {
        return $this->helperData->getFaqsUrl($this, Data::TYPE_TAG);
    }
}
