{# templates/mylinks.html #}
{% extends 'base.html' %}

{# page title #}
{% block title %}Ordnerkonfiguration{% endblock %}

{# page content #}
{% block content %}
  <div class="container">
    <h2>Ordnerkonfiguration</h2>
    <div id="records"></div>
    <button id="add-btn" class="btn btn-primary mt-3">Add New Record</button>
  </div>

  <!-- Confirmation Modal -->
  <div class="modal fade" id="confirmDeleteModal" tabindex="-1" aria-labelledby="confirmDeleteLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="confirmDeleteLabel">Confirm Deletion</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          Do you really want to delete this record?
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="button" class="btn btn-danger confirm-delete">Delete</button>
        </div>
      </div>
    </div>
  </div>
{% endblock %}

{% block scripts %}
  <script>
    const ALPHABET = {{ alphabet|tojson }};
    let data = [];
    let editing = new Set();
    let pendingDelete = null;

    // helper to format DD.MM.YYYY → YYYY-MM-DD
    function formatISO(d) {
      const [dd, mm, yyyy] = d.split('.');
      return (dd && mm && yyyy) ? `${yyyy}-${mm}-${dd}` : '';
    }

    // load from server
    async function loadData() {
      try {
        const res = await fetch('/admin/folder_secret_config_editor/data');
        data = await res.json();
        render();
      } catch (err) {
        console.error(err);
      }
    }

    // send delete/update actions
    async function sendAction(payload) {
      await fetch('/admin/folder_secret_config_editor/action', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      await loadData();
    }

    // delete record after confirmation
    function deleteRec(secret) {
      sendAction({ action: 'delete', secret });
    }

    // build all cards
    function render() {
      const cont = document.getElementById('records');
      cont.innerHTML = '';

      data.forEach(rec => {
        const key = rec.secret;
        const isEdit = editing.has(key);
        const expired = (formatISO(rec.validity) && new Date(formatISO(rec.validity)) < new Date());
        const cls = isEdit ? 'unlocked' : 'locked';

        // outer card
        const wrapper = document.createElement('div');
        wrapper.className = 'card mb-3';
        wrapper.dataset.secret = key;

        const body = document.createElement('div');
        body.className = `card-body ${cls}`;

        // header
        const h5 = document.createElement('h5');
        h5.innerHTML = `Link${expired ? ' <span class="text-danger fw-bold"> ! abgelaufen !</span>' : ''}`;
        body.appendChild(h5);

        // secret input
        const secDiv = document.createElement('div');
        secDiv.className = 'mb-2';
        secDiv.innerHTML = `Secret: `;
        const secInput = document.createElement('input');
        secInput.className = 'form-control';
        secInput.type = 'text';
        secInput.value = rec.secret;
        secInput.readOnly = !isEdit;
        secInput.dataset.field = 'secret';
        secDiv.appendChild(secInput);
        body.appendChild(secDiv);

        // validity input
        const valDiv = document.createElement('div');
        valDiv.className = 'mb-2';
        valDiv.innerHTML = `Gültig bis: `;
        const valInput = document.createElement('input');
        valInput.className = 'form-control';
        valInput.type = 'date';
        valInput.value = formatISO(rec.validity);
        valInput.readOnly = !isEdit;
        valInput.dataset.field = 'validity';
        valDiv.appendChild(valInput);
        body.appendChild(valDiv);

        // folders
        const folderHeader = document.createElement('h6');
        folderHeader.textContent = 'Ordner';
        body.appendChild(folderHeader);

        rec.folders.forEach((f, i) => {
          const fwrap = document.createElement('div');
          fwrap.style = 'border:1px solid #ccc; padding:10px; margin-bottom:10px; border-radius:5px;';

          // name
          fwrap.appendChild(document.createTextNode("Ordnername: "));
          const nameGroup = document.createElement('div');
          nameGroup.className = 'input-group mb-2';
          const nameInput = document.createElement('input');
          nameInput.className = 'form-control';
          nameInput.type = 'text';
          nameInput.value = f.foldername;
          nameInput.readOnly = !isEdit;
          nameInput.dataset.field = `foldername-${i}`;
          nameGroup.appendChild(nameInput);

          if (isEdit) {
            const remBtn = document.createElement('button');
            remBtn.className = 'btn btn-outline-danger';
            remBtn.type = 'button';
            remBtn.textContent = 'Remove';
            remBtn.addEventListener('click', () => removeFolder(key, i));
            nameGroup.appendChild(remBtn);
          }
          fwrap.appendChild(nameGroup);

          // path
          fwrap.appendChild(document.createTextNode("Ordnerpfad: "));
          const pathInput = document.createElement('input');
          pathInput.className = 'form-control mb-2';
          pathInput.type = 'text';
          pathInput.value = f.folderpath;
          pathInput.readOnly = !isEdit;
          pathInput.dataset.field = `folderpath-${i}`;
          fwrap.appendChild(pathInput);

          body.appendChild(fwrap);
        });

        if (isEdit) {
          const addFld = document.createElement('button');
          addFld.className = 'btn btn-sm btn-primary mb-2';
          addFld.type = 'button';
          addFld.textContent = 'Add Folder';
          addFld.addEventListener('click', () => addFolder(key));
          body.appendChild(addFld);
        }

        // actions row
        const actions = document.createElement('div');

        if (!isEdit) {
          const openButton = document.createElement('button');
          openButton.className = 'btn btn-secondary btn-sm me-2';
          openButton.onclick = () => window.open(`/?secret=${rec.secret}`, '_self');
          openButton.textContent = 'Link öffnen';
          actions.appendChild(openButton);
        }

        const delBtn = document.createElement('button');
        delBtn.className = 'btn btn-danger btn-sm me-2 delete-btn';
        delBtn.type = 'button';
        delBtn.textContent = 'Delete';
        delBtn.dataset.secret = key;
        actions.appendChild(delBtn);

        const cloneBtn = document.createElement('button');
        cloneBtn.className = 'btn btn-secondary btn-sm me-2';
        cloneBtn.type = 'button';
        cloneBtn.textContent = 'Clone';
        cloneBtn.addEventListener('click', () => cloneRec(key));
        actions.appendChild(cloneBtn);

        if (isEdit) {
          const saveBtn = document.createElement('button');
          saveBtn.className = 'btn btn-success btn-sm';
          saveBtn.type = 'button';
          saveBtn.textContent = 'Save';
          saveBtn.addEventListener('click', () => saveRec(key));
          actions.appendChild(saveBtn);
        } else {
          const editBtn = document.createElement('button');
          editBtn.className = 'btn btn-warning btn-sm';
          editBtn.type = 'button';
          editBtn.textContent = 'Edit';
          editBtn.addEventListener('click', () => editRec(key));
          actions.appendChild(editBtn);
        }

        body.appendChild(actions);
        wrapper.appendChild(body);
        cont.appendChild(wrapper);
      });
    }

    // generate a unique secret
    function generateSecret(existing) {
      let s;
      do {
        s = Array.from({length:32}, () => ALPHABET[Math.floor(Math.random()*ALPHABET.length)]).join('');
      } while (existing.includes(s));
      return s;
    }

    // CRUD helpers
    function editRec(secret) {
      editing.add(secret);
      render();
    }
    function cloneRec(secret) {
      const idx = data.findIndex(r => r.secret === secret);
      const rec = JSON.parse(JSON.stringify(data[idx]));
      const existing = data.map(r => r.secret);
      rec.secret = generateSecret(existing);
      data.splice(idx+1, 0, rec);
      editing.add(rec.secret);
      render();
    }
    function addFolder(secret) {
      data.find(r => r.secret === secret).folders.push({foldername:'', folderpath:''});
      render();
    }
    function removeFolder(secret, i) {
      data.find(r => r.secret === secret).folders.splice(i,1);
      render();
    }

    async function saveRec(secret) {
      const card = document.querySelector(`[data-secret="${secret}"]`);
      const newSecret = card.querySelector('input[data-field="secret"]').value.trim();
      const validity = card.querySelector('input[data-field="validity"]').value;
      const rec = data.find(r => r.secret === secret);
      const folders = rec.folders.map((_, i) => ({
        foldername: card.querySelector(`input[data-field="foldername-${i}"]`).value.trim(),
        folderpath: card.querySelector(`input[data-field="folderpath-${i}"]`).value.trim()
      }));

      if (!newSecret || data.some(r => r.secret !== secret && r.secret === newSecret)) {
        return alert('Secret must be unique and non-empty');
      }
      if (!validity) {
        return alert('Validity required');
      }
      if (folders.some(f => !f.foldername || !f.folderpath)) {
        return alert('Folder entries cannot be empty');
      }

      await sendAction({
        action: 'update',
        oldSecret: secret,
        newSecret,
        validity,
        folders
      });
      editing.delete(secret);
      await loadData();
    }

    // modal handling for delete
    document.addEventListener('click', e => {
      if (e.target.matches('.delete-btn')) {
        pendingDelete = e.target.dataset.secret;
        const modal = new bootstrap.Modal(document.getElementById('confirmDeleteModal'));
        modal.show();
      }
    });
    document.querySelector('.confirm-delete').addEventListener('click', () => {
      if (pendingDelete) deleteRec(pendingDelete);
      pendingDelete = null;
      const modal = bootstrap.Modal.getInstance(document.getElementById('confirmDeleteModal'));
      modal.hide();
    });

    // init
    document.addEventListener('DOMContentLoaded', () => {
      document.getElementById('add-btn').addEventListener('click', () => {
        const existing = data.map(r => r.secret);
        const newSecret = generateSecret(existing);
        data.push({ secret: newSecret, validity: new Date().toISOString().slice(0,10), folders: [] });
        editing.add(newSecret);
        render();
      });
      loadData();
    });
  </script>
{% endblock %}

