<?php
/**
 * @package     Bluecoder.JFilters
 *
 * @copyright   Copyright © 2021 - 2023 Blue-Coder.com. All rights reserved.
 * @license     GNU General Public License 2 or later, see COPYING.txt for license details.
 */

namespace Bluecoder\Component\Jfilters\Administrator\Field;

\defined('_JEXEC') or die();

use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Form\FormField;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Layout\LayoutHelper;
use Joomla\CMS\Object\CMSObject;
use Joomla\CMS\Session\Session;

class FiltersModalButtonField extends FormField
{

    protected function getInput()
    {
        // Check if com_jfilters is enabled
        if (!ComponentHelper::isEnabled('com_jfilters')) {
            return;
        }

        // Guess the field context based on view.
        $jinput = Factory::getApplication()->input;
        $context = $jinput->get('option') . '.' . $jinput->get('view');

        // Load the JFilters language files. This usually called outside the com_jfilters context (e.g. from a module).
        Factory::getApplication()->getLanguage()->load('com_jfilters', JPATH_ADMINISTRATOR);

        $link = 'index.php?option=com_jfilters&amp;view=filters&amp;layout=modal&amp;tmpl=component&amp;context='
            . $context . '&amp;client=module.results&amp;' . Session::getFormToken() . '=1&amp;' . $this->value;

        $data = $this->getLayoutData();

        $button = new CMSObject();
        $button->modal   = true;
        $button->link    = $link;
        // The Modal Heading
        $button->text    = Text::_('COM_JFILTERS_FILTERS');
        $button->name    = $this->_type . '_' . $this->_name;
        $button->id = 'jfilters_filters_modal';
        $button->options = [
            'confirmCallback' => 'applyFilters(\'module\');',
            'confirmText'     => Text::_('COM_JFILTERS_APPLY_FILTERS'),
        ];

        $html = '<button value="' . $link . '" class="button-preview btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#' . $button->id . '">
    ' . Text::_('MOD_JFILTERS_RESULTS_ADD_FILTERS_LABEL') . '</button>
        <input type="hidden" name="jform[params][selected_filters]" id="jfilters_filters_selected" value="' . htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') . '"/>';

        $html .= LayoutHelper::render('joomla.editors.buttons.modal', $button);

        return $html;
    }
}