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

defined('_JEXEC') or die;

use Exception;
use Joomla\CMS\Factory;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;
use Joomla\CMS\WebAsset\WebAssetManager;
use Joomla\Component\Formea\Site\Libraries\FormeaSubmissionResponse;

/**
 * HTML Formea View class for the Formea component
 *
 * @since  1.0.0
 */
class HtmlView extends BaseHtmlView
{
  /**
   * @var FormeaSubmissionResponse | null
   * @since 1.1.7
   */
  public $submissionResponse = null;
  public $formId = 0;

  /**
   * 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();
    $this->formId = $app->getInput()->getInt('id', 0);
    if ($this->formId > 0) {
      $session                 = $app->getSession();
      $_formSubmissionResponse = $session->get('FORMEA_FORM_SUBMISSION_' . $this->formId);
      if (!empty($_formSubmissionResponse)) {
        $this->submissionResponse = $_formSubmissionResponse;
        $this->_setDocs();
      }
    }

    return parent::display($tpl);
  }

  protected function _setDocs()
  {
    $app = Factory::getApplication();
    /** @var WebAssetManager $wa */
    $wa = $app->getDocument()->getWebAssetManager();
    $js = '';
    $js .= "document.addEventListener('DOMContentLoaded', function () {";
    $js .= "    var redirectForm = document.getElementById('formeaRedirectForm');";
    $js .= "    if(redirectForm){";
    $js .= "      redirectForm.submit();";
    $js .= "    }";
    $js .= "  });";
    $wa->addInlineScript($js);
  }
}
