<?php
declare(strict_types=1);

/**
ET-Chat Copyright by SEDesign | ET-Chat v3.x.x Lizenz: CCPL | Autor: Evgeni Tcherkasski (info@s-e-d.de)
ET-Chat_T-FISH-MOD Weiterentwicklungen, Optimierungen und Ergänzungen am Code sind das geistige Eigentum von Tommy (Thomas Kuhn) und Harlekin (Bernd Witte).

Die darauf folgende Optimierungen und Ergänzungen am Code sind das Geistige Eigentum von Powermen (Christian K.)
und wird unter der Namenserweiterung M.C.v.x.x.x. geführt. 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
 */

function e(string $v): string {
    return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}

ob_start();
?>

<?php if (!empty($saved)): ?>
<div id="successBanner">
	<div class="success-banner" id="successBanner"><span>Änderungen wurden erfolgreich gespeichert.</span>
				<span class="close-btn" onclick="closeSuccessBanner()">✖</span>
	</div>
</div>
<?php endif; ?>

<form method="post" id="adminForm" class="admin-form-box">

<input type="hidden" name="csrf_token" value="<?= e($csrfToken ?? '') ?>">

<table class="admin-table" id="bewerbungsTable">
<thead>
<tr>
    <th></th>
    <th>Label</th>
    <th>Typ</th>
    <th>Sichtbar</th>
    <th>Pflicht</th>
    <th>Optionen</th>
    <th>Aktion</th>
</tr>
</thead>

<tbody>
<?php if (!empty($felder)): ?>
<?php foreach ($felder as $feld):
    $id = (int)$feld['etchat_id'];
    $type = $feld['etchat_field_type'];
?>
<tr data-id="<?= $id ?>">

<td><span class="drag-handle">☰</span></td>

<td>
<input type="text" name="label[<?= $id ?>]" value="<?= e($feld['etchat_field_name']) ?>">
</td>

<td><?= e($type) ?></td>

<td>
<input type="checkbox" name="sichtbar[<?= $id ?>]" value="1" <?= $feld['etchat_visible']?'checked':'' ?>>
</td>

<td>
<input type="checkbox" name="pflicht[<?= $id ?>]" value="1" <?= $feld['etchat_required']?'checked':'' ?>>
</td>

<td>
<?php if (in_array($type, ['select','checkbox'], true)):
    $opt = json_decode($feld['etchat_options'] ?? '', true) ?: [];
?>
<textarea name="optionen[<?= $id ?>]"><?= e(implode("\n", $opt)) ?></textarea>
<?php endif; ?>
</td>

<td>
<?php if ($feld['etchat_custom']): ?>
<a href="?AdminKontaktform&delete=<?= $id ?>&csrf_token=<?= e($csrfToken) ?>"
   onclick="return confirm('Dieses Feld wirklich löschen?')">
   Löschen
</a>
<?php endif; ?>
</td>

</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>

<hr>

<h3>Neues Feld hinzufügen</h3>

<input type="text" name="new_label" placeholder="Label">

<select name="new_type">
    <option value="text">Text</option>
    <option value="textarea">Textarea</option>
    <option value="email">E-Mail</option>
    <option value="date">Datum</option>
    <option value="select">Select</option>
    <option value="checkbox">Checkbox</option>
</select>

Sichtbar <input type="checkbox" name="new_visible" checked>
Pflicht <input type="checkbox" name="new_required">

<br><br>

<textarea class="admin-textarea-medium" name="new_options" placeholder="Optionen je Zeile"></textarea>

<input type="hidden" name="order" id="orderInput">

<br><br>

<button type="submit">Speichern</button>

</form>

<?php
$extraScripts = <<<JS
<script>
// IDENTISCH übernommen (Drag & Drop + Warnung)
const tableBody = document.querySelector("#bewerbungsTable tbody");
let dragSrcEl = null;
let formChanged = false;

tableBody.addEventListener('mousedown', e => {
    if(e.target.classList.contains('drag-handle')){
        const row = e.target.closest('tr');
        if(row) row.draggable = true;
    }
});

tableBody.addEventListener('dragstart', e => {
    dragSrcEl = e.target.closest('tr');
    dragSrcEl.classList.add('dragging');
});

tableBody.addEventListener('dragover', e => {
    e.preventDefault();
    const target = e.target.closest('tr');
    if(target && target !== dragSrcEl){
        const rect = target.getBoundingClientRect();
        const next = (e.clientY - rect.top) > rect.height/2;
        tableBody.insertBefore(dragSrcEl, next ? target.nextSibling : target);
    }
});

tableBody.addEventListener('dragend', () => {
    dragSrcEl.classList.remove('dragging');
    dragSrcEl.draggable = false;
    updateOrder();
});

function updateOrder(){
    const order = [];
    tableBody.querySelectorAll('tr').forEach(row => {
        if(row.dataset.id) order.push(row.dataset.id);
    });
    document.getElementById('orderInput').value = order.join(',');
    formChanged = true;
}

document.querySelectorAll("input, textarea, select").forEach(el => {
    el.addEventListener("input", () => formChanged = true);
    el.addEventListener("change", () => formChanged = true);
});

window.addEventListener("beforeunload", e => {
    if(formChanged){
        e.preventDefault();
        e.returnValue = '';
    }
});

document.getElementById('adminForm').addEventListener("submit", () => {
    formChanged = false;
});
</script>

<script>
window.addEventListener('DOMContentLoaded', () => {
    const banner = document.getElementById("successBanner");
    if (banner) {
        setTimeout(() => {
            banner.style.display = "none";
        }, 5000);
    }
});

function closeSuccessBanner() {
    const banner = document.getElementById("successBanner");
    if (banner) banner.style.display = "none";
}
</script>

JS;

$content = ob_get_clean();

$pageTitle = 'Kontaktformular bearbeiten';
$backLink  = './?AdminKontakt';
$footerNote = '';

include __DIR__ . '/admin_master_template.php';