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

defined('_JEXEC') or die;

use Exception;
use Joomla\CMS\Application\CMSApplicationInterface;
use Joomla\CMS\Factory;
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\CMS\WebAsset\WebAssetManager;
use Joomla\Component\Formea\Administrator\Helper\FormeaHelper;
use Joomla\Component\Formea\Administrator\Model\ElementModel;
use Joomla\CMS\Language\Multilanguage;
use Joomla\Component\Formea\Administrator\View\FormeaView;
use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
use Joomla\Filesystem\Path;
use stdClass;


/**
 * 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;

  /**
   * @var object
   * @since 1.0.0
   */
  public $elementType;

  /**
   * @var bool
   * @since 1.0.0
   */
  public $isMultiLang;

  /**
   * @var
   * @since 1.0.0
   */
  public $languageLists;

  /**
   * @var int
   * @since 1.0.0
   */
  public $totalLanguages;

  /**
   * @var string
   * @since 1.0.0
   */
  public $lang_tag;

  public $formeaScript;

  public $formeaScript2;

  public $isOptionListVal = false;

  public $hasElementConfig = false;

  public $elementTypeDetailConfig;

  public $totalLang;


  /**
   * 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();
    $type      = $this->app->getInput()->getString('type', null);
    if (empty($type)) {
      $this->app->enqueueMessage(Text::_('COM_FORMEA_INVALID_ELTYPE_ITEM'), 'error');
      $this->app->redirect(Route::_('index.php?option=com_formea&view=elements', false));
    }

    /** @var ElementModel $model */
    $model       = $this->getModel();
    $elementType = $model->getElementType($type);
    if (empty($elementType)) {
      $this->app->enqueueMessage(Text::_('COM_FORMEA_INVALID_ELTYPE_NOT_FOUND'), 'error');
      $this->app->redirect(Route::_('index.php?option=com_formea&view=elements', false));
    }
    $this->elementType = $elementType;
    if (isset($this->elementType->config->values->optionLists)) {
      $this->isOptionListVal = $this->elementType->config->values->optionLists;
    }
    $this->elementTypeDetailConfig = new stdClass();
    if (isset($this->elementType->config->details)) {
      $this->elementTypeDetailConfig = $this->elementType->config->details;
    }

    $this->item             = $model->getItem();
    $this->form             = $this->getForm();
    $this->state            = $this->get('State');
    $this->params           = $this->state->get('params');
    $this->hasElementConfig = $this->state->get('element.' . $this->elementType->name . '.hasConfig');


    $this->lang_tag                 = $this->app->getLanguage()->getTag();
    $this->isMultiLang              = Multilanguage::isEnabled();
    $langLists                      = FormeaGeneralHelper::getLanguages();
    $languageLists                  = [];
    $languageLists[$this->lang_tag] = (object) [];
    $this->totalLanguages           = count($langLists);
    for ($i = 0; $i < $this->totalLanguages; $i++) {
      $languageLists[$langLists[$i]->lang_code] = $langLists[$i];
    }
    $languageLists       = array_values($languageLists);
    $this->languageLists = $languageLists;

    $doc = $this->getDocument();
    /** @var WebAssetManager $wa */
    $wa = $doc->getWebAssetManager();
    $wa->getRegistry()->addExtensionRegistryFile('com_formea');
    if ($this->elementType->config->validations->enabled) {
      $wa->useScript('com_formea.admin-field-validation');
    }

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

    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::sprintf('COM_FORMEA_S_ELEMENT', $this->elementType->name);
    if (!empty($this->item->title)) {
      $title = Text::_($this->item->title) . ' : ' . $title;
    }
    ToolbarHelper::title(
      $title,
      'fas fa-stream'
    );
    $this->getDocument()->setTitle($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('element.apply');
        //ToolbarHelper::save('element.save');
        ToolbarHelper::saveGroup(
          [
            ['save', 'element.save'],
            ['save2new', 'element.save2new'],
          ],
          'btn-success'
        );
      }

      ToolbarHelper::cancel('element.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);

      $toolbarButtons = [];

      // Can't save the record if it's not editable
      if ($itemEditable) {
        ToolbarHelper::apply('element.apply');

        $toolbarButtons[] = ['save', 'element.save'];

        // We can save this record, but check the create permission to see if we can return to make a new one.
        if ($canDo->get('core.create')) {
          $toolbarButtons[] = ['save2new', 'element.save2new'];
        }
      }


      // If checked out, we can still save
      if ($canDo->get('core.create')) {
        $toolbarButtons[] = ['save2copy', 'element.save2copy'];
      }

      ToolbarHelper::saveGroup(
        $toolbarButtons,
        'btn-success'
      );

      ToolbarHelper::cancel('element.cancel', 'JTOOLBAR_CLOSE');
    }
    ToolbarHelper::divider();
    ToolbarHelper::help('', false, FormeaHelper::getHelpLink('Element'));
    $wa = $this->getDocument()->getWebAssetManager();
    $g  = [
      'element' => [
        'id'   => (empty($this->item->id)) ? 0 : $this->item->id,
        'type' => $this->item->type
      ]
    ];
    $wa->addInlineScript('FsrGlobal.datum = ' . json_encode($g) . ';');
  }

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