<?php
require_once '../includes/auth.php';
if (!checkPermission('admin')) {
    header('Location: ../dashboard.php');
    exit;
}
$sous_dossier_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$sous_dossier_id) {
    header('Location: ../dashboard.php');
    exit;
}
require_once '../config/database.php';
require_once '../includes/functions.php';

$pdo = getPDO();

$stmt = $pdo->prepare("SELECT sd.*, d.nom as dossier_nom, p.nom as projet_nom FROM sous_dossiers sd
                       JOIN dossiers d ON sd.dossier_id = d.id
                       JOIN projets p ON d.projet_id = p.id
                       WHERE sd.id = ?");
$stmt->execute([$sous_dossier_id]);
$sous_dossier = $stmt->fetch();
if (!$sous_dossier) {
    $_SESSION['error'] = "Sous-dossier introuvable.";
    header('Location: ../dashboard.php');
    exit;
}

$stmt = $pdo->prepare("SELECT contenu_template FROM templates WHERE sous_dossier_id = ?");
$stmt->execute([$sous_dossier_id]);
$template = $stmt->fetch();
if ($template && !empty($template['contenu_template'])) {
    $contenu = json_decode($template['contenu_template'], true);
} else {
    $contenu = [
        'en_tete' => [
            ['label' => 'Chantier', 'type' => 'text', 'name' => 'chantier', 'options' => []],
            ['label' => 'Date', 'type' => 'date', 'name' => 'date_controle', 'options' => []],
            ['label' => 'Intervenant', 'type' => 'text', 'name' => 'intervenant', 'options' => []]
        ],
        'tableau' => [
            'colonnes' => [
                ['label' => 'C', 'type' => 'radio', 'options' => ['C', 'NC', 'NA'], 'need_explanation' => false],
                ['label' => 'Observation', 'type' => 'text', 'options' => []]
            ],
            'lignes' => ['Point 1', 'Point 2', 'Point 3']
        ]
    ];
}

// Normalisation
if (!is_array($contenu)) $contenu = [];
if (!isset($contenu['en_tete']) || !is_array($contenu['en_tete'])) $contenu['en_tete'] = [];
if (!isset($contenu['tableau']) || !is_array($contenu['tableau'])) $contenu['tableau'] = [];
if (!isset($contenu['tableau']['colonnes']) || !is_array($contenu['tableau']['colonnes'])) $contenu['tableau']['colonnes'] = [];
if (!isset($contenu['tableau']['lignes']) || !is_array($contenu['tableau']['lignes'])) $contenu['tableau']['lignes'] = [];

foreach ($contenu['tableau']['colonnes'] as &$col) {
    if (!isset($col['options'])) $col['options'] = [];
    if (!isset($col['need_explanation'])) $col['need_explanation'] = false;
}
unset($col);

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $template_json = $_POST['template_json'] ?? '';
    if (empty($template_json)) {
        $error = "Données du template invalides.";
    } else {
        try {
            $decoded = json_decode($template_json, true);
            if (!is_array($decoded)) throw new Exception("JSON invalide");
            $stmt = $pdo->prepare("INSERT INTO templates (sous_dossier_id, contenu_template) VALUES (?, ?) ON DUPLICATE KEY UPDATE contenu_template = ?");
            $stmt->execute([$sous_dossier_id, $template_json, $template_json]);
            logAction($pdo, $_SESSION['user_id'], 'edit_template', "Template du sous-dossier $sous_dossier_id modifié");
            $success = "Template enregistré.";
            $contenu = $decoded;
        } catch (Exception $e) {
            $error = "Erreur : " . $e->getMessage();
        }
    }
}

