<?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\Article\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\Article;
use Mageplaza\Faqs\Model\ResourceModel\Article\Collection;
use Mageplaza\Faqs\Model\ResourceModel\Article\CollectionFactory;

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

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

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

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

    /**
     * Set grid params
     */
    public function _construct()
    {
        parent::_construct();

        $this->setId('article_grid');
        $this->setDefaultSort('position');
        $this->setDefaultDir('ASC');
        $this->setSaveParametersInSession(false);
        $this->setUseAjax(true);

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

    /**
     * @inheritdoc
     */
    protected function _prepareCollection()
    {
        $articleId = $this->getArticle()->getId();
        if (!$articleId) {
            $articleId = $this->getRequest()->getParam('article_id');
        }
        /** @var Collection $collection */
        $collection = $this->articleCollectionFactory->create();
        $collection->addFieldToSelect('*')->addFieldToFilter('article_id', ['neq' => $articleId]);
        $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'           => __('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;
    }

    /**
     * @return array|false
     * @throws LocalizedException
     */
    protected function _getSelectedArticles()
    {
        $articles = $this->getRequest()->getPost('article_articles', null);
        if (!is_array($articles)) {
            $articles = $this->getArticle()->getRelatedArticleIds();

            return array_combine($articles, $articles);
        }

        return $articles;
    }

    /**
     * Get selected products. This is callback function when clicking filter product
     *
     * @return array
     * @throws LocalizedException
     */
    public function getSelectedArticles()
    {
        $selected = $this->getArticle()->getRelatedArticleIds();
        if (!is_array($selected)) {
            $selected = [];
        }

        return array_combine($selected, $selected);
    }

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

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

    /**
     * @return Article
     */
    public function getArticle()
    {
        return $this->coreRegistry->registry('mageplaza_faqs_article');
    }

    /**
     * Apply the product grid filter
     *
     * @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('article_id', ['in' => $articleIds]);
            } else {
                if ($articleIds) {
                    $this->getCollection()->addFieldToFilter('article_id', ['nin' => $articleIds]);
                }
            }
        } else {
            parent::_addColumnFilterToCollection($column);
        }

        return $this;
    }

    /**
     * @return string
     */
    public function getTabLabel()
    {
        return __('Related FAQ Assign');
    }

    /**
     * @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/article/relatedarticles', ['_current' => true]);
    }

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