<?php
\defined('_JEXEC') or die;

use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Language\Text;

$hasTree = !empty($this->treeHtml);

// ACL-Daten aus der View (für Vorbelegung im Formular)
$viewLevels = method_exists($this, 'getViewLevels') ? (array) $this->getViewLevels() : [];
$aclMap     = method_exists($this, 'getFolderAccess') ? (array) $this->getFolderAccess() : [];
?>
<style>
  /* Layout */
  .eis-flex{display:flex;gap:1rem;align-items:flex-start}
  .eis-tree-wrap{flex:1 1 auto;background:#f9f9f9;border:1px solid #ddd;border-radius:6px;padding:1em}
  .eis-edit{flex:0 0 360px;background:#fff;border:1px solid #ddd;border-radius:6px;padding:1em}
  .eis-edit h4{margin:.2rem 0 1rem}

  /* Baum */
  .pdf-tree{list-style:none;margin:0;padding:0}
  .pdf-tree ul{list-style:none;margin-left:1.25em;padding:0;display:none}
  .pdf-tree li{margin:.35em 0}
  .folder>.toggle{cursor:pointer;width:1.25em;display:inline-block;user-select:none}
  .folder>.folder-label,.file>.file-label{cursor:pointer;user-select:none}
  .pdf-tree .meta{color:#666}
  .pdf-tree .count{color:#999}
  .pdf-tree .is-selected{background:rgba(0,0,0,.06);border-radius:3px}

  /* Steuerleiste */
  .controls{margin-bottom:.75em}
  .controls button{margin-right:.5em}

  /* Form */
  .control-group{margin-bottom:.6rem}
  .form-help{color:#666;font-size:.9em}
</style>

<!-- Scan-Formular -->
<form action="<?php echo Route::_('index.php?option=com_eis&task=display.scan'); ?>" method="post" id="eis-scan-form">
  <fieldset class="adminform">
    <legend><?php echo Text::_('COM_EIS_DOCUMENT_PATH'); ?></legend>
    <div class="form-help"><?php echo Text::_('COM_EIS_SETTINGS_TITLE'); ?> · <?php echo Text::_('COM_EIS_FIELD_DOCUMENT_ROOT_LABEL'); ?></div>
  </fieldset>
  <div class="mt-2">
    <button class="btn btn-primary" type="submit">
      <?php echo Text::_('COM_EIS_SCAN_DOCUMENTS'); ?>
    </button>
  </div>
  <?php echo HTMLHelper::_('form.token'); ?>
</form>

<hr>

<?php if (!$hasTree): ?>
  <p class="text-muted">
    <?php echo Text::_('COM_EIS_NO_DOCUMENTS_FOUND'); ?>
  </p>
<?php else: ?>

  <h3 class="mt-3"><?php echo Text::_('COM_EIS_PDF_TREE'); ?></h3>

  <div class="eis-flex">

    <!-- Linke Seite: Baum -->
    <div class="eis-tree-wrap">
      <div class="controls">
        <button id="eis-expand-all" type="button" class="btn btn-sm btn-secondary">
          <?php echo Text::_('COM_EIS_EXPAND_ALL'); ?>
        </button>
        <button id="eis-collapse-all" type="button" class="btn btn-sm btn-secondary">
          <?php echo Text::_('COM_EIS_COLLAPSE_ALL'); ?>
        </button>
      </div>

      <div class="tree" id="eis-tree" role="tree" aria-label="<?php echo Text::_('COM_EIS_PDF_TREE'); ?>">
        <?php echo $this->treeHtml; ?>
      </div>
    </div>

    <!-- Rechte Seite: Inline-Bearbeitung + ACL -->
    <div class="eis-edit">
      <h4><?php echo Text::_('COM_EIS_EDIT_TITLE') ?: 'Anzeigename bearbeiten'; ?></h4>

      <form action="<?php echo Route::_('index.php?option=com_eis&task=display.rename'); ?>" method="post" id="eis-rename-form" novalidate>
        <div class="control-group">
          <label for="eis-current-name"><?php echo Text::_('COM_EIS_FIELD_NAME') ?: 'Originalname'; ?></label>
          <input type="text" id="eis-current-name" class="form-control" value="" readonly>
        </div>

        <div class="control-group">
          <label for="eis-title"><?php echo Text::_('COM_EIS_FIELD_TITLE') ?: 'Anzeigename (optional)'; ?></label>
          <input type="text" name="title" id="eis-title" class="form-control" value=""
                 placeholder="<?php echo Text::_('COM_EIS_PLACEHOLDER_TITLE') ?: 'Leer lassen = automatisch aus Dateiname'; ?>">
          <div class="form-help"><?php echo Text::_('COM_EIS_FILESIZE'); ?>: <span id="eis-filesize">–</span></div>
        </div>

        <input type="hidden" name="id" id="eis-id" value="">

        <div class="mt-2">
          <button type="submit" class="btn btn-success" id="eis-save" disabled>
            <?php echo Text::_('JSAVE'); ?>
          </button>
          <button type="button" id="eis-clear-title" class="btn btn-light" disabled>
            <?php echo Text::_('JDEFAULT') ?: 'Zurücksetzen'; ?>
          </button>
        </div>

        <?php echo HTMLHelper::_('form.token'); ?>
      </form>

      <!-- ===== ACL: Zugriff (Top-Level-Ordner) ===== -->
      <hr style="margin:1rem 0">

      <h4><?php echo Text::_('COM_EIS_ACCESS_TITLE') ?: 'Zugriff (Top-Level-Ordner)'; ?></h4>

      <form action="<?php echo Route::_('index.php?option=com_eis&task=display.saveAccess'); ?>"
            method="post" id="eis-access-form">
        <div class="control-group">
          <label for="eis-folder-viewlevel">
            <?php echo Text::_('COM_EIS_FIELD_VIEWLEVEL') ?: 'Zugriffsebene'; ?>
          </label>
          <select name="viewlevel_id" id="eis-folder-viewlevel" class="form-control">
            <option value="0">(Öffentlich)</option>
            <?php foreach ($viewLevels as $vl): ?>
              <option value="<?php echo (int)$vl['id']; ?>">
                <?php echo htmlspecialchars($vl['title'], ENT_QUOTES, 'UTF-8'); ?>
              </option>
            <?php endforeach; ?>
          </select>
          <div class="form-help">
            <?php echo Text::_('COM_EIS_ACCESS_HELP') ?: 'Nur für Ordner der ersten Ebene. Unterordner und Dateien erben die Einstellung.'; ?>
          </div>
        </div>

        <input type="hidden" name="folder_id" id="eis-folder-id" value="">
        <?php echo HTMLHelper::_('form.token'); ?>

        <div class="mt-2">
          <button type="submit" class="btn btn-secondary" id="eis-access-save" disabled>
            <?php echo Text::_('JSAVE'); ?>
          </button>
        </div>
      </form>
      <!-- ===== /ACL ===== -->
    </div>
  </div>

  <script>
    (function(){
      const tree    = document.getElementById('eis-tree');
      const form    = document.getElementById('eis-rename-form');
      const idFld   = document.getElementById('eis-id');
      const nameFld = document.getElementById('eis-current-name');
      const titleFld= document.getElementById('eis-title');
      const sizeOut = document.getElementById('eis-filesize');
      const btnSave = document.getElementById('eis-save');
      const btnClr  = document.getElementById('eis-clear-title');

      // ACL-Form Elemente
      const aclForm     = document.getElementById('eis-access-form');
      const aclFolderId = document.getElementById('eis-folder-id');
      const aclSelect   = document.getElementById('eis-folder-viewlevel');
      const aclBtn      = document.getElementById('eis-access-save');

      // PHP-Map folder_id => viewlevel_id an JS übergeben
      const ACL_MAP = <?php echo json_encode($aclMap, JSON_UNESCAPED_SLASHES); ?>;

      if (!tree) return;

      let lastSelected;

      // Helper: prüfen, ob li.folder Top-Level ist
      function isTopLevelFolder(li){
        if (!li) return false;
        const parentLi = li.parentElement ? li.parentElement.closest('li.folder') : null;
        return !parentLi; // kein übergeordneter <li.folder>
      }

      // Toggle (Caret) & Auswahl
      tree.addEventListener('click', (e) => {
        const t = e.target;

        // Ein-/Ausklappen
        if (t.classList.contains('toggle') || t.classList.contains('folder-label')) {
          const li = t.closest('li.folder');
          if (li) {
            const childUl = li.querySelector(':scope > ul');
            if (childUl) {
              const open = childUl.style.display === 'block';
              childUl.style.display = open ? 'none' : 'block';
              const caret = li.querySelector(':scope > .toggle');
              if (caret) caret.textContent = open ? '▶' : '▼';
            }
          }
        }

        // Auswahl für Bearbeitung (Ordner- oder Datei-Label)
        if (t.classList.contains('folder-label') || t.classList.contains('file-label')) {
          const li = t.closest('li');
          if (!li) return;

          // Visuelles Highlight
          if (lastSelected) lastSelected.classList.remove('is-selected');
          t.classList.add('is-selected');
          lastSelected = t;

          // Daten aus data-Attributen
          const id    = li.getAttribute('data-id') || '';
          const title = li.getAttribute('data-title') || '';
          const name  = li.getAttribute('data-name') || '';
          const size  = li.getAttribute('data-size') || ''; // optional

          idFld.value   = id;
          nameFld.value = name;
          titleFld.value= title;
          sizeOut.textContent = size || '–';

          btnSave.disabled = !id;
          btnClr.disabled  = !id;

          // ACL-Form: nur bei Top-Level-Ordner aktivieren und vorbelegen
          if (li.classList.contains('folder') && isTopLevelFolder(li)) {
            aclFolderId.value = id || '';
            aclBtn.disabled = !aclFolderId.value;
            // vorwählen
            const current = (id && ACL_MAP[id]) ? String(ACL_MAP[id]) : '0';
            if (aclSelect) {
              for (const opt of aclSelect.options) {
                opt.selected = (opt.value === current);
              }
            }
          } else {
            // kein Top-Level -> ACL-Form deaktivieren
            aclFolderId.value = '';
            aclBtn.disabled = true;
          }

          // Fokus ins Titel-Feld
          titleFld.focus();
        }
      });

      // „Zurücksetzen“ = Titel leeren
      btnClr?.addEventListener('click', () => {
        titleFld.value = '';
        titleFld.focus();
      });

      // Global: Aus-/Einklappen
      document.getElementById('eis-expand-all')?.addEventListener('click', () => {
        document.querySelectorAll('.pdf-tree ul').forEach(ul => ul.style.display = 'block');
        document.querySelectorAll('.pdf-tree .toggle').forEach(t => t.textContent = '▼');
      });
      document.getElementById('eis-collapse-all')?.addEventListener('click', () => {
        document.querySelectorAll('.pdf-tree ul').forEach(ul => ul.style.display = 'none');
        document.querySelectorAll('.pdf-tree .toggle').forEach(t => t.textContent = '▶');
      });
    })();
  </script>

<?php endif; ?>
