<?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\ResourceModel;

use Magento\Framework\App\RequestInterface;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Magento\Framework\Model\ResourceModel\Db\Context;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Mageplaza\Faqs\Helper\Data;
use Mageplaza\Faqs\Model\Tag as TagModel;

/**
 * Class Tag
 * @package Mageplaza\Faqs\Model\ResourceModel
 */
class Tag extends AbstractDb
{
    /**
     * Date model
     *
     * @var DateTime
     */
    public $date;

    /**
     * Event Manager
     *
     * @var ManagerInterface
     */
    public $eventManager;

    /**
     * Post relation model
     *
     * @var string
     */
    public $tagArticleTable;

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

    /**
     * @var RequestInterface
     */
    private $request;

    /**
     * Tag constructor.
     *
     * @param Context $context
     * @param ManagerInterface $eventManager
     * @param DateTime $date
     * @param RequestInterface $request
     * @param Data $helperData
     */
    public function __construct(
        Context $context,
        ManagerInterface $eventManager,
        DateTime $date,
        RequestInterface $request,
        Data $helperData
    ) {
        $this->helperData   = $helperData;
        $this->date         = $date;
        $this->eventManager = $eventManager;
        $this->request      = $request;

        parent::__construct($context);

        $this->tagArticleTable = $this->getTable('mageplaza_faqs_article_tag');
    }

    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('mageplaza_faqs_tag', 'tag_id');
    }

    /**
     * @param string $ids
     *
     * @return array
     * @throws LocalizedException
     */
    public function getTagNameByIds($ids)
    {
        $adapter = $this->getConnection();
        $select  = $adapter->select()
            ->from($this->getMainTable(), 'name')
            ->where("tag_id IN (" . $ids . ")");

        return $adapter->fetchCol($select);
    }

    /**
     * @inheritdoc
     */
    protected function _beforeSave(AbstractModel $object)
    {
        $object->setUpdatedAt($this->date->date());
        if ($object->isObjectNew()) {
            $object->setCreatedAt($this->date->date());
        }

        if (is_array($object->getStoreIds())) {
            $object->setStoreIds(implode(',', $object->getStoreIds()));
        }

        if (!$object->getUrlKey()) {
            $object->setUrlKey(
                $this->helperData->generateUrlKey($this, $object, $object->getName())
            );
        }

        return parent::_beforeSave($object);
    }

    /**
     * @param AbstractModel|TagModel $object
     *
     * @return AbstractDb
     */
    protected function _afterSave(AbstractModel $object)
    {
        $this->saveArticleRelation($object);

        return parent::_afterSave($object);
    }

    /**
     * @param TagModel $tag
     *
     * @return $this
     */
    protected function saveArticleRelation(TagModel $tag)
    {
        $tag->setIsChangedArticleList(false);
        $id = $tag->getId();

        $articles = $tag->getArticlesIds();

        if ($articles === null) {
            if ($tag->getIsArticleGrid()) {
                $articles = [];
            } else {
                return $this;
            }
        }

        $articles    = array_keys($articles);
        $oldArticles = $tag->getArticleIds();
        $insert      = array_diff($articles, $oldArticles);
        $delete      = array_diff($oldArticles, $articles);
        $adapter     = $this->getConnection();

        if (!empty($delete)) {
            $condition = ['article_id IN(?)' => $delete, 'tag_id=?' => $id];
            $adapter->delete($this->tagArticleTable, $condition);
        }
        if (!empty($insert)) {
            $data = [];
            foreach ($insert as $entityId) {
                $data[] = [
                    'tag_id'     => (int) $id,
                    'article_id' => (int) $entityId
                ];
            }
            $adapter->insertMultiple($this->tagArticleTable, $data);
        }
        if (!empty($insert) || !empty($delete)) {
            $entityIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
            $this->eventManager->dispatch(
                'mageplaza_faqs_tag_change_articles',
                ['article' => $tag, 'entity_ids' => $entityIds]
            );
        }
        if (!empty($insert) || !empty($delete)) {
            $tag->setIsChangedArticleList(true);
            $entityIds = array_keys($insert + $delete);
            $tag->setAffectedArticleIds($entityIds);
        }

        return $this;
    }

    /**
     * @param TagModel $tag
     *
     * @return array
     */
    public function getArticleIds(TagModel $tag)
    {
        $adapter = $this->getConnection();
        $select  = $adapter->select()->from(
            $this->tagArticleTable,
            'article_id'
        )
            ->where(
                'tag_id = ?',
                (int) $tag->getId()
            );

        return $adapter->fetchCol($select);
    }

    /**
     * @param TagModel $tag
     *
     * @return array
     */
    public function getArticlesPosition(TagModel $tag)
    {
        $select = $this->getConnection()->select()
            ->from($this->tagArticleTable, ['article_id'])
            ->where('tag_id = :tag_id');

        $bind = ['tag_id' => (int) $tag->getId()];

        return $this->getConnection()->fetchPairs($select, $bind);
    }
}
