<?php

/**
 * @package     Joomla.Administrator
 * @subpackage  com_formea
 *
 * @copyright   Copyright (C) 2010-2025 Feseur Sdn Bhd. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @version     1.3.0
 */

namespace Joomla\Component\Formea\Administrator\View\Formeas;

defined('_JEXEC') or die;

use Exception;
use Joomla\CMS\Factory;
use Joomla\CMS\Form\Form;
use Joomla\CMS\Helper\ContentHelper;
use Joomla\CMS\HTML\Helpers\Sidebar;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\View\GenericDataException;
use Joomla\CMS\Object\CMSObject;
use Joomla\CMS\Pagination\Pagination;
use Joomla\CMS\Toolbar\Toolbar;
use Joomla\CMS\Toolbar\ToolbarHelper;
use Joomla\Component\Content\Administrator\Extension\ContentComponent;
use Joomla\Component\Formea\Administrator\Helper\FormeaHelper;
use Joomla\Component\Formea\Administrator\Model\FormeasModel;
use Joomla\Component\Formea\Administrator\View\FormeaView;

/**
 * View class for a list of formeas.
 *
 * @since  1.0.0
 */
class HtmlView extends FormeaView
{
  /**
   * An array of items
   *
   * @var    array
   * @since  1.0.0
   */
  public $items = [];

  /**
   * The pagination object
   *
   * @var    Pagination
   * @since  1.0.0
   */
  public $pagination;

  /**
   * The model state
   *
   * @var    CMSObject
   * @since  1.0.0
   */
  public $state;

  /**
   * Form object for search filters
   *
   * @var    Form
   * @since  1.0.0
   */
  public $filterForm;

  /**
   * The active search filters
   *
   * @var    array
   * @since  1.0.0
   */
  public $activeFilters = [];

  /**
   * The sidebar markup
   *
   * @var    string
   * @since  1.0.0
   */
  protected $sidebar;

  /**
   * Is this view an Empty State
   *
   * @var   boolean
   * @since 1.0.0
   */
  private $isEmptyState = false;

  /**
   * Method to display the view.
   *
   * @param   string  $tpl  A template file to load. [optional]
   *
   * @return  void
   *
   * @throws  Exception
   * @since   1.0.0
   */
  public function display($tpl = null): void
  {

    /** @var FormeasModel $model */
    $model               = $this->getModel();
    $this->items         = $model->getItems();
    $this->pagination    = $model->getPagination();
    $this->filterForm    = $model->getFilterForm();
    $this->activeFilters = $model->getActiveFilters();
    $this->state         = $model->getState();
    $this->isEmptyState  = $this->get('IsEmptyState');

    $errors = $this->getErrors();

    if (count($errors)) {
      throw new GenericDataException(implode("\n", $errors), 500);
    }

    if (!count($this->items) && $this->isEmptyState) {
      $this->setLayout('emptystate');
    }

    // We don't need toolbar in the modal window.
    if ($this->getLayout() !== 'modal') {
      FormeaHelper::addSubmenu('formeas');
      $this->addToolbar();
      $this->sidebar = Sidebar::render();
    }

    $this->getDocument()->setTitle(Text::_('COM_FORMEA_FORMS_MANAGER') . ' - ' . Text::_('COM_FORMEA'));

    $wa = $this->getDocument()->getWebAssetManager();
    $wa->useScript('field.modal-fields');
    $wa->useScript('com_formea.form-upload');
    $wa->useStyle('com_formea.form-upload');
    $wa->useStyle('switcher');

    parent::display($tpl);
  }

  /**
   * Add the page title and toolbar.
   *
   * @return  void
   *
   * @throws  Exception
   * @since   1.0.0
   */
  protected function addToolbar()
  {
    $canDo = ContentHelper::getActions(
      'com_formea',
      'category',
      $this->state->get('filter.category_id')
    );
    $user  = Factory::getApplication()->getIdentity();

    // Get the toolbar object instance
    $toolbar = Toolbar::getInstance();

    ToolbarHelper::title(
      Text::_('COM_FORMEA_FORMS_MANAGER'),
      'formea-block'
    );

    if (
      $canDo->get('core.create')
      || count($user->getAuthorisedCategories(
        'com_formea',
        'core.create'
      )) > 0
    ) {
      $toolbar->addNew('formea.add');
    }

    if ($canDo->get('core.edit.state')) {

      $toolbar->standardButton('index', 'COM_FORMEA_UPLOAD_FORMS')
        ->icon('icon-upload')
        ->onclick('formeaCore.uploadForms(\'cmd\');')->listCheck(false);

      $dropdown = $toolbar->dropdownButton('status-group')
        ->text('JTOOLBAR_CHANGE_STATUS')
        ->toggleSplit(false)
        ->icon('icon-ellipsis-h')
        ->buttonClass('btn btn-action')
        ->listCheck(true);

      $childBar = $dropdown->getChildToolbar();

      $childBar->publish('formeas.publish')->listCheck(true);

      $childBar->unpublish('formeas.unpublish')->listCheck(true);

      $childBar->basicButton('broom', 'Clear Submissions', 'formeas.clearSubmission')->listCheck(true);

      if ($user->authorise('core.admin')) {
        $childBar->checkin('formeas.checkin')->listCheck(true);
      }

      if ($this->state->get('filter.published') != ContentComponent::CONDITION_TRASHED) {
        $childBar->trash('formeas.trash')->listCheck(true);
      }
    }

    if (!$this->isEmptyState && $this->state->get('filter.published') == ContentComponent::CONDITION_TRASHED && $canDo->get('core.delete')) {
      $toolbar->delete('formeas.delete', 'JTOOLBAR_EMPTY_TRASH')
        ->message('JGLOBAL_CONFIRM_DELETE')
        ->listCheck(true);
    }

    $toolbar->popupButton('batch')
      ->text('JTOOLBAR_BATCH')
      ->selector('collapseModal')
      ->listCheck(true);


    if (
      $user->authorise('core.admin', 'com_formea')
      || $user->authorise(
        'core.options',
        'com_formea'
      )
    ) {
      $toolbar->preferences('com_formea');
    }

    ToolbarHelper::divider();
    ToolbarHelper::help('', false, FormeaHelper::getHelpLink('Formeas'));

    HTMLHelper::_('sidebar.setAction', 'index.php?option=com_formea');
  }


  /**
   * Returns an array of fields the table can be sorted by
   *
   * @return  array  Array containing the field name to sort by as the key and display text as value
   *
   * @since   1.0.0
   */
  protected function getSortFields()
  {
    return [
      'a.ordering'     => Text::_('JGRID_HEADING_ORDERING'),
      'a.published'    => Text::_('JSTATUS'),
      'a.name'         => Text::_('JGLOBAL_TITLE'),
      'category_title' => Text::_('JCATEGORY'),
      'a.access'       => Text::_('JGRID_HEADING_ACCESS'),
      'a.language'     => Text::_('JGRID_HEADING_LANGUAGE'),
      'a.id'           => Text::_('JGRID_HEADING_ID'),
    ];
  }
}
