<?php
require_once 'connexion/auth.php'; 

// SÉCURITÉ : Accès réservé
if (!isLogged() || !(hasRole('Administrateur') || hasRole('Maire') || hasRole('Adjoint') || hasRole('Secretaire'))) {
    header('Location: index.php');
    exit();
}

// ==========================================
// 1. CONFIGURATION DE LA GED
// ==========================================
$types_documents = [
    "Acte de décès",
    "Autorisation de transport",
    "Demande d'inhumation",
    "Certificat médical",
    "Livret de famille"
];

$dossier_ged = __DIR__ . '/GED/Cimetiere/defunts/';
if (!is_dir($dossier_ged)) { @mkdir($dossier_ged, 0777, true); }

// ==========================================
// 2. CRÉATION DES TABLES & MIGRATION AUTO
// ==========================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS cimetiere_defunts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        concession_id INT NULL,
        numero_case INT NULL,
        nom VARCHAR(100) NOT NULL,
        prenom VARCHAR(100) NOT NULL,
        date_naissance DATE NULL,
        date_deces DATE NOT NULL,
        date_inhumation DATE NULL,
        type_obseques VARCHAR(50) DEFAULT 'Cercueil',
        notes TEXT,
        acte_deces VARCHAR(255) NULL,
        FOREIGN KEY (concession_id) REFERENCES cimetiere_concessions(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS cimetiere_defunts_docs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        defunt_id INT NOT NULL,
        type_document VARCHAR(100) NOT NULL,
        chemin_fichier VARCHAR(255) NOT NULL,
        FOREIGN KEY (defunt_id) REFERENCES cimetiere_defunts(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $anciens = $pdo->query("SELECT id, acte_deces FROM cimetiere_defunts WHERE acte_deces IS NOT NULL AND acte_deces != ''")->fetchAll();
    foreach($anciens as $a) {
        $check = $pdo->prepare("SELECT id FROM cimetiere_defunts_docs WHERE defunt_id = ? AND type_document = 'Acte de décès'");
        $check->execute([$a['id']]);
        if(!$check->fetch()) {
            $pdo->prepare("INSERT INTO cimetiere_defunts_docs (defunt_id, type_document, chemin_fichier) VALUES (?, 'Acte de décès', ?)")->execute([$a['id'], $a['acte_deces']]);
        }
    }
} catch (Exception $e) { }

function nettoyerNomFichier($chaine) {
    if (empty($chaine)) return 'document';
    $accents = ['À','Á','Â','Ã','Ä','Å','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ò','Ó','Ô','Õ','Ö','Ù','Ú','Û','Ü','Ý','à','á','â','ã','ä','å','ç','è','é','ê','ë','ì','í','î','ï','ð','ò','ó','ô','õ','ö','ù','ú','û','ü','ý','ÿ'];
    $sans = ['A','A','A','A','A','A','C','E','E','E','E','I','I','I','I','O','O','O','O','O','U','U','U','U','Y','a','a','a','a','a','a','c','e','e','e','e','i','i','i','i','o','o','o','o','o','o','u','u','u','u','y','y'];
    $chaine = str_replace($accents, $sans, $chaine);
    $chaine = str_replace([' ', '\''], '_', $chaine);
    $chaine = preg_replace('/[^a-zA-Z0-9_]+/', '', $chaine);
    return strtolower(trim($chaine, '_'));
}

$message = ''; $type_msg = ''; $action_get = $_GET['action'] ?? 'liste';
$defunt_edit = null;

// ==========================================
// 3. TRAITEMENT DES FORMULAIRES (POST)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {

    // --- A. AJOUTER / ÉDITER UN DÉFUNT ET SES DOCUMENTS ---
    if (in_array($_POST['action'], ['ajouter', 'editer'])) {
        
        $nom = mb_convert_case(trim($_POST['nom'] ?? ''), MB_CASE_TITLE, "UTF-8");
        $prenom = mb_convert_case(trim($_POST['prenom'] ?? ''), MB_CASE_TITLE, "UTF-8");
        
        $date_naissance = !empty($_POST['date_naissance']) ? $_POST['date_naissance'] : null;
        $date_deces = !empty($_POST['date_deces']) ? $_POST['date_deces'] : null;
        $date_inhumation = !empty($_POST['date_inhumation']) ? $_POST['date_inhumation'] : null;
        $type_obseques = $_POST['type_obseques'] ?? 'Inhumation en cercueil';
        $concession_id = !empty($_POST['concession_id']) ? (int)$_POST['concession_id'] : null;
        $numero_case = null; // Champ supprimé, n'est plus utilisé
        $notes = trim($_POST['notes'] ?? '');

        if ($_POST['action'] === 'ajouter') {
            $stmt = $pdo->prepare("INSERT INTO cimetiere_defunts (concession_id, numero_case, nom, prenom, date_naissance, date_deces, date_inhumation, type_obseques, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$concession_id, $numero_case, $nom, $prenom, $date_naissance, $date_deces, $date_inhumation, $type_obseques, $notes]);
            $defunt_id = $pdo->lastInsertId();
            $message = "Défunt enregistré."; 
        } else {
            $defunt_id = (int)$_POST['id'];
            $stmt = $pdo->prepare("UPDATE cimetiere_defunts SET concession_id=?, numero_case=?, nom=?, prenom=?, date_naissance=?, date_deces=?, date_inhumation=?, type_obseques=?, notes=? WHERE id=?");
            $stmt->execute([$concession_id, $numero_case, $nom, $prenom, $date_naissance, $date_deces, $date_inhumation, $type_obseques, $notes, $defunt_id]);
            $message = "Fiche mise à jour.";
        }

        if (isset($_FILES['nouveau_document']) && $_FILES['nouveau_document']['error'] === UPLOAD_ERR_OK && !empty($_POST['type_document'])) {
            $type_doc = $_POST['type_document'];
            $ext = strtolower(pathinfo($_FILES['nouveau_document']['name'], PATHINFO_EXTENSION));
            
            $str_dossier = $nom . '_' . $prenom . '_' . ($date_naissance ?? 'inconnu') . '_' . $date_deces;
            $nom_dossier = nettoyerNomFichier($str_dossier);
            $chemin_dossier_absolu = $dossier_ged . $nom_dossier . '/';
            
            if (!is_dir($chemin_dossier_absolu)) { @mkdir($chemin_dossier_absolu, 0777, true); }

            $nom_fichier = nettoyerNomFichier($type_doc) . '.' . $ext;
            $chemin_relatif = $nom_dossier . '/' . $nom_fichier;
            
            if (@move_uploaded_file($_FILES['nouveau_document']['tmp_name'], $dossier_ged . $chemin_relatif)) {
                $check = $pdo->prepare("SELECT id FROM cimetiere_defunts_docs WHERE defunt_id = ? AND type_document = ?");
                $check->execute([$defunt_id, $type_doc]);
                if ($row = $check->fetch()) {
                    $pdo->prepare("UPDATE cimetiere_defunts_docs SET chemin_fichier = ? WHERE id = ?")->execute([$chemin_relatif, $row['id']]);
                } else {
                    $pdo->prepare("INSERT INTO cimetiere_defunts_docs (defunt_id, type_document, chemin_fichier) VALUES (?, ?, ?)")->execute([$defunt_id, $type_doc, $chemin_relatif]);
                }
            }
        }

        header("Location: cimetiere_defunts.php?action=editer&id=".$defunt_id."&msg=ok");
        exit();
    }
    
    // --- B. SUPPRIMER UN DOCUMENT SPÉCIFIQUE ---
    elseif ($_POST['action'] === 'supprimer_doc') {
        $doc_id = (int)$_POST['doc_id'];
        $defunt_id = (int)$_POST['defunt_id'];
        
        $stmt = $pdo->prepare("SELECT chemin_fichier FROM cimetiere_defunts_docs WHERE id = ?");
        $stmt->execute([$doc_id]);
        $chemin = $stmt->fetchColumn();
        
        if ($chemin && file_exists($dossier_ged . $chemin)) { @unlink($dossier_ged . $chemin); }
        $pdo->prepare("DELETE FROM cimetiere_defunts_docs WHERE id = ?")->execute([$doc_id]);
        
        header("Location: cimetiere_defunts.php?action=editer&id=".$defunt_id."&msg=doc_del");
        exit();
    }

    // --- C. SUPPRIMER LE DÉFUNT ET SON DOSSIER PHYSIQUE ---
    elseif ($_POST['action'] === 'supprimer') {
        $id = (int)$_POST['id'];
        
        $docs = $pdo->prepare("SELECT chemin_fichier FROM cimetiere_defunts_docs WHERE defunt_id = ?");
        $docs->execute([$id]);
        $dossiers_a_supprimer = [];
        
        foreach($docs->fetchAll() as $d) {
            $chemin_complet = $dossier_ged . $d['chemin_fichier'];
            if (file_exists($chemin_complet)) { @unlink($chemin_complet); }
            $dossiers_a_supprimer[] = dirname($chemin_complet);
        }
        
        $dossiers_a_supprimer = array_unique($dossiers_a_supprimer);
        foreach($dossiers_a_supprimer as $dossier) {
            if (is_dir($dossier)) {
                $fichiers = array_diff(scandir($dossier), array('.','..'));
                foreach ($fichiers as $fichier) { @unlink($dossier . '/' . $fichier); }
                @rmdir($dossier);
            }
        }
        
        $stmt_info = $pdo->prepare("SELECT nom, prenom, date_naissance, date_deces FROM cimetiere_defunts WHERE id = ?");
        $stmt_info->execute([$id]);
        $info = $stmt_info->fetch();
        if ($info) {
            $str_dossier = $info['nom'] . '_' . $info['prenom'] . '_' . ($info['date_naissance'] ?? 'inconnu') . '_' . $info['date_deces'];
            $chemin_dossier_absolu = $dossier_ged . nettoyerNomFichier($str_dossier);
            if (is_dir($chemin_dossier_absolu)) {
                $fichiers = array_diff(scandir($chemin_dossier_absolu), array('.','..'));
                foreach ($fichiers as $fichier) { @unlink($chemin_dossier_absolu . '/' . $fichier); }
                @rmdir($chemin_dossier_absolu);
            }
        }
        
        $pdo->prepare("DELETE FROM cimetiere_defunts WHERE id=?")->execute([$id]);
        header("Location: cimetiere_defunts.php?msg=del");
        exit();
    }
}

if (isset($_GET['msg'])) {
    $type_msg = "succes";
    if($_GET['msg']=='ok') $message = "Enregistrement réussi.";
    if($_GET['msg']=='del') $message = "Fiche supprimée.";
    if($_GET['msg']=='doc_del') $message = "Document supprimé de la GED.";
}

// ==========================================
// 4. RÉCUPÉRATION POUR AFFICHAGE
// ==========================================
try {
    // On récupère toutes les concessions SAUF le meuble parent (qui a pour type Columbarium)
    $raw_concessions = $pdo->query("
        SELECT id, numero_tombe, type_concession 
        FROM cimetiere_concessions 
        WHERE type_concession NOT IN ('Columbarium', 'Colombarium')
    ")->fetchAll(PDO::FETCH_ASSOC);

    // Tri naturel en PHP (comprend que 'Case 2' vient avant 'Case 10')
    usort($raw_concessions, function($a, $b) {
        return strnatcasecmp($a['numero_tombe'], $b['numero_tombe']);
    });

    $liste_concessions = $raw_concessions;
} catch (Exception $e) { 
    $liste_concessions = []; 
}

$documents_ged = [];
if ($action_get === 'editer' && isset($_GET['id'])) {
    $stmt = $pdo->prepare("SELECT * FROM cimetiere_defunts WHERE id = ?");
    $stmt->execute([(int)$_GET['id']]);
    $defunt_edit = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($defunt_edit) {
        $stmt_docs = $pdo->prepare("SELECT * FROM cimetiere_defunts_docs WHERE defunt_id = ? ORDER BY type_document ASC");
        $stmt_docs->execute([$defunt_edit['id']]);
        $documents_ged = $stmt_docs->fetchAll(PDO::FETCH_ASSOC);
    }
}

try {
    // Jointure pour récupérer le type_concession en plus du numéro
    $liste_defunts = $pdo->query("
        SELECT d.*, c.numero_tombe, c.type_concession, 
        (SELECT COUNT(*) FROM cimetiere_defunts_docs WHERE defunt_id = d.id) as nb_docs 
        FROM cimetiere_defunts d 
        LEFT JOIN cimetiere_concessions c ON d.concession_id = c.id 
        ORDER BY d.date_deces DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $liste_defunts = []; }

// Pré-remplissage des URL
$pre_selected_conc = $_GET['concession_id'] ?? ($defunt_edit['concession_id'] ?? '');
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Registre Défunts - Memoria</title>
    <link rel="stylesheet" href="css/global.css">
    <link rel="stylesheet" href="css/cimetiere.css">
    <style>
        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; background: white; padding: 20px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .table-container, .form-container { background: white; border-radius: 15px; padding: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .search-bar { width: 100%; padding: 12px; margin-bottom: 20px; border: 1px solid #ddd; border-radius: 8px; }
        table { width: 100%; border-collapse: collapse; text-align: left; }
        th, td { padding: 15px; border-bottom: 1px solid #eee; }
        .btn-primary { background: #4a7c44; color: white; border: none; padding: 10px 20px; border-radius: 8px; font-weight: bold; cursor: pointer; text-decoration: none; display: inline-block; }
        .msg { padding: 15px; border-radius: 10px; margin-bottom: 20px; font-weight: bold; }
        .succes { background: #e8f5e9; color: #2ecc71; }
        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .form-group { display: flex; flex-direction: column; margin-bottom: 15px; }
        label { font-weight: bold; margin-bottom: 5px; font-size: 0.9em; }
        input, select, textarea { padding: 10px; border: 1px solid #ccc; border-radius: 8px; }
        .badge { padding: 4px 8px; border-radius: 12px; font-size: 0.8em; font-weight: bold; background: #eee; }
        
        .capitalize-input { text-transform: capitalize; }
        
        .ged-container { background: #fdfaf6; border: 2px dashed #e6c8a5; padding: 20px; border-radius: 15px; margin-top: 25px; }
        .ged-header { display: flex; align-items: center; gap: 10px; margin-bottom: 15px; color: #d35400; font-size: 1.1em; font-weight: bold; }
        .doc-list { list-style: none; padding: 0; margin: 0 0 20px 0; }
        .doc-item { background: white; border: 1px solid #eee; padding: 10px 15px; border-radius: 8px; display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
        .doc-type { font-weight: bold; color: #333; }
        .doc-actions { display: flex; gap: 10px; }
        .ged-upload-box { background: white; padding: 15px; border-radius: 10px; border: 1px solid #ddd; display: flex; gap: 15px; align-items: flex-end; flex-wrap: wrap; }
    </style>
</head>
<body class="memoria-layout">
    <aside class="memoria-sidebar">
        <div class="memoria-sidebar-header"><img src="images/cimetiere/logo_memoria.webp" alt="Logo"><h1>Memoria</h1></div>
        <nav class="memoria-sidebar-nav">
            <a href="admin_cimetiere.php" class="memoria-nav-item">📊 Dashboard</a>
            <a href="cimetiere_plan.php" class="memoria-nav-item">🗺️ Plan</a>
            <a href="cimetiere_concessions.php" class="memoria-nav-item">📜 Concessions</a>
            <a href="cimetiere_defunts.php" class="memoria-nav-item active">⚱️ Défunts</a>
        </nav>
        <div class="memoria-sidebar-footer"><a href="index.php" class="memoria-btn-retour">← Retour au site</a></div>
    </aside>

    <main class="memoria-main-content">
        <?php if($message): ?><div class="msg <?= $type_msg ?>"><?= $message ?></div><?php endif; ?>

        <?php if ($action_get === 'liste'): ?>
            <div class="page-header"><h2>Registre des Défunts</h2><a href="?action=ajouter" class="btn-primary">+ Déclarer un défunt</a></div>
            <div class="table-container">
                <input type="text" id="searchInput" class="search-bar" placeholder="Rechercher..." onkeyup="filterTable()">
                <table id="defuntsTable">
                    <thead><tr><th>Nom & Prénoms</th><th>Décès</th><th>Emplacement</th><th style="text-align:center;">Dossier GED</th><th>Actions</th></tr></thead>
                    <tbody>
                        <?php foreach ($liste_defunts as $d): ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($d['nom'] . ' ' . $d['prenom']) ?></strong></td>
                            <td><?= date('d/m/Y', strtotime($d['date_deces'])) ?></td>
                            <td>
                                <?php if($d['numero_tombe']): ?>
                                    <strong><?= htmlspecialchars($d['numero_tombe']) ?></strong>
                                    <span style="font-size: 0.85em; color: #666; margin-left: 5px;">(<?= htmlspecialchars($d['type_concession'] ?? '') ?>)</span>
                                    <?php if($d['numero_case']): ?> 
                                        <br><small style="color: #e67e22; font-weight: bold;">Case n°<?= htmlspecialchars($d['numero_case']) ?></small> 
                                    <?php endif; ?>
                                <?php else: ?>
                                    <small style="color:red;">Non lié</small>
                                <?php endif; ?>
                            </td>
                            <td style="text-align:center;">
                                <?php if($d['nb_docs'] > 0 || !empty($d['acte_deces'])): ?>
                                    <span class="badge" style="background:#e1ede0; color:#28a745;">📁 <?= max($d['nb_docs'], 1) ?> doc(s)</span>
                                <?php else: ?> 
                                    <span style="color:#ccc;">Vide</span> 
                                <?php endif; ?>
                            </td>
                            <td><a href="?action=editer&id=<?= $d['id'] ?>" style="color:#4a7c44; font-weight:bold;">Éditer</a></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="page-header"><h2><?= $action_get == 'ajouter' ? 'Déclaration Défunt' : 'Édition Fiche & GED' ?></h2><a href="cimetiere_defunts.php" class="btn-primary" style="background:#666;">← Retour</a></div>
            
           <div class="form-container">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="<?= $action_get ?>">
                    <?php if(isset($defunt_edit['id'])): ?><input type="hidden" name="id" value="<?= $defunt_edit['id'] ?>"><?php endif; ?>

                    <div class="form-grid">
                        <div class="form-group"><label>Nom de famille</label><input type="text" name="nom" class="capitalize-input" value="<?= htmlspecialchars($defunt_edit['nom'] ?? '') ?>" required></div>
                        <div class="form-group"><label>Prénom(s)</label><input type="text" name="prenom" class="capitalize-input" value="<?= htmlspecialchars($defunt_edit['prenom'] ?? '') ?>" required></div>
                        
                        <div class="form-group"><label>Date de Naissance</label><input type="date" name="date_naissance" id="date_n" value="<?= $defunt_edit['date_naissance'] ?? '' ?>"></div>
                        <div class="form-group"><label>Date de Décès</label><input type="date" name="date_deces" id="date_d" value="<?= $defunt_edit['date_deces'] ?? '' ?>" required></div>
                        
                        <div class="form-group"><label>Type d'obsèques</label>
                            <select name="type_obseques">
                                <?php $to = $defunt_edit['type_obseques'] ?? 'Inhumation en cercueil'; ?>
                                <option value="Inhumation en cercueil" <?= $to=='Inhumation en cercueil'?'selected':'' ?>>Inhumation en cercueil</option>
                                <option value="Dépôt d'urne" <?= $to=="Dépôt d'urne"?'selected':'' ?>>Dépôt d'urne</option>
                                <option value="Dispersion des cendres" <?= $to=='Dispersion des cendres'?'selected':'' ?>>Dispersion des cendres</option>
                            </select>
                        </div>
                        
                        <div class="form-group"><label>Date Inhumation / Dispersion</label><input type="date" name="date_inhumation" id="date_i" value="<?= $defunt_edit['date_inhumation'] ?? '' ?>"></div>

                        <div class="form-group" style="grid-column: span 2;">
                            <label>Lier à un emplacement du Plan</label>
                            <select name="concession_id" style="width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 8px;">
                                <option value="">-- Sélectionner l'emplacement --</option>
                                <?php foreach($liste_concessions as $c): ?>
                                <option value="<?= $c['id'] ?>" <?= ($pre_selected_conc == $c['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($c['numero_tombe']) ?> (<?= htmlspecialchars($c['type_concession']) ?>)
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group" style="grid-column: span 2;">
                            <label>Notes & Remarques</label>
                            <textarea name="notes" rows="2"><?= htmlspecialchars($defunt_edit['notes'] ?? '') ?></textarea>
                        </div>
                    </div>

                    <div class="ged-container">
                        <div class="ged-header">📁 Dossier Numérique (GED)</div>
                        
                        <?php if($action_get === 'ajouter'): ?>
                            <p style="color:#666; font-style:italic; margin:0;">Créez d'abord la fiche du défunt pour pouvoir lui rattacher des documents.</p>
                        <?php else: ?>
                            
                            <?php if(!empty($documents_ged)): ?>
                                <ul class="doc-list">
                                    <?php foreach($documents_ged as $doc): ?>
                                        <li class="doc-item">
                                            <div>
                                                <span class="doc-type">📄 <?= htmlspecialchars($doc['type_document']) ?></span>
                                            </div>
                                            <div class="doc-actions">
                                                <a href="GED/Cimetiere/defunts/<?= $doc['chemin_fichier'] ?>" target="_blank" class="btn-primary" style="padding:5px 10px; font-size:0.9em; background:#3498db;">Consulter</a>
                                                
                                                <button type="submit" name="action" value="supprimer_doc" 
                                                        onclick="document.getElementById('delete_doc_id').value='<?= $doc['id'] ?>'; return confirm('Supprimer ce document ?');" 
                                                        style="background:#fee; color:#e74c3c; border:none; padding:5px 10px; border-radius:8px; cursor:pointer; font-weight:bold;">✖</button>
                                            </div>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php else: ?>
                                <p style="color:#999; margin-bottom:15px;">Le dossier de ce défunt est vide.</p>
                            <?php endif; ?>
                            
                            <input type="hidden" name="doc_id" id="delete_doc_id" value="">
                            <input type="hidden" name="defunt_id" value="<?= $defunt_edit['id'] ?>">

                            <div class="ged-upload-box">
                                <div class="form-group" style="flex:1; margin:0;">
                                    <label>Ajouter un document au dossier</label>
                                    <select name="type_document">
                                        <?php foreach($types_documents as $type): ?>
                                            <option value="<?= $type ?>"><?= $type ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="form-group" style="flex:2; margin:0;">
                                    <input type="file" name="nouveau_document" accept="application/pdf, image/jpeg, image/png">
                                </div>
                            </div>

                        <?php endif; ?>
                    </div>

                    <button type="submit" class="btn-primary" style="margin-top:20px; width:100%; padding:15px; font-size:1.1em;">💾 Enregistrer la fiche & les documents</button>
                    
                    <?php if($action_get == 'editer'): ?>
                        <button type="submit" name="action" value="supprimer" style="background:transparent; color:#e74c3c; margin-top:15px; width:100%; border:none; text-decoration:underline; cursor:pointer;" onclick="return confirm('⚠️ ATTENTION : Cela supprimera définitivement le défunt ET tous les documents de son dossier GED. Continuer ?');">Supprimer définitivement la fiche et le dossier</button>
                    <?php endif; ?>
                </form>
            </div>
        <?php endif; ?>
    </main>

    <script>
        function filterTable() {
            let input = document.getElementById("searchInput").value.toUpperCase();
            let rows = document.getElementById("defuntsTable").getElementsByTagName("tr");
            for (let i = 1; i < rows.length; i++) {
                rows[i].style.display = rows[i].innerText.toUpperCase().includes(input) ? "" : "none";
            }
        }
        
        const dn = document.getElementById('date_n'); 
        const dd = document.getElementById('date_d'); 
        const di = document.getElementById('date_i'); 

        function verifierDates() {
            if (dn && dn.value && dd) dd.min = dn.value;
            
            if (di) {
                if (dd && dd.value) di.min = dd.value; 
                else if (dn && dn.value) di.min = dn.value;
            }

            if (dn) {
                if (dd && dd.value) dn.max = dd.value;
                else if (di && di.value) dn.max = di.value;
            }
        }

        if(dn) dn.addEventListener('change', verifierDates);
        if(dd) dd.addEventListener('change', verifierDates);
        if(di) di.addEventListener('change', verifierDates);

        verifierDates();
    </script>
</body>
</html>