<?php
require_once 'includes/auth.php';
require_once 'config/database.php';
require_once 'includes/functions.php';

$pdo = getPDO();
$error = '';
$fiche_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$sous_dossier_id = filter_input(INPUT_GET, 'sous_dossier_id', FILTER_VALIDATE_INT);

if ($fiche_id) {
    $stmt = $pdo->prepare("SELECT f.*, sd.nom as sous_dossier_nom, d.nom as dossier_nom, p.nom as projet_nom
                           FROM fiches f
                           JOIN sous_dossiers sd ON f.sous_dossier_id = sd.id
                           JOIN dossiers d ON sd.dossier_id = d.id
                           JOIN projets p ON d.projet_id = p.id
                           WHERE f.id = ?");
    $stmt->execute([$fiche_id]);
    $fiche = $stmt->fetch();
    if (!$fiche) { header('Location: dashboard.php'); exit; }
    $sous_dossier_id = $fiche['sous_dossier_id'];
    $contenu = json_decode($fiche['contenu'], true);
} else {
    if (!$sous_dossier_id) { header('Location: dashboard.php'); exit; }
    $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) { 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 = [];
    }
    $fiche = null;
}

// Normalisation
if (!is_array($contenu)) $contenu = [];
$contenu += ['en_tete' => [], 'tableau' => []];
$contenu['tableau'] += ['colonnes' => [], 'lignes' => [], 'valeurs' => []];
if (empty($contenu['tableau']['colonnes'])) {
    $contenu['tableau']['colonnes'] = [
        ['label' => 'C', 'type' => 'radio', 'options' => ['C','NC','NA'], 'need_explanation' => false],
        ['label' => 'Observation', 'type' => 'text', 'options' => []]
    ];
}
if (empty($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);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $titre = trim($_POST['titre'] ?? '');
    $zone = trim($_POST['zone'] ?? '');
    $observation = trim($_POST['observation'] ?? '');
    $statut = $_POST['statut'] ?? 'brouillon';
    $type_reserve = $_POST['type_reserve'] ?? 'sans_reserve';
    $description_reserve = trim($_POST['description_reserve'] ?? '');

    $en_tete = [];
    if (!empty($contenu['en_tete'])) {
        foreach ($contenu['en_tete'] as $champ) {
            $name = $champ['name'];
            $champ['valeur'] = $_POST[$name] ?? '';
            $en_tete[] = $champ;
        }
    }

    $lignes = $_POST['lignes'] ?? [];
    $valeurs = $_POST['valeurs'] ?? [];
    $explications = $_POST['explications'] ?? [];

    $tableau = [
        'colonnes' => $contenu['tableau']['colonnes'],
        'lignes'   => $lignes,
        'valeurs'  => $valeurs,
        'explications' => $explications
    ];
    $nouveau_contenu = ['en_tete' => $en_tete, 'tableau' => $tableau];

    if (empty($titre)) {
        $error = "Le titre est requis.";
    } else {
        try {
            $pdo->beginTransaction();
            if (!$fiche) {
                $numero = genererNumeroFiche($pdo, $sous_dossier_id);
                if (!$numero) throw new Exception("Erreur génération numéro");
                $stmt = $pdo->prepare("INSERT INTO fiches (sous_dossier_id, numero_fiche, titre, zone, observation, type_reserve, description_reserve, contenu, statut, createur_id, signature_emetteur) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
                $stmt->execute([$sous_dossier_id, $numero, $titre, $zone, $observation, $type_reserve, $description_reserve, json_encode($nouveau_contenu), $statut, $_SESSION['user_id'], $_SESSION['user_signature'] ?? null]);
                $fiche_id = $pdo->lastInsertId();
                logAction($pdo, $_SESSION['user_id'], 'creation_fiche', "Fiche $numero");
            } else {
                $stmt = $pdo->prepare("UPDATE fiches SET titre=?, zone=?, observation=?, type_reserve=?, description_reserve=?, contenu=?, statut=? WHERE id=?");
                $stmt->execute([$titre, $zone, $observation, $type_reserve, $description_reserve, json_encode($nouveau_contenu), $statut, $fiche_id]);
                logAction($pdo, $_SESSION['user_id'], 'modification_fiche', "Fiche $fiche_id");
            }
            $pdo->commit();
            header("Location: fiche_view.php?id=$fiche_id");
            exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Erreur : " . $e->getMessage();
        }
    }
}

require_once 'includes/header.php';
$sous_dossier_nom = $fiche['sous_dossier_nom'] ?? $sous_dossier['nom'] ?? '';
$projet_nom = $fiche['projet_nom'] ?? $sous_dossier['projet_nom'] ?? '';
?>
<div class="row"><div class="col-12"><h1><?= $fiche ? 'Modifier' : 'Créer' ?> une fiche</h1><p class="text-muted">Sous-dossier : <?= htmlspecialchars($sous_dossier_nom) ?> | Projet : <?= htmlspecialchars($projet_nom) ?></p></div></div>
<?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>
<form method="post" id="ficheForm">
    <div class="row mb-3">
        <div class="col-md-6"><label>Titre *</label><input type="text" name="titre" class="form-control" value="<?= htmlspecialchars($fiche['titre'] ?? '') ?>" required></div>
        <div class="col-md-3"><label>Zone</label><input type="text" name="zone" class="form-control" value="<?= htmlspecialchars($fiche['zone'] ?? '') ?>"></div>
        <div class="col-md-3"><label>Type de réserve</label><select name="type_reserve" id="type_reserve" class="form-select"><option value="sans_reserve" <?= ($fiche['type_reserve']??'sans_reserve')=='sans_reserve'?'selected':'' ?>>Sans réserve</option><option value="avec_reserve" <?= ($fiche['type_reserve']??'')=='avec_reserve'?'selected':'' ?>>Avec réserve</option></select></div>
    </div>
    <div class="mb-3" id="reserveDescriptionContainer" style="display: none;">
        <label for="description_reserve" class="form-label">Description des réserves</label>
        <textarea class="form-control" id="description_reserve" name="description_reserve" rows="4"><?= htmlspecialchars($fiche['description_reserve'] ?? '') ?></textarea>
        <small class="text-muted">Décrivez précisément les réserves constatées.</small>
    </div>
    <div class="mb-3"><label>Observation générale</label><textarea name="observation" class="form-control" rows="2"><?= htmlspecialchars($fiche['observation'] ?? '') ?></textarea></div>

    <?php if (!empty($contenu['en_tete'])): ?>
    <div class="card mb-4"><div class="card-header bg-light">Informations générales</div><div class="card-body"><div class="row">
        <?php foreach ($contenu['en_tete'] as $champ): 
            $type = $champ['type'];
            $name = $champ['name'];
            $value = $champ['valeur'] ?? '';
            if ($type == 'textarea'): ?>
                <div class="col-md-4 mb-2"><label><?= htmlspecialchars($champ['label']) ?></label><textarea class="form-control" name="<?= $name ?>"><?= htmlspecialchars($value) ?></textarea></div>
            <?php elseif ($type == 'select' && !empty($champ['options'])): ?>
                <div class="col-md-4 mb-2"><label><?= htmlspecialchars($champ['label']) ?></label><select class="form-select" name="<?= $name ?>"><option value="">-- Sélectionner --</option><?php foreach ($champ['options'] as $opt): ?><option value="<?= htmlspecialchars($opt) ?>" <?= $value == $opt ? 'selected' : '' ?>><?= htmlspecialchars($opt) ?></option><?php endforeach; ?></select></div>
            <?php elseif ($type == 'time'): ?>
                <div class="col-md-4 mb-2"><label><?= htmlspecialchars($champ['label']) ?></label><input type="time" class="form-control" name="<?= $name ?>" value="<?= htmlspecialchars($value) ?>"></div>
            <?php elseif ($type == 'email'): ?>
                <div class="col-md-4 mb-2"><label><?= htmlspecialchars($champ['label']) ?></label><input type="email" class="form-control" name="<?= $name ?>" value="<?= htmlspecialchars($value) ?>"></div>
            <?php elseif ($type == 'tel'): ?>
                <div class="col-md-4 mb-2"><label><?= htmlspecialchars($champ['label']) ?></label><input type="tel" class="form-control" name="<?= $name ?>" value="<?= htmlspecialchars($value) ?>"></div>
            <?php elseif ($type == 'number'): ?>
                <div class="col-md-4 mb-2"><label><?= htmlspecialchars($champ['label']) ?></label><input type="number" class="form-control" name="<?= $name ?>" value="<?= htmlspecialchars($value) ?>"></div>
            <?php elseif ($type == 'date'): ?>
                <div class="col-md-4 mb-2"><label><?= htmlspecialchars($champ['label']) ?></label><input type="date" class="form-control" name="<?= $name ?>" value="<?= htmlspecialchars($value) ?>"></div>
            <?php else: ?>
                <div class="col-md-4 mb-2"><label><?= htmlspecialchars($champ['label']) ?></label><input type="text" class="form-control" name="<?= $name ?>" value="<?= htmlspecialchars($value) ?>"></div>
            <?php endif; ?>
        <?php endforeach; ?>
    </div></div></div>
    <?php endif; ?>

    <div class="card mb-4">
        <div class="card-header bg-light d-flex justify-content-between align-items-center">
            <span>Tableau des contrôles</span>
            <div><button type="button" class="btn btn-sm btn-success" onclick="ajouterLigne()"><i class="fas fa-plus"></i> Ligne</button><button type="button" class="btn btn-sm btn-primary ms-2" onclick="ajouterColonne()"><i class="fas fa-columns"></i> Colonne</button></div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="tableControles">
                    <thead class="table-light"><tr id="headerRow"><th>Élément contrôlé</th>
                        <?php foreach ($contenu['tableau']['colonnes'] as $j => $col): ?>
                            <th><input type="text" class="form-control form-control-sm" name="colonnes[<?= $j ?>]" value="<?= htmlspecialchars($col['label']) ?>" placeholder="Titre colonne"></th>
                        <?php endforeach; ?>
                        <th style="width:80px;">Actions</th>
                    </tr></thead>
                    <tbody>
                        <?php $lignes = $contenu['tableau']['lignes']; $valeurs = $contenu['tableau']['valeurs']; $explications = $contenu['tableau']['explications'] ?? []; ?>
                        <?php foreach ($lignes as $i => $ligne): ?>
                            <tr data-ligne="<?= $i ?>">
                                <td><input type="text" class="form-control" name="lignes[<?= $i ?>]" value="<?= htmlspecialchars($ligne) ?>" placeholder="Intitulé"></td>
                                <?php foreach ($contenu['tableau']['colonnes'] as $j => $col): 
                                    $type = $col['type'];
                                    $opt = $col['options'];
                                    $needExp = $col['need_explanation'] ?? false;
                                    $cellValue = $valeurs[$i][$j] ?? '';
                                    $expValue = $explications[$i][$j] ?? '';
                                ?>
                                <td class="td-colonne-<?= $j ?>" data-col="<?= $j ?>" data-row="<?= $i ?>" data-need-exp="<?= $needExp ? '1' : '0' ?>">
                                    <?php if ($type == 'radio'): ?>
                                        <div class="radio-group">
                                            <?php foreach ($opt as $optIdx => $optVal): ?>
                                                <label class="me-2"><input type="radio" name="valeurs[<?= $i ?>][<?= $j ?>]" value="<?= htmlspecialchars($optVal) ?>" <?= $cellValue == $optVal ? 'checked' : '' ?> data-optidx="<?= $optIdx ?>" data-last="<?= ($optIdx == count($opt)-1) ? '1' : '0' ?>"> <?= htmlspecialchars($optVal) ?></label>
                                            <?php endforeach; ?>
                                        </div>
                                        <?php if ($needExp): ?>
                                            <div class="explanation-field mt-1" style="display: <?= ($cellValue == end($opt)) ? 'block' : 'none' ?>;">
                                                <input type="text" class="form-control form-control-sm" name="explications[<?= $i ?>][<?= $j ?>]" placeholder="Explication (requise)" value="<?= htmlspecialchars($expValue) ?>">
                                            </div>
                                        <?php endif; ?>
                                    <?php elseif ($type == 'checkbox'): ?>
                                        <input type="checkbox" name="valeurs[<?= $i ?>][<?= $j ?>]" value="on" <?= $cellValue == 'on' ? 'checked' : '' ?>>
                                    <?php elseif ($type == 'textarea'): ?>
                                        <textarea class="form-control" name="valeurs[<?= $i ?>][<?= $j ?>]" rows="2"><?= htmlspecialchars($cellValue) ?></textarea>
                                    <?php elseif ($type == 'date'): ?>
                                        <input type="date" class="form-control" name="valeurs[<?= $i ?>][<?= $j ?>]" value="<?= htmlspecialchars($cellValue) ?>">
                                    <?php elseif ($type == 'time'): ?>
                                        <input type="time" class="form-control" name="valeurs[<?= $i ?>][<?= $j ?>]" value="<?= htmlspecialchars($cellValue) ?>">
                                    <?php elseif ($type == 'number'): ?>
                                        <input type="number" class="form-control" name="valeurs[<?= $i ?>][<?= $j ?>]" value="<?= htmlspecialchars($cellValue) ?>">
                                    <?php elseif ($type == 'email'): ?>
                                        <input type="email" class="form-control" name="valeurs[<?= $i ?>][<?= $j ?>]" value="<?= htmlspecialchars($cellValue) ?>">
                                    <?php elseif ($type == 'tel'): ?>
                                        <input type="tel" class="form-control" name="valeurs[<?= $i ?>][<?= $j ?>]" value="<?= htmlspecialchars($cellValue) ?>">
                                    <?php elseif ($type == 'select' && !empty($opt)): ?>
                                        <select class="form-select" name="valeurs[<?= $i ?>][<?= $j ?>]">
                                            <option value="">--</option>
                                            <?php foreach ($opt as $optVal): ?>
                                                <option value="<?= htmlspecialchars($optVal) ?>" <?= $cellValue == $optVal ? 'selected' : '' ?>><?= htmlspecialchars($optVal) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    <?php elseif ($type == 'text' && !empty($opt)): ?>
                                        <!-- Texte pré‑rempli, non modifiable -->
                                        <?php
                                        $displayValue = (!empty($cellValue)) ? $cellValue : (isset($opt[$i]) ? $opt[$i] : '');
                                        ?>
                                        <div class="form-control-plaintext"><?= htmlspecialchars($displayValue) ?></div>
                                        <input type="hidden" name="valeurs[<?= $i ?>][<?= $j ?>]" value="<?= htmlspecialchars($displayValue) ?>">
                                    <?php else: ?>
                                        <input type="text" class="form-control" name="valeurs[<?= $i ?>][<?= $j ?>]" value="<?= htmlspecialchars($cellValue) ?>">
                                    <?php endif; ?>
                                </td>
                                <?php endforeach; ?>
                                <td class="text-center"><button type="button" class="btn btn-sm btn-danger" onclick="supprimerLigne(this)"><i class="fas fa-trash"></i></button></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="mb-3"><label>Statut</label><select name="statut" class="form-select"><option value="brouillon" <?= ($fiche['statut']??'brouillon')=='brouillon'?'selected':'' ?>>Brouillon</option><option value="soumis" <?= ($fiche['statut']??'')=='soumis'?'selected':'' ?>>Soumis</option><option value="valide" <?= ($fiche['statut']??'')=='valide'?'selected':'' ?>>Validé</option></select></div>

    <div class="d-grid gap-2 d-md-flex justify-content-md-end"><button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-save"></i> Enregistrer</button><a href="sous_dossier.php?id=<?= $sous_dossier_id ?>" class="btn btn-outline-secondary btn-lg">Annuler</a></div>
</form>

<script>
// Initialisation des colonnes (stockées dans un tableau global)
let colonnesTypes = <?php
    $tmp = [];
    foreach ($contenu['tableau']['colonnes'] as $c) {
        $tmp[] = ['type' => $c['type'], 'options' => $c['options'] ?? [], 'need_explanation' => $c['need_explanation'] ?? false];
    }
    echo json_encode($tmp);
?>;

function ajouterLigne() {
    const tbody = document.querySelector('#tableControles tbody');
    const nbLignes = tbody.children.length;
    let html = `<td><input type="text" class="form-control" name="lignes[${nbLignes}]" placeholder="Intitulé"></td>`;
    for (let j = 0; j < colonnesTypes.length; j++) {
        const col = colonnesTypes[j];
        let cellHtml = '';
        if (col.type === 'radio') {
            cellHtml = '<td class="td-colonne-'+j+'">';
            for (let opt of col.options) {
                cellHtml += `<label class="me-2"><input type="radio" name="valeurs[${nbLignes}][${j}]" value="${opt}"> ${opt}</label>`;
            }
            if (col.need_explanation) {
                cellHtml += '<div class="explanation-field mt-1" style="display:none;">';
                cellHtml += `<input type="text" class="form-control form-control-sm" name="explications[${nbLignes}][${j}]" placeholder="Explication">`;
                cellHtml += '</div>';
            }
            cellHtml += '</td>';
        } else if (col.type === 'checkbox') {
            cellHtml = `<td><input type="checkbox" name="valeurs[${nbLignes}][${j}]" value="on"></td>`;
        } else if (col.type === 'textarea') {
            cellHtml = `<td><textarea class="form-control" name="valeurs[${nbLignes}][${j}]" rows="2"></textarea></td>`;
        } else if (col.type === 'date') {
            cellHtml = `<td><input type="date" class="form-control" name="valeurs[${nbLignes}][${j}]"></td>`;
        } else if (col.type === 'time') {
            cellHtml = `<td><input type="time" class="form-control" name="valeurs[${nbLignes}][${j}]"></td>`;
        } else if (col.type === 'number') {
            cellHtml = `<td><input type="number" class="form-control" name="valeurs[${nbLignes}][${j}]"></td>`;
        } else if (col.type === 'email') {
            cellHtml = `<td><input type="email" class="form-control" name="valeurs[${nbLignes}][${j}]"></td>`;
        } else if (col.type === 'tel') {
            cellHtml = `<td><input type="tel" class="form-control" name="valeurs[${nbLignes}][${j}]"></td>`;
        } else if (col.type === 'select' && col.options.length) {
            let htmlOpt = '<select class="form-select" name="valeurs['+nbLignes+']['+j+']"><option value="">--</option>';
            col.options.forEach(opt => htmlOpt += `<option value="${opt}">${opt}</option>`);
            htmlOpt += '</select>';
            cellHtml = `<td>${htmlOpt}</td>`;
        } else if (col.type === 'text' && col.options.length) {
            let defaultValue = col.options[nbLignes] ? col.options[nbLignes] : '';
            cellHtml = `<td><div class="form-control-plaintext">${defaultValue}</div><input type="hidden" name="valeurs[${nbLignes}][${j}]" value="${defaultValue}"></td>`;
        } else {
            cellHtml = `<td><input type="text" class="form-control" name="valeurs[${nbLignes}][${j}]"></td>`;
        }
        html += cellHtml;
    }
    html += `<td class="text-center"><button type="button" class="btn btn-sm btn-danger" onclick="supprimerLigne(this)"><i class="fas fa-trash"></i></button></td>`;
    const row = document.createElement('tr');
    row.innerHTML = html;
    tbody.appendChild(row);
    appliquerEvenementsRadios(row);
}

function supprimerLigne(btn) {
    const row = btn.closest('tr');
    if (document.querySelectorAll('#tableControles tbody tr').length > 1) row.remove();
    else alert("Vous devez garder au moins une ligne.");
}

function ajouterColonne() {
    const headerRow = document.getElementById('headerRow');
    const nbColonnes = headerRow.children.length - 2;
    const type = prompt("Type de colonne : radio, checkbox, text, textarea, date, time, number, email, tel, select", "text");
    if (!type) return;
    let options = [];
    let needExplanation = false;
    if (type === 'radio' || type === 'select' || type === 'text') {
        const opts = prompt("Options (séparées par des virgules)", type === 'radio' ? "C,NC,NA" : "");
        if (opts) options = opts.split(',').map(o => o.trim());
    }
    if (type === 'radio') {
        needExplanation = confirm("Activer la nécessité d'explication pour la dernière option ?");
    }
    colonnesTypes.push({type: type, options: options, need_explanation: needExplanation});
    const newTh = document.createElement('th');
    newTh.innerHTML = `<input type="text" class="form-control form-control-sm" name="colonnes[${nbColonnes}]" placeholder="Titre colonne" value="Nouvelle">`;
    headerRow.insertBefore(newTh, headerRow.lastElementChild);
    const tbody = document.querySelector('#tableControles tbody');
    for (let i = 0; i < tbody.children.length; i++) {
        let cellHtml = '';
        if (type === 'radio') {
            cellHtml = '<td class="td-colonne-'+nbColonnes+'">';
            for (let opt of options) {
                cellHtml += `<label class="me-2"><input type="radio" name="valeurs[${i}][${nbColonnes}]" value="${opt}"> ${opt}</label>`;
            }
            if (needExplanation) {
                cellHtml += '<div class="explanation-field mt-1" style="display:none;">';
                cellHtml += `<input type="text" class="form-control form-control-sm" name="explications[${i}][${nbColonnes}]" placeholder="Explication">`;
                cellHtml += '</div>';
            }
            cellHtml += '</td>';
        } else if (type === 'checkbox') {
            cellHtml = `<td><input type="checkbox" name="valeurs[${i}][${nbColonnes}]" value="on"></td>`;
        } else if (type === 'textarea') {
            cellHtml = `<td><textarea class="form-control" name="valeurs[${i}][${nbColonnes}]" rows="2"></textarea></td>`;
        } else if (type === 'date') {
            cellHtml = `<td><input type="date" class="form-control" name="valeurs[${i}][${nbColonnes}]"></td>`;
        } else if (type === 'time') {
            cellHtml = `<td><input type="time" class="form-control" name="valeurs[${i}][${nbColonnes}]"></td>`;
        } else if (type === 'number') {
            cellHtml = `<td><input type="number" class="form-control" name="valeurs[${i}][${nbColonnes}]"></td>`;
        } else if (type === 'email') {
            cellHtml = `<td><input type="email" class="form-control" name="valeurs[${i}][${nbColonnes}]"></td>`;
        } else if (type === 'tel') {
            cellHtml = `<td><input type="tel" class="form-control" name="valeurs[${i}][${nbColonnes}]"></td>`;
        } else if (type === 'select' && options.length) {
            let htmlOpt = '<select class="form-select" name="valeurs['+i+']['+nbColonnes+']"><option value="">--</option>';
            options.forEach(opt => htmlOpt += `<option value="${opt}">${opt}</option>`);
            htmlOpt += '</select>';
            cellHtml = `<td>${htmlOpt}</td>`;
        } else if (type === 'text' && options.length) {
            let defaultValue = options[i] ? options[i] : '';
            cellHtml = `<td><div class="form-control-plaintext">${defaultValue}</div><input type="hidden" name="valeurs[${i}][${nbColonnes}]" value="${defaultValue}"></td>`;
        } else {
            cellHtml = `<td><input type="text" class="form-control" name="valeurs[${i}][${nbColonnes}]"><td>`;
        }
        const cell = tbody.children[i].insertCell(tbody.children[i].cells.length - 1);
        cell.innerHTML = cellHtml;
        if (type === 'radio') appliquerEvenementsRadios(tbody.children[i]);
    }
}

function appliquerEvenementsRadios(row) {
    const radios = row.querySelectorAll('input[type="radio"]');
    radios.forEach(radio => {
        radio.addEventListener('change', function() {
            const td = this.closest('td');
            const expDiv = td.querySelector('.explanation-field');
            if (expDiv) {
                const isLast = this.getAttribute('data-last') === '1';
                expDiv.style.display = isLast ? 'block' : 'none';
            }
        });
    });
}

document.querySelectorAll('#tableControles tbody tr').forEach(row => appliquerEvenementsRadios(row));

document.addEventListener('DOMContentLoaded', function() {
    const typeReserveSelect = document.getElementById('type_reserve');
    const descContainer = document.getElementById('reserveDescriptionContainer');
    function toggleReserveField() {
        descContainer.style.display = typeReserveSelect.value === 'avec_reserve' ? 'block' : 'none';
    }
    if (typeReserveSelect) {
        typeReserveSelect.addEventListener('change', toggleReserveField);
        toggleReserveField();
    }
});
</script>

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