<?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\Block\Adminhtml\Tag\Edit\Tab;

use Exception;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Block\Widget\Grid\Column;
use Magento\Backend\Block\Widget\Grid\Extended;
use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Backend\Helper\Data;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;
use Mageplaza\Faqs\Model\Tag as TagModel;
use Mageplaza\Faqs\Model\ArticleFactory;
use Mageplaza\Faqs\Model\Article as ArticleModel;
use Mageplaza\Faqs\Model\ResourceModel\Article\Collection;
use Mageplaza\Faqs\Model\ResourceModel\Article\CollectionFactory;

/**
 * Class Article
 * @package Mageplaza\Faqs\Block\Adminhtml\Tag\Edit\Tab
 */
class Article extends Extended implements TabInterface
{
    /**
     * Article collection factory
     *
     * @var CollectionFactory
     */
    public $articleCollectionFactory;

    /**
     * Registry
     *
     * @var Registry
     */
    public $coreRegistry;

    /**
     * Article factory
     *
     * @var ArticleFactory
     */
    public $articleFactory;

    /**
     * Post constructor.
     *
     * @param Context $context
     * @param Registry $coreRegistry
     * @param Data $backendHelper
     * @param ArticleFactory $articleFactory
     * @param CollectionFactory $articleCollectionFactory
     * @param array $data
     */
    public function __construct(
        Context $context,
        Registry $coreRegistry,
        Data $backendHelper,
        ArticleFactory $articleFactory,
        CollectionFactory $articleCollectionFactory,
        array $data = []
    ) {
        $this->coreRegistry             = $coreRegistry;
        $this->articleFactory           = $articleFactory;
        $this->articleCollectionFactory = $articleCollectionFactory;

        parent::__construct($context, $backendHelper, $data);
    }

    /**
     * Set grid params
     */
    public function _construct()
    {
        parent::_construct();
        $this->setId('article_grid');
        $this->setDefaultSort('related.article_id');
        $this->setDefaultDir('ASC');
        $this->setSaveParametersInSession(false);
        $this->setUseAjax(true);

        if ($this->getTag()->getId()) {
            $this->setDefaultFilter(['in_articles' => 1]);
        }
    }

    /**
     * @inheritdoc
     */
    protected function _prepareCollection()
    {
        /** @var Collection $collection */
        $collection = $this->articleCollectionFactory->create();
        $collection->addFieldToSelect('*');
        $this->setCollection($collection);

        return parent::_prepareCollection();
    }

    /**
     * @return $this
     * @throws Exception
     */
    protected function _prepareColumns()
    {
        $this->addColumn('in_articles', [
            'header_css_class' => 'a-center',
            'type'             => 'checkbox',
            'name'             => 'in_article',
            'values'           => $this->_getSelectedArticles(),
            'align'            => 'center',
            'index'            => 'article_id'
        ]);
        $this->addColumn('article_id', [
            'header'           => __('Article ID'),
            'sortable'         => true,
            'index'            => 'article_id',
            'type'             => 'number',
            'header_css_class' => 'col-id',
            'column_css_class' => 'col-id'
        ]);
        $this->addColumn('name', [
            'header'           => __('Question Name'),
            'index'            => 'name',
            'header_css_class' => 'col-name',
            'column_css_class' => 'col-name'
        ]);
        $this->addColumn('url_key', [
            'header'           => __('URL Key'),
            'index'            => 'url_key',
            'header_css_class' => 'col-url-key',
            'column_css_class' => 'col-url-key'
        ]);
        $this->addColumn('position', [
            'header'           => __('Position'),
            'name'             => 'position',
            'header_css_class' => 'hidden',
            'column_css_class' => 'hidden',
            'validate_class'   => 'validate-number',
            'index'            => 'position',
            'editable'         => true,
        ]);

        return $this;
    }

    /**
     * Retrieve selected Articles
     *
     * @return array
     */
    protected function _getSelectedArticles()
    {
        $articles = $this->getRequest()->getPost('tag_articles', null);

        if (!is_array($articles)) {
            $articles = $this->getTag()->getArticleIds();

            return array_combine($articles, $articles);
        }

        return $articles;
    }

    /**
     * Retrieve selected Articles
     *
     * @return array
     */
    public function getSelectedArticles()
    {
        $selected = $this->getTag()->getArticleIds();
        if (!is_array($selected)) {
            $selected = [];
        }

        return array_combine($selected, $selected);
    }

    /**
     * @param ArticleModel|Object $item
     *
     * @return string
     */
    public function getRowUrl($item)
    {
        return '#';
    }

    /**
     * get grid url
     *
     * @return string
     */
    public function getGridUrl()
    {
        return $this->getUrl('*/*/articlesGrid', ['id' => $this->getTag()->getId()]);
    }

    /**
     * @return TagModel
     */
    public function getTag()
    {
        return $this->coreRegistry->registry('mageplaza_faqs_tag');
    }

    /**
     * @param Column $column
     *
     * @return $this
     * @throws LocalizedException
     */
    protected function _addColumnFilterToCollection($column)
    {
        if ($column->getId() == 'in_articles') {
            $articleIds = $this->_getSelectedArticles();
            if (empty($articleIds)) {
                $articleIds = 0;
            }
            if ($column->getFilter()->getValue()) {
                $this->getCollection()->addFieldToFilter('main_table.article_id', ['in' => $articleIds]);
            } elseif ($articleIds) {
                $this->getCollection()->addFieldToFilter('main_table.article_id', ['nin' => $articleIds]);
            }
        } else {
            parent::_addColumnFilterToCollection($column);
        }

        return $this;
    }

    /**
     * @return string
     */
    public function getTabLabel()
    {
        return __('Question');
    }

    /**
     * @return bool
     */
    public function isHidden()
    {
        return false;
    }

    /**
     * @return string
     */
    public function getTabTitle()
    {
        return $this->getTabLabel();
    }

    /**
     * @return bool
     */
    public function canShowTab()
    {
        return true;
    }

    /**
     * @return string
     */
    public function getTabUrl()
    {
        return $this->getUrl('mpfaqs/tag/articles', ['_current' => true]);
    }

    /**
     * @return string
     */
    public function getTabClass()
    {
        return 'ajax only';
    }
}
