<?php
  /**
   * @package     Formea.Plugin
   * @subpackage  Core.Pdf
   *
   * @copyright   Copyright (C) 2010-2024 Feseur Sdn Bhd. All rights reserved.
   * @license     GNU General Public License version 2 or later; see LICENSE.txt
   */

  namespace Joomla\Component\Formea\Plugins\Core\Pdf\Field;

  use Joomla\CMS\Factory;
  use Joomla\CMS\Form\FormField;
  use Joomla\CMS\Form\FormHelper;
  use Joomla\CMS\Language\Text;
  use Joomla\CMS\Uri\Uri;
  use Joomla\CMS\Version;
  use Joomla\CMS\WebAsset\WebAssetManager;
  use Joomla\Registry\Registry;
  use Joomla\Session\SessionInterface;

  class FormeaCorePdfPreviewField extends FormField
  {
    /**
     * The name field type.
     *
     * @var    string
     */
    protected $type = 'FormeaCorePdfPreview';

    private $app;


    public function __construct($form = null)
    {
      parent::__construct($form);
      $this->app = Factory::getApplication();
      /** @var WebAssetManager $wa */
      $wa = $this->app->getDocument()->getWebAssetManager();

      // Get the Joomla version
      $version        = new Version();
      $currentVersion = $version->getShortVersion();

      // Check if the version is less than 5.0.0
      if (version_compare($currentVersion, '5.0.0', '<'))
      {
        // Beware, we're dealing with legacy deprecated code
        $wa->useScript('com_formea.core.Pdf.previewField-j4');
      }
      else
      {
        // J5
        $wa->useScript('com_formea.core.Pdf.previewField');
      }
    }

    protected function getLabel()
    {
      return '';
    }

    /**
     * Method to get the field input markup for the file field.
     * Field attributes allow specification of a maximum file size and a string
     * of accepted file extensions.
     *
     * @return  string  The field input markup.
     *
     * @note    The field does not include an upload mechanism.
     * @see     \Joomla\CMS\Form\Field\MediaField
     * @since   1.7.0
     */
    protected function getInput()
    {
      $rootUrl = Uri::root();
      /** @var SessionInterface $session */
      $session = $this->app->getSession();
      $token = $session->getFormToken();
      return '<button type="button" class="btn btn-success" onclick="FormeaPdfPreviewField.generatePdf(event,\''.$token.'\')">'.Text::_('FORMEA_PDF_TEST_GENERATE').'</button>';
    }

    /**
     * Method to get a control group with label and input.
     *
     * @param   array  $options  Options to be passed into the rendering of the field
     *
     * @return  string  A string containing the html for the control group
     *
     * @since   3.2
     */
    public function renderField($options = [])
    {
      return $this->getInput();
    }


  }
