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

defined('_JEXEC') or die;

use Exception;
use Joomla\CMS\Application\CMSApplicationInterface;
use Joomla\CMS\Factory;
use Joomla\Component\Formea\Site\Libraries\FormeaEltype;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Folder;
use Joomla\CMS\Form\Form;
use Joomla\CMS\Helper\ContentHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Toolbar\ToolbarHelper;
use Joomla\CMS\WebAsset\WebAssetManager;
use Joomla\Component\Formea\Administrator\Helper\FormeaHelper;
use Joomla\Component\Formea\Administrator\Model\FormeaModel;
use Joomla\CMS\Language\Multilanguage;
use Joomla\Component\Formea\Administrator\View\FormeaView;
use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
use Joomla\Filesystem\Path;
use Joomla\Utilities\ArrayHelper;


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

  /**
   * @var array
   * @since 1.0.0
   */
  public $placeholder_keys;

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

  /**
   * @var array
   * @since 1.0.0
   */
  public $coreExtensions;

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

  /**
   * 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();
    /** @var FormeaModel $model */
    $model                     = $this->getModel();
    $this->item                = $model->getItem();
    $this->form                = $this->getForm();
    $this->hasCoreExtensions   = $model->hasCoreExtensions;
    $this->coreExtensions      = $model->coreExtensions;
    $this->totalCoreExtensions = count($this->coreExtensions);

    if (empty($this->item->admin_column)) {
      $this->item->admin_column = [];
    } else {
      $this->item->admin_column = json_decode($this->item->admin_column, true);
    }
    $this->item->admin_column = ArrayHelper::toInteger($this->item->admin_column);

    $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;

    $elementAssets = $this->loadElementAssets();
    $doc           = $this->getDocument();
    /** @var WebAssetManager $wa */
    $wa = $doc->getWebAssetManager();
    $wa->getRegistry()->addExtensionRegistryFile('com_formea');
    $wa->useScript('com_formea.admin-column-display');
    $wa->useScript('com_formea.admin-edit-formea');
    // $wa->useScript('com_formea.admin-edit-form-hook');
    // $wa->useStyle('com_formea.admin-edit-formea');
    $elementFiles = $elementAssets['fileStyles'];

    if (!empty($elementFiles)) {
      $totalElementFiles = count($elementFiles);
      for ($l = 0; $l < $totalElementFiles; $l++) {
        $wa->useStyle($elementFiles[$l]);
      }
    }
    $langText       = (object) ['loading' => Text::_('COM_FORMEA_LOADING_WAIT'), 'copyToClipBoard' => Text::_('COM_FORMEA_CLICK_COPY_CLIPBOARD')];
    $langTextObject = [
      'show' => Text::_('JSHOW'),
      'hide' => Text::_('JHIDE')
    ];

    $js = 'FsrGlobal.langText = ' . json_encode($langText) . ';';
    $js .= 'var langCode = \'' . $this->lang_tag . '\';';
    $js .= 'var selectedAdminColumn = ' . json_encode($this->item->admin_column) . ';';
    $js .= 'var elementUrl = \'index.php?option=com_formea&task=element.edit&layout=modal&tmpl=component\';';
    $js .= 'var langText = ' . json_encode($langTextObject) . ';';
    $js .= file_get_contents(JPATH_ADMINISTRATOR . '/components/com_formea/tmpl/formea/hook.js');

    $wa->addInlineScript($js);

    //core extension files if any
    if ($this->hasCoreExtensions) {
      $lang    = $this->app->getLanguage();
      $langTag = $lang->getTag();

      for ($j = 0; $j < $this->totalCoreExtensions; $j++) {
        $corePath      = FORMEA_CORE_PATH . '/' . $this->coreExtensions[$j]->name;
        $coreParamFile = $corePath . '/core.json';
        if (is_file(Path::clean($coreParamFile))) {
          $coreParam = json_decode(file_get_contents($coreParamFile));
          if (isset($coreParam->adminFiles->load)) {
            if ($coreParam->adminFiles->load) {
              $totalFiles = count($coreParam->adminFiles->fileScripts);
              for ($k = 0; $k < $totalFiles; $k++) {
                $wa->useScript($coreParam->adminFiles->fileScripts[$k]);
              }
              $totalFiles = count($coreParam->adminFiles->fileStyles);
              for ($k = 0; $k < $totalFiles; $k++) {
                $wa->useStyle($coreParam->adminFiles->fileStyles[$k]);
              }
            }
          }
        }
        if (is_dir(Path::clean($corePath . '/language/' . $langTag))) {
          $lang->load($this->coreExtensions[$j]->name, $corePath, $langTag);
        }
      }
    }

    //  $this->_setForm();
    $this->addToolbar();
    $this->getPlaceholderKeys();


    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  = $isNew ? Text::_('COM_FORMEA_MANAGER_FORMEA_NEW') : Text::_('COM_FORMEA_MANAGER_FORMEA_EDIT');
    ToolbarHelper::title(
      $title,
      'address formea'
    );
    $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('formea.apply');

        ToolbarHelper::saveGroup(
          [
            ['save', 'formea.save'],
            ['save2new', 'formea.save2new'],
          ],
          'btn-success'
        );
      }

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

        $toolbarButtons[] = ['save', 'formea.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', 'formea.save2new'];
        }
      }

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

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

  private function getPlaceholderKeys()
  {
    $this->placeholder_keys = array_keys(FormeaGeneralHelper::getGlobalPlaceholders());
  }

  /**
   * Method to load Element type CSS for Preview
   *
   * @since 1.0.9
   */
  private function loadElementAssets()
  {
    $allElements   = FormeaHelper::getInstalledElTypes(1);
    $totalElements = count($allElements);
    $assets        = [
      'inlineScripts' => [],
      'inlineStyles'  => [],
      'fileScripts'   => [],
      'fileStyles'    => []
    ];
    for ($i = 0; $i < $totalElements; $i++) {
      if (isset($allElements[$i]->config)) {
        if (!empty($allElements[$i]->config->get('formBuilder'))) {
          $formBuilder = $allElements[$i]->config->get('formBuilder');
          if (isset($formBuilder->loadCss) && $formBuilder->loadCss) {

            $classFile = 'Formea' . $allElements[$i]->name . '.php';
            if (is_file(Path::clean(FORMEA_ELEMENT_PATH . '/' . $allElements[$i]->name . '/' . $classFile))) {
              require_once FORMEA_ELEMENT_PATH . '/' . $allElements[$i]->name . '/' . $classFile;
              $classFile = str_replace('.php', '', $classFile);
              /** @var FormeaEltype $elementClass */
              $elementClass         = new $classFile();
              $cssFiles             = $elementClass->getAdminLoadableStyle();
              $assets['fileStyles'] = array_merge($assets['fileStyles'], $cssFiles);
            }
          }
        }
      }
    }

    return $assets;
  }
}
