<?php

/**
 * @package     Joomla.Site
 * @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\Site\View\Formea;

defined('_JEXEC') or die;

use Exception;
use Joomla\Component\Formea\Site\Libraries\FormeaSubmissionResponse;
use Joomla\Filesystem\Path;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\View\GenericDataException;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\User\User;
use Joomla\CMS\WebAsset\WebAssetManager;
use Joomla\Component\Formea\Site\Helper\FormeaGeneralHelper;
use Joomla\Component\Formea\Site\Libraries\FormeaForm;
use Joomla\Registry\Registry;
use Joomla\Session\SessionInterface;
use stdClass;

/**
 * HTML Formea View class for the Formea component
 *
 * @since  1.0.0
 */
class HtmlView extends BaseHtmlView
{
    /**
     * The page parameters
     *
     * @var    Registry|null
     * @since  1.0.0
     */
    protected $params = null;

    /**
     * The item model state
     *
     * @var    Registry
     * @since  1.0.0
     */
    protected $state;

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

    /**
     * @var User
     * @since 1.0.0
     */
    private $user;

    /**
     * @var FormeaForm
     * @since 1.0.0
     */
    public $form;

    public $renderexExtension = null;

    /**
     * @var FormeaSubmissionResponse | null
     * @since 1.1.3
     */
    public $submissionData = null;


    /**
     * Execute and display a template script.
     *
     * @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)
    {
        $app = Factory::getApplication();
        $item = $this->get('Item');

        $this->user = $this->getCurrentUser();
        //check if user has access
        $groups = $this->user->getAuthorisedViewLevels();
        if (!in_array($item->access_level, $groups)) {
            $return = base64_encode(Uri::getInstance());
            $login_url_with_return = Route::_('index.php?option=com_users&view=login&return=' . $return);
            $app->enqueueMessage(Text::_('JERROR_ALERTNOAUTHOR'), 'notice');
            $app->redirect($login_url_with_return, 403);
        }
        $state = $this->state = $this->get('State');
        $params = $this->params = $state->get('params');
        // Check for errors.
        if (count($errors = $this->get('Errors'))) {
            throw new GenericDataException(implode("\n", $errors), 500);
        }

        $itemparams = $item->params;

        $temp = clone $params;
        $temp->merge($itemparams);
        $formClass = new FormeaForm(['id' => $item->id]);
        $this->item = $formClass->getObject();
        $this->item->params = $temp;

        $this->form = $formClass;
        $this->item->details = $formClass->getDetails();
        $this->item->themes = $formClass->getThemes();
        $this->item->elementLayouts = $formClass->getPages();
        //TODO:Update dispatcher see form module
        /*Factory::getApplication()->triggerEvent('onContentPrepare', array('com_formea.formea', &$item));

            // Store the events for later
            $item->event                    = new stdClass;
            $results                        = Factory::getApplication()->triggerEvent('onContentAfterTitle', array('com_formea.formea', &$item, &$item->params));
            $item->event->afterDisplayTitle = trim(implode("\n", $results));

            $results                           = Factory::getApplication()->triggerEvent('onContentBeforeDisplay', array('com_formea.formea', &$item, &$item->params));
            $item->event->beforeDisplayContent = trim(implode("\n", $results));

            $results                          = Factory::getApplication()->triggerEvent('onContentAfterDisplay', array('com_formea.formea', &$item, &$item->params));
            $item->event->afterDisplayContent = trim(implode("\n", $results));*/

        //clear the submitted data for when page reloads
        /** @var SessionInterface $session */
        $session = Factory::getApplication()->getSession();
        $submittedData = $session->get('FORMEA_FORM_SUBMISSION_' . $item->id);

        if (!empty($submittedData)) {
            $this->submissionData = $submittedData;
            $session->remove('FORMEA_FORM_SUBMISSION_' . $item->id);
        }

        $additionalCssFiles = [];
        $additionalJSFiles = [];
        $additionalCss = '';
        $additionalJS = '';

        $elementAssets = $this->form->getAllAssets();


        $totalCssFiles = count($elementAssets->fileStyles);
        for ($i = 0; $i < $totalCssFiles; $i++) {
            $additionalCssFiles[] = $elementAssets->fileStyles[$i];
        }
        $totalJsFiles = count($elementAssets->fileScripts);
        for ($i = 0; $i < $totalJsFiles; $i++) {
            $additionalJSFiles[] = $elementAssets->fileScripts[$i];
        }
        $totalInlineScripts = count($elementAssets->inlineScripts);
        for ($i = 0; $i < $totalInlineScripts; $i++) {
            $additionalJS .= $elementAssets->inlineScripts[$i];
        }
        $totalInlineStyles = count($elementAssets->inlineStyles);
        for ($i = 0; $i < $totalInlineStyles; $i++) {
            $additionalCss .= $elementAssets->inlineStyles[$i];
        }
        if ($this->item->form_type > 0) {
            $renderer_id = $this->item->params->get('renderer_id', 0);
            if ($renderer_id > 0) {
                $rendererExtension = FormeaGeneralHelper::getCoreExtension($renderer_id, 1, 1);
                if (!empty($rendererExtension)) {
                    $this->renderexExtension = $rendererExtension;
                    $rendererFile = 'Formea' . $rendererExtension->name . '.php';
                    $rendererDirectory = JPATH_ROOT . '/components/com_formea/plugins/core/' . $rendererExtension->name . '/';
                    if (is_file(Path::clean($rendererDirectory . $rendererFile))) {
                        $this->addTemplatePath($rendererDirectory . 'tmpl/');
                    }
                }
            }
        }
        $this->_setDocument($additionalCss, $additionalJS, $additionalCssFiles, $additionalJSFiles);

        return parent::display($tpl);
    }

    /**
     * @param $additionalCssFiles
     * @param $additionalJSFiles
     *
     *
     * @throws Exception
     * @since 1.0.0
     */
    protected function _setDocument($additionalCss = '', $additionalJS = '', $additionalCssFiles = [], $additionalJSFiles = [])
    {
        $app = Factory::getApplication();
        /** @var WebAssetManager $wa */
        $wa = $app->getDocument()->getWebAssetManager();
        $csrf = Session::getFormToken();
        $formeaOption = [
            'oid' => $csrf,
            'base_url' => Uri::base()
        ];
        $wa->addInlineScript('var FormeaOption = ' . json_encode($formeaOption) . ';');

        if (!empty($additionalJS)) {
            $wa->addInlineScript($additionalJS);
        }
        if (!empty($additionalCss)) {
            $wa->addInlineStyle($additionalCss);
        }
        if (!empty($this->item->inline_css)) {
            $wa->addInlineStyle($this->item->inline_css);
        }
        if (!empty($additionalJSFiles)) {
            $totalAdditionalJsFile = count($additionalJSFiles);
            for ($j = 0; $j < $totalAdditionalJsFile; $j++) {
                $wa->useScript($additionalJSFiles[$j]);
            }
        }
        if (!empty($additionalCssFiles)) {
            $totalAdditionalCssFile = count($additionalCssFiles);
            for ($j = 0; $j < $totalAdditionalCssFile; $j++) {
                $wa->useStyle($additionalCssFiles[$j]);
            }
        }
    }
}
