<?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
 * @since       1.2.0
 * @version     1.3.0
 */

namespace Joomla\Component\Formea\Administrator\Field;


use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Form\FormField;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Version;
use Joomla\CMS\WebAsset\WebAssetManager;

class FormeaAttachmentsField extends FormField
{
  /**
   * The form field type.
   *
   * @var    string
   * @since  1.2.0
   */
  public $type = 'FormeaAttachments';
  private $app;

  private $isLegacy = false;

  public function __construct($form = null)
  {
    parent::__construct($form);
    $this->app = Factory::getApplication();

    /** @var WebAssetManager $wa */
    $wa = $this->app->getDocument()->getWebAssetManager();
    $wa->useStyle('com_formea.field-attachments');

    // 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.field-attachments-j4');
      $this->isLegacy = true;
    } else {
      // J5
      $wa->useScript('com_formea.field-attachments');
    }


    $this->prepareDocs();
  }

  public function getInput()
  {
    $formId  = $this->getAttribute('form-id');
    $value   = $this->value;
    //$lang    = 'en-GB';
    $lang    = $this->app->getLanguage()->getTag();
    $emailId = 0;
    if (strlen($value) > 0) {
      $split = explode('|#|', $value);
      if (count($split) == 2) {
        $emailId = $split[0];
        $lang    = $split[1];
      }
    }

    $baseUrl = Uri::base();
    $session = $this->app->getSession();
    $csrf    = $session->getFormToken();
    $html    = '';
    $html    .= '
       <formea-attachments
        id="' . $this->id . '"
        base-url="' . $baseUrl . '"
        csrf-token="' . $csrf . '"
        form-id="' . $formId . '"
        email-id="' . $emailId . '"
        lang="' . $lang . '"
        name="' . $this->name . '"
      ></formea-attachments>
      ';

    if ($this->isLegacy) {
      $legacyId = 'attachmentMediaModal_' . $this->id;
      $url = 'index.php?option=com_media&view=media&tmpl=component';
      $modalHTML = HTMLHelper::_(
        'bootstrap.renderModal',
        $legacyId,
        [
          'url'         => $url,
          'title'       => Text::_('COM_FORMEA_SELECT_MEDIA'),
          'closeButton' => true,
          'height'      => '100%',
          'width'       => '100%',
          'modalWidth'  => '80',
          'bodyHeight'  => '60',
          'footer'      => '<button type="button" class="btn btn-success" id="' . $legacyId . '_media_select" >' . Text::_('JSELECT') . '</button>'
            . '<button type="button" class="btn btn-secondary" id="' . $legacyId . '_media_close">' . Text::_('JCANCEL') . '</button>',
        ]
      );
      $html .= $modalHTML;
    }

    return $html;
  }

  private function prepareDocs()
  {
    $imagesExt    = array_map(
      'trim',
      explode(
        ',',
        ComponentHelper::getParams('com_media')->get(
          'image_extensions',
          'bmp,gif,jpg,jpeg,png,webp'
        )
      )
    );
    $audiosExt    = array_map(
      'trim',
      explode(
        ',',
        ComponentHelper::getParams('com_media')->get(
          'audio_extensions',
          'mp3,m4a,mp4a,ogg'
        )
      )
    );
    $videosExt    = array_map(
      'trim',
      explode(
        ',',
        ComponentHelper::getParams('com_media')->get(
          'video_extensions',
          'mp4,mp4v,mpeg,mov,webm'
        )
      )
    );
    $documentsExt = array_map(
      'trim',
      explode(
        ',',
        ComponentHelper::getParams('com_media')->get(
          'doc_extensions',
          'doc,odg,odp,ods,odt,pdf,ppt,txt,xcf,xls,csv'
        )
      )
    );

    $doc = $this->app->getDocument();
    $doc->addScriptOptions('media-picker-api', ['apiBaseUrl' => Uri::base(true) . '/index.php?option=com_media&format=json']);
    if (!$doc->getScriptOptions('media-picker')) {
      $doc->addScriptOptions('media-picker', [
        'images'    => $imagesExt,
        'audios'    => $audiosExt,
        'videos'    => $videosExt,
        'documents' => $documentsExt,
      ]);
    }


    Text::script('JSELECT');
    Text::script('COM_FORMEA_SELECT_MEDIA');
    Text::script('JCLOSE');
    Text::script('JFIELD_MEDIA_LAZY_LABEL');
    Text::script('JFIELD_MEDIA_ALT_LABEL');
    Text::script('JFIELD_MEDIA_ALT_CHECK_LABEL');
    Text::script('JFIELD_MEDIA_ALT_CHECK_DESC_LABEL');
    Text::script('JFIELD_MEDIA_CLASS_LABEL');
    Text::script('JFIELD_MEDIA_FIGURE_CLASS_LABEL');
    Text::script('JFIELD_MEDIA_FIGURE_CAPTION_LABEL');
    Text::script('JFIELD_MEDIA_LAZY_LABEL');
    Text::script('JFIELD_MEDIA_SUMMARY_LABEL');
    Text::script('JFIELD_MEDIA_EMBED_CHECK_DESC_LABEL');
    Text::script('JFIELD_MEDIA_DOWNLOAD_CHECK_DESC_LABEL');
    Text::script('JFIELD_MEDIA_DOWNLOAD_CHECK_LABEL');
    Text::script('JFIELD_MEDIA_EMBED_CHECK_LABEL');
    Text::script('JFIELD_MEDIA_WIDTH_LABEL');
    Text::script('JFIELD_MEDIA_TITLE_LABEL');
    Text::script('JFIELD_MEDIA_HEIGHT_LABEL');
    Text::script('JFIELD_MEDIA_UNSUPPORTED');
    Text::script('JFIELD_MEDIA_DOWNLOAD_FILE');
    Text::script('JLIB_APPLICATION_ERROR_SERVER');
    Text::script('JLIB_FORM_MEDIA_PREVIEW_EMPTY', true);
  }
}
