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

defined('_JEXEC') or die;

use Exception;
use Joomla\CMS\Application\CMSApplicationInterface;
use Joomla\CMS\Factory;
use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
use Joomla\Filesystem\Folder;
use Joomla\CMS\Form\Form;
use Joomla\CMS\Helper\ContentHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Toolbar\ToolbarHelper;
use Joomla\Component\Formea\Administrator\Helper\FormeaHelper;
use Joomla\Component\Formea\Administrator\Model\FormeaModel;
use Joomla\Component\Formea\Administrator\View\FormeaView;
use Joomla\Filesystem\Path;


/**
 * View to edit a formea.
 *
 * @since  1.0.0
 */
class HtmlView extends FormeaView
{
  /**
   * The Form object
   *
   * @var    Form
   * @since  1.0.0
   */
  public $form;

  /**
   * The active item
   *
   * @var    object
   * @since  1.0.0
   */
  public $item;

  /**
   * @var CMSApplicationInterface
   * @since 1.0.0
   */
  protected $app;


  /**
   * Display the view.
   *
   * @param   string  $tpl  The name of the template file to parse; automatically searches through the template paths.
   *
   * @return  mixed  A string if successful, otherwise an Error object.
   *
   * @throws  Exception
   * @since   1.0.0
   */
  public function display($tpl = null)
  {
    $this->app = Factory::getApplication();
    $id        = $this->app->getInput()->getInt('id', 0);
    if ($id < 1) {
      $this->app->enqueueMessage(Text::_('COM_FORMEA_INVALID_ELTYPE_ITEM'), 'error');
      $this->app->redirect(Route::_('index.php?option=com_formea&view=eltypes', false));
    }

    /** @var FormeaModel $model */
    $model      = $this->getModel();
    $this->item = $model->getItem();
    $this->form = $this->getForm();

    // If we are forcing a language in modal (used for associations).
    if (
      $this->getLayout() === 'modal'
      && $forcedLanguage = Factory::getApplication()->input->get('forcedLanguage', '')
    ) {
      // Set the language field to the forcedLanguage and disable changing it.
      $this->form->setValue('language', null, $forcedLanguage);
      $this->form->setFieldAttribute('language', 'readonly', 'true');

      // Only allow to select categories with All language or with the forced language.
      $this->form->setFieldAttribute('catid', 'language', '*,' . $forcedLanguage);
    }

    $this->_loadLanguage();
    $this->addToolbar();

    return parent::display($tpl);
  }

  /**
   * Add the page title and toolbar.
   *
   * @return  void
   *
   * @throws  Exception
   * @since   1.0.0
   */
  private function addToolbar(): void
  {
    $app = Factory::getApplication();
    $app->input->set('hidemainmenu', true);

    $user   = $app->getIdentity();
    $userId = $user->id;
    $isNew  = ($this->item->id == 0);

    $title = Text::_('COM_FORMEA_ELTYPE');
    if (!empty($this->item->title)) {
      $title .= ': ' . Text::_($this->item->title);
    }
    ToolbarHelper::title(
      $title,
      'key'
    );
    $this->setDocumentTitle($title . ' - ' . Text::_('COM_FORMEA'));

    // Since we don't track these assets at the item level, use the category id.
    $canDo = ContentHelper::getActions('com_formea', 'component', $this->item->id);

    // Build the actions for new and existing records.
    if ($isNew) {
      // For new records, check the create permission.
      if ($isNew && $canDo) {
        ToolbarHelper::apply('eltype.apply');
        ToolbarHelper::save('eltype.save');
      }

      ToolbarHelper::cancel('eltype.cancel');
    } else {
      // Since it's an existing record, check the edit permission, or fall back to edit own if the owner.
      $itemEditable = $canDo->get('core.edit')
        || ($canDo->get('core.edit.own')
          && $this->item->created_by == $userId);


      ToolbarHelper::apply('eltype.apply');
      ToolbarHelper::save('eltype.save');
      ToolbarHelper::cancel('eltype.cancel', 'JTOOLBAR_CLOSE');
    }
    ToolbarHelper::divider();
    ToolbarHelper::help('', false, FormeaHelper::getHelpLink('Eltype'));
  }

  protected function _loadLanguage()
  {
    if (!empty($this->item)) {
      $lang     = $this->app->getLanguage();
      $langTag  = $lang->getTag();
      FormeaGeneralHelper::loadExtensionLanguage($this->item->name, 'element', $lang, $langTag);
    }
  }
}