// Récupération des autres sous-dossiers pour la copie
$stmt = $pdo->prepare("SELECT sd.id, sd.nom as sous_dossier_nom, d.nom as dossier_nom, p.nom as projet_nom
                       FROM sous_dossiers sd
                       JOIN dossiers d ON sd.dossier_id = d.id
                       JOIN projets p ON d.projet_id = p.id
                       WHERE sd.id != ?
                       ORDER BY p.nom, d.nom, sd.nom");
$stmt->execute([$sous_dossier_id]);
$autres_sous_dossiers = $stmt->fetchAll();

require_once '../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="fas fa-edit me-2"></i>Éditer le template</h1>
    <div>
        <a href="creer_sous_dossier_rapide.php" class="btn btn-info me-2">
            <i class="fas fa-bolt"></i> Création rapide
        </a>
        <button type="button" class="btn btn-secondary me-2" data-bs-toggle="modal" data-bs-target="#loadLibraryModal">
            <i class="fas fa-database"></i> Charger depuis bibliothèque
        </button>
        <a href="../dashboard.php" class="btn btn-outline-secondary">Retour</a>
    </div>
</div>
<div class="alert alert-info">
    <i class="fas fa-info-circle me-2"></i>
    Sous-dossier : <strong><?= htmlspecialchars($sous_dossier['nom']) ?></strong><br>
    Dossier : <?= htmlspecialchars($sous_dossier['dossier_nom']) ?> | Projet : <?= htmlspecialchars($sous_dossier['projet_nom']) ?>
</div>

<?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>

<!-- Modal : Charger depuis bibliothèque -->
<div class="modal fade" id="loadLibraryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-secondary text-white">
                <h5 class="modal-title"><i class="fas fa-database"></i> Charger un template de la bibliothèque</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <select id="librarySelect" class="form-select">
                    <option value="">-- Choisir un template --</option>
                    <?php
                    $libs = $pdo->query("SELECT id, nom FROM templates_library ORDER BY nom")->fetchAll();
                    foreach ($libs as $lib) {
                        echo '<option value="' . $lib['id'] . '">' . htmlspecialchars($lib['nom']) . '</option>';
                    }
                    ?>
                </select>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                <button type="button" class="btn btn-primary" id="btnLoadLibrary">Charger</button>
            </div>
        </div>
    </div>
</div>

<form method="post" id="templateForm">
    <div class="card mb-4">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="fas fa-heading"></i> En-tête de la fiche</h5>
        </div>
        <div class="card-body">
            <div id="enTeteFields">
                <?php foreach ($contenu['en_tete'] as $field): ?>
                    <div class="row mb-2 en-tete-field">
                        <div class="col-md-3"><input type="text" class="form-control" placeholder="Label" value="<?= htmlspecialchars($field['label']) ?>"></div>
                        <div class="col-md-3"><select class="form-select field-type">
                                <option value="text" <?= ($field['type'] ?? 'text') == 'text' ? 'selected' : '' ?>>Texte</option>
                                <option value="textarea" <?= ($field['type'] ?? '') == 'textarea' ? 'selected' : '' ?>>Texte long</option>
                                <option value="date" <?= ($field['type'] ?? '') == 'date' ? 'selected' : '' ?>>Date</option>
                                <option value="time" <?= ($field['type'] ?? '') == 'time' ? 'selected' : '' ?>>Heure</option>
                                <option value="number" <?= ($field['type'] ?? '') == 'number' ? 'selected' : '' ?>>Nombre</option>
                                <option value="email" <?= ($field['type'] ?? '') == 'email' ? 'selected' : '' ?>>Email</option>
                                <option value="tel" <?= ($field['type'] ?? '') == 'tel' ? 'selected' : '' ?>>Téléphone</option>
                                <option value="select" <?= ($field['type'] ?? '') == 'select' ? 'selected' : '' ?>>Sélection (options)</option>
                            </select></div>
                        <div class="col-md-3"><input type="text" class="form-control field-options" placeholder="Options (séparées par des virgules)" value="<?= isset($field['options']) && is_array($field['options']) ? htmlspecialchars(implode(',', $field['options'])) : '' ?>" <?= ($field['type'] ?? '') != 'select' ? 'disabled' : '' ?>></div>
                        <div class="col-md-2"><input type="text" class="form-control" placeholder="Nom interne" value="<?= htmlspecialchars($field['name'] ?? '') ?>"></div>
                        <div class="col-md-1"><button type="button" class="btn btn-sm btn-danger" onclick="supprimerChampEnTete(this)"><i class="fas fa-trash"></i></button></div>
                    </div>
                <?php endforeach; ?>
            </div>
            <button type="button" class="btn btn-sm btn-success" onclick="ajouterChampEnTete()"><i class="fas fa-plus"></i> Ajouter un champ</button>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="fas fa-table"></i> Tableau de contrôle</h5>
        </div>
        <div class="card-body">
            <h6>Colonnes</h6>
            <div id="colonnesList">
                <?php foreach ($contenu['tableau']['colonnes'] as $col): ?>
                    <div class="row mb-2 colonne-item">
                        <div class="col-md-2"><input type="text" class="form-control" placeholder="Label" value="<?= htmlspecialchars($col['label'] ?? '') ?>"></div>
                        <div class="col-md-2"><select class="form-select col-type">
                                <option value="text" <?= ($col['type'] ?? '') == 'text' ? 'selected' : '' ?>>Texte (libre ou pré‑rempli)</option>
                                <option value="textarea" <?= ($col['type'] ?? '') == 'textarea' ? 'selected' : '' ?>>Texte long</option>
                                <option value="date" <?= ($col['type'] ?? '') == 'date' ? 'selected' : '' ?>>Date</option>
                                <option value="time" <?= ($col['type'] ?? '') == 'time' ? 'selected' : '' ?>>Heure</option>
                                <option value="number" <?= ($col['type'] ?? '') == 'number' ? 'selected' : '' ?>>Nombre</option>
                                <option value="email" <?= ($col['type'] ?? '') == 'email' ? 'selected' : '' ?>>Email</option>
                                <option value="tel" <?= ($col['type'] ?? '') == 'tel' ? 'selected' : '' ?>>Téléphone</option>
                                <option value="radio" <?= ($col['type'] ?? '') == 'radio' ? 'selected' : '' ?>>Radio (options)</option>
                                <option value="checkbox" <?= ($col['type'] ?? '') == 'checkbox' ? 'selected' : '' ?>>Checkbox (Oui/Non)</option>
                                <option value="select" <?= ($col['type'] ?? '') == 'select' ? 'selected' : '' ?>>Sélection (options)</option>
                            </select></div>
                        <div class="col-md-3"><input type="text" class="form-control col-options" placeholder="Options (séparées par des virgules)" value="<?= isset($col['options']) && is_array($col['options']) ? htmlspecialchars(implode(',', $col['options'])) : '' ?>" <?= !in_array($col['type'] ?? '', ['radio','select','text']) ? 'disabled' : '' ?>></div>
                        <div class="col-md-3"><div class="form-check"><input type="checkbox" class="form-check-input need-explanation" <?= isset($col['need_explanation']) && $col['need_explanation'] ? 'checked' : '' ?> <?= ($col['type'] ?? '') != 'radio' ? 'disabled' : '' ?>><label class="form-check-label">Nécessite explication pour dernière option</label></div></div>
                        <div class="col-md-2"><button type="button" class="btn btn-sm btn-danger" onclick="supprimerColonne(this)"><i class="fas fa-trash"></i> Supprimer</button></div>
                    </div>
                <?php endforeach; ?>
            </div>
            <button type="button" class="btn btn-sm btn-success" onclick="ajouterColonne()"><i class="fas fa-plus"></i> Ajouter colonne</button>

            <hr>
            <h6 class="mt-3">Lignes (intitulés fixes)</h6>
            <p class="text-muted">Ces lignes seront proposées à l'utilisateur, qui pourra en ajouter ou supprimer selon ses besoins lors de la création de la fiche.</p>
            <div id="lignesList">
                <?php foreach ($contenu['tableau']['lignes'] as $ligne): ?>
                    <div class="row mb-2 ligne-item">
                        <div class="col-md-10"><input type="text" class="form-control" placeholder="Intitulé de la ligne" value="<?= htmlspecialchars($ligne) ?>"></div>
                        <div class="col-md-2"><button type="button" class="btn btn-sm btn-danger" onclick="supprimerLigneTemplate(this)"><i class="fas fa-trash"></i> Supprimer</button></div>
                    </div>
                <?php endforeach; ?>
            </div>
            <button type="button" class="btn btn-sm btn-success" onclick="ajouterLigneTemplate()"><i class="fas fa-plus"></i> Ajouter ligne</button>
        </div>
    </div>

    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
        <button type="button" class="btn btn-primary" onclick="enregistrerTemplate()">Enregistrer le template</button>
        <a href="../dashboard.php" class="btn btn-outline-secondary">Annuler</a>
    </div>
</form>

<!-- Modal pour copier depuis un autre sous-dossier -->
<div class="modal fade" id="copyTemplateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title"><i class="fas fa-copy"></i> Copier depuis un sous-dossier</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <select id="selectTemplateSource" class="form-select">
                    <option value="">-- Choisir un sous-dossier --</option>
                    <?php foreach ($autres_sous_dossiers as $sd): ?>
                        <option value="<?= $sd['id'] ?>"><?= htmlspecialchars($sd['projet_nom']) ?> / <?= htmlspecialchars($sd['dossier_nom']) ?> / <?= htmlspecialchars($sd['sous_dossier_nom']) ?></option>
                    <?php endforeach; ?>
                </select>
                <div class="mt-3" id="templatePreview" style="display:none;"><pre id="templatePreviewContent" style="max-height:200px; overflow:auto; background:#f5f5f5; padding:10px;"></pre></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                <button type="button" class="btn btn-primary" id="btnCopyTemplate" disabled>Copier</button>
            </div>
        </div>
    </div>
</div>

<script>
// ------------------------------------------------------------------
// Fonctions de gestion du formulaire
// ------------------------------------------------------------------
function ajouterChampEnTete() {
    const container = document.getElementById('enTeteFields');
    const div = document.createElement('div');
    div.className = 'row mb-2 en-tete-field';
    div.innerHTML = `
        <div class="col-md-3"><input type="text" class="form-control" placeholder="Label"></div>
        <div class="col-md-3"><select class="form-select field-type">
            <option value="text">Texte</option>
            <option value="textarea">Texte long</option>
            <option value="date">Date</option>
            <option value="time">Heure</option>
            <option value="number">Nombre</option>
            <option value="email">Email</option>
            <option value="tel">Téléphone</option>
            <option value="select">Sélection (options)</option>
        </select></div>
        <div class="col-md-3"><input type="text" class="form-control field-options" placeholder="Options (séparées par des virgules)" disabled></div>
        <div class="col-md-2"><input type="text" class="form-control" placeholder="Nom interne"></div>
        <div class="col-md-1"><button type="button" class="btn btn-sm btn-danger" onclick="supprimerChampEnTete(this)"><i class="fas fa-trash"></i></button></div>
    `;
    container.appendChild(div);
    attacherEvenementsChampEnTete(div);
}
function supprimerChampEnTete(btn) { btn.closest('.en-tete-field').remove(); }

function ajouterColonne() {
    const container = document.getElementById('colonnesList');
    const div = document.createElement('div');
    div.className = 'row mb-2 colonne-item';
    div.innerHTML = `
        <div class="col-md-2"><input type="text" class="form-control" placeholder="Label"></div>
        <div class="col-md-2"><select class="form-select col-type">
            <option value="text">Texte (libre ou pré‑rempli)</option>
            <option value="textarea">Texte long</option>
            <option value="date">Date</option>
            <option value="time">Heure</option>
            <option value="number">Nombre</option>
            <option value="email">Email</option>
            <option value="tel">Téléphone</option>
            <option value="radio">Radio (options)</option>
            <option value="checkbox">Checkbox (Oui/Non)</option>
            <option value="select">Sélection (options)</option>
        </select></div>
        <div class="col-md-3"><input type="text" class="form-control col-options" placeholder="Options (séparées par des virgules)" disabled></div>
        <div class="col-md-3"><div class="form-check"><input type="checkbox" class="form-check-input need-explanation" disabled><label class="form-check-label">Nécessite explication pour dernière option</label></div></div>
        <div class="col-md-2"><button type="button" class="btn btn-sm btn-danger" onclick="supprimerColonne(this)"><i class="fas fa-trash"></i> Supprimer</button></div>
    `;
    container.appendChild(div);
    attacherEvenementsColonne(div);
}
function supprimerColonne(btn) { btn.closest('.colonne-item').remove(); }

function ajouterLigneTemplate() {
    const container = document.getElementById('lignesList');
    const div = document.createElement('div');
    div.className = 'row mb-2 ligne-item';
    div.innerHTML = `
        <div class="col-md-10"><input type="text" class="form-control" placeholder="Intitulé de la ligne"></div>
        <div class="col-md-2"><button type="button" class="btn btn-sm btn-danger" onclick="supprimerLigneTemplate(this)"><i class="fas fa-trash"></i> Supprimer</button></div>
    `;
    container.appendChild(div);
}
function supprimerLigneTemplate(btn) { btn.closest('.ligne-item').remove(); }

function attacherEvenementsChampEnTete(div) {
    const select = div.querySelector('.field-type');
    const optionsInput = div.querySelector('.field-options');
    select?.addEventListener('change', () => {
        if (select.value === 'select') {
            optionsInput.disabled = false;
        } else {
            optionsInput.disabled = true;
            optionsInput.value = '';
        }
    });
}
function attacherEvenementsColonne(div) {
    const select = div.querySelector('.col-type');
    const optionsInput = div.querySelector('.col-options');
    const needExp = div.querySelector('.need-explanation');
    select?.addEventListener('change', () => {
        const val = select.value;
        if (val === 'radio' || val === 'select' || val === 'text') {
            optionsInput.disabled = false;
        } else {
            optionsInput.disabled = true;
            optionsInput.value = '';
        }
        if (val === 'radio') {
            needExp.disabled = false;
        } else {
            needExp.disabled = true;
            needExp.checked = false;
        }
    });
}

// Appliquer les événements aux éléments existants
document.querySelectorAll('#enTeteFields .en-tete-field').forEach(el => attacherEvenementsChampEnTete(el));
document.querySelectorAll('#colonnesList .colonne-item').forEach(el => attacherEvenementsColonne(el));

function enregistrerTemplate() {
    const enTete = [];
    document.querySelectorAll('#enTeteFields .en-tete-field').forEach(field => {
        const label = field.querySelector('input[placeholder="Label"]').value;
        const type = field.querySelector('.field-type').value;
        const name = field.querySelector('input[placeholder="Nom interne"]').value;
        let options = [];
        if (type === 'select') {
            const optVal = field.querySelector('.field-options').value;
            if (optVal.trim()) options = optVal.split(',').map(o => o.trim());
        }
        if (label && name) enTete.push({label, type, name, options});
    });
    const colonnes = [];
    document.querySelectorAll('#colonnesList .colonne-item').forEach(col => {
        const label = col.querySelector('input[placeholder="Label"]').value;
        const type = col.querySelector('.col-type').value;
        let options = [];
        if (type === 'radio' || type === 'select' || type === 'text') {
            const optVal = col.querySelector('.col-options').value;
            if (optVal.trim()) options = optVal.split(',').map(o => o.trim());
        }
        const need_explanation = col.querySelector('.need-explanation').checked;
        if (label) colonnes.push({label, type, options, need_explanation});
    });
    const lignes = [];
    document.querySelectorAll('#lignesList .ligne-item').forEach(ligne => {
        const text = ligne.querySelector('input[placeholder="Intitulé de la ligne"]').value;
        if (text) lignes.push(text);
    });
    const template = { en_tete: enTete, tableau: { colonnes, lignes } };
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'template_json';
    input.value = JSON.stringify(template);
    document.getElementById('templateForm').appendChild(input);
    document.getElementById('templateForm').submit();
}

// --- Modal "Charger depuis bibliothèque" ---
document.getElementById('btnLoadLibrary').addEventListener('click', function() {
    var libId = document.getElementById('librarySelect').value;
    if (!libId) { alert('Veuillez sélectionner un template.'); return; }
    fetch('../ajax_get_template_library.php?id=' + libId)
        .then(response => response.json())
        .then(data => {
            if (data.error) { alert('Erreur : ' + data.error); return; }
            reconstruireFormulaire(data);
            bootstrap.Modal.getInstance(document.getElementById('loadLibraryModal')).hide();
            alert('Template chargé. Vous pouvez maintenant l\'adapter puis l\'enregistrer.');
        })
        .catch(err => alert('Erreur réseau : ' + err));
});

// --- Modal de copie depuis un sous-dossier existant ---
let selectedSourceId = null;
const selectSource = document.getElementById('selectTemplateSource');
const btnCopy = document.getElementById('btnCopyTemplate');
const previewDiv = document.getElementById('templatePreview');
const previewContent = document.getElementById('templatePreviewContent');

if (selectSource) {
    selectSource.addEventListener('change', function() {
        selectedSourceId = this.value;
        if (!selectedSourceId) {
            btnCopy.disabled = true;
            previewDiv.style.display = 'none';
            return;
        }
        fetch('../ajax_get_template.php?id=' + selectedSourceId)
            .then(res => res.json())
            .then(data => {
                if (data.error) {
                    previewDiv.style.display = 'block';
                    previewContent.textContent = 'Erreur : ' + data.error;
                    btnCopy.disabled = true;
                } else {
                    previewDiv.style.display = 'block';
                    previewContent.textContent = JSON.stringify(data, null, 2);
                    btnCopy.disabled = false;
                }
            })
            .catch(err => { previewDiv.style.display = 'block'; previewContent.textContent = 'Erreur chargement'; btnCopy.disabled = true; });
    });
    btnCopy.addEventListener('click', function() {
        if (!selectedSourceId) return;
        fetch('../ajax_get_template.php?id=' + selectedSourceId)
            .then(res => res.json())
            .then(data => {
                if (data.error) { alert('Erreur : ' + data.error); return; }
                reconstruireFormulaire(data);
                bootstrap.Modal.getInstance(document.getElementById('copyTemplateModal')).hide();
                alert('Template copié avec succès !');
            })
            .catch(err => alert('Erreur réseau : ' + err));
    });
}

function reconstruireFormulaire(tpl) {
    // En-têtes
    const enTeteContainer = document.getElementById('enTeteFields');
    enTeteContainer.innerHTML = '';
    (tpl.en_tete || []).forEach(field => {
        const div = document.createElement('div');
        div.className = 'row mb-2 en-tete-field';
        div.innerHTML = `
            <div class="col-md-3"><input type="text" class="form-control" placeholder="Label" value="${escapeHtml(field.label)}"></div>
            <div class="col-md-3"><select class="form-select field-type">${getTypeOptions(field.type)}</select></div>
            <div class="col-md-3"><input type="text" class="form-control field-options" placeholder="Options (séparées par des virgules)" value="${escapeHtml((field.options || []).join(','))}" ${field.type !== 'select' ? 'disabled' : ''}></div>
            <div class="col-md-2"><input type="text" class="form-control" placeholder="Nom interne" value="${escapeHtml(field.name)}"></div>
            <div class="col-md-1"><button type="button" class="btn btn-sm btn-danger" onclick="supprimerChampEnTete(this)"><i class="fas fa-trash"></i></button></div>
        `;
        enTeteContainer.appendChild(div);
        attacherEvenementsChampEnTete(div);
    });
    // Colonnes
    const colonnesContainer = document.getElementById('colonnesList');
    colonnesContainer.innerHTML = '';
    (tpl.tableau && tpl.tableau.colonnes || []).forEach(col => {
        const div = document.createElement('div');
        div.className = 'row mb-2 colonne-item';
        div.innerHTML = `
            <div class="col-md-2"><input type="text" class="form-control" placeholder="Label" value="${escapeHtml(col.label)}"></div>
            <div class="col-md-2"><select class="form-select col-type">${getColTypeOptions(col.type)}</select></div>
            <div class="col-md-3"><input type="text" class="form-control col-options" placeholder="Options (séparées par des virgules)" value="${escapeHtml((col.options || []).join(','))}" ${!['radio','select','text'].includes(col.type) ? 'disabled' : ''}></div>
            <div class="col-md-3"><div class="form-check"><input type="checkbox" class="form-check-input need-explanation" ${col.need_explanation ? 'checked' : ''} ${col.type !== 'radio' ? 'disabled' : ''}><label class="form-check-label">Nécessite explication pour dernière option</label></div></div>
            <div class="col-md-2"><button type="button" class="btn btn-sm btn-danger" onclick="supprimerColonne(this)"><i class="fas fa-trash"></i> Supprimer</button></div>
        `;
        colonnesContainer.appendChild(div);
        attacherEvenementsColonne(div);
    });
    // Lignes
    const lignesContainer = document.getElementById('lignesList');
    lignesContainer.innerHTML = '';
    (tpl.tableau && tpl.tableau.lignes || []).forEach(ligne => {
        const div = document.createElement('div');
        div.className = 'row mb-2 ligne-item';
        div.innerHTML = `
            <div class="col-md-10"><input type="text" class="form-control" placeholder="Intitulé de la ligne" value="${escapeHtml(ligne)}"></div>
            <div class="col-md-2"><button type="button" class="btn btn-sm btn-danger" onclick="supprimerLigneTemplate(this)"><i class="fas fa-trash"></i> Supprimer</button></div>
        `;
        lignesContainer.appendChild(div);
    });
}

function escapeHtml(str) { if (!str) return ''; return str.replace(/[&<>]/g, m => m==='&'?'&amp;': m==='<'?'&lt;':'&gt;'); }
function getTypeOptions(selected) {
    const types = ['text','textarea','date','time','number','email','tel','select'];
    const labels = {'text':'Texte','textarea':'Texte long','date':'Date','time':'Heure','number':'Nombre','email':'Email','tel':'Téléphone','select':'Sélection (options)'};
    return types.map(t => `<option value="${t}" ${selected===t?'selected':''}>${labels[t]}</option>`).join('');
}
function getColTypeOptions(selected) {
    const types = ['text','textarea','date','time','number','email','tel','radio','checkbox','select'];
    const labels = {
        'text':'Texte (libre ou pré‑rempli)',
        'textarea':'Texte long',
        'date':'Date',
        'time':'Heure',
        'number':'Nombre',
        'email':'Email',
        'tel':'Téléphone',
        'radio':'Radio (options)',
        'checkbox':'Checkbox (Oui/Non)',
        'select':'Sélection (options)'
    };
    return types.map(t => `<option value="${t}" ${selected===t?'selected':''}>${labels[t]}</option>`).join('');
}
</script>

<?php require_once '../includes/footer.php'; ?>