<?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();
}

// ==========================================
// CRÉATION AUTO DE LA COLONNE DE LIAISON
// ==========================================
try {
    $check = $pdo->query("SHOW COLUMNS FROM cimetiere_concessions LIKE 'parent_id'");
    if (!$check->fetch()) {
        $pdo->exec("ALTER TABLE cimetiere_concessions ADD COLUMN parent_id INT DEFAULT NULL");
    }
} catch (PDOException $e) {}

// ==========================================
// GESTION DES REQUÊTES AJAX (SANS RECHARGEMENT)
// ==========================================
if (isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    
    try {
        if ($_POST['action'] === 'save_tombe') {
            $stmt = $pdo->prepare("INSERT INTO cimetiere_concessions (numero_tombe, coord_x, coord_y, largeur, hauteur, statut, rotation, type_concession, nb_lignes, cases_par_ligne) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                trim($_POST['numero_tombe']), $_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'], $_POST['statut'], $_POST['rot'], $_POST['type_concession'], (int)$_POST['nb_lignes'], (int)$_POST['cases_par_ligne']
            ]);
            
            $id_parent = $pdo->lastInsertId();

            // CRÉATION AUTOMATIQUE DES CASES ENFANTS SI C'EST UN COLOMBARIUM
            if (in_array($_POST['type_concession'], ['Columbarium', 'Colombarium'])) {
                $nb = (int)$_POST['nb_lignes'] * (int)$_POST['cases_par_ligne'];
                for($i=1; $i<=$nb; $i++) {
                    $nom_case = trim($_POST['numero_tombe']) . " - Case $i";
                    $pdo->prepare("INSERT INTO cimetiere_concessions (numero_tombe, statut, type_concession, parent_id) VALUES (?, 'Libre', 'Case de columbarium', ?)")->execute([$nom_case, $id_parent]);
                }
            }
            
            echo json_encode(['status' => 'ok', 'id' => $id_parent]);
            exit();
        }
        
        if ($_POST['action'] === 'edit_tombe') {
            $stmt = $pdo->prepare("UPDATE cimetiere_concessions SET numero_tombe = ?, statut = ?, rotation = ?, type_concession = ?, nb_lignes = ?, cases_par_ligne = ? WHERE id = ?");
            $stmt->execute([trim($_POST['numero_tombe']), $_POST['statut'], $_POST['rot'], $_POST['type_concession'], (int)$_POST['nb_lignes'], (int)$_POST['cases_par_ligne'], (int)$_POST['id']]);
            echo json_encode(['status' => 'ok']);
            exit();
        }
        
        if ($_POST['action'] === 'update_geom') {
            $stmt = $pdo->prepare("UPDATE cimetiere_concessions SET coord_x=?, coord_y=?, largeur=?, hauteur=?, rotation=? WHERE id=?");
            $stmt->execute([$_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'], $_POST['rot'], (int)$_POST['id']]);
            echo json_encode(['status' => 'ok']);
            exit();
        }
        
        if ($_POST['action'] === 'delete_tombe') {
            // On supprime d'abord les cases liées pour éviter les données orphelines
            $stmt_enfants = $pdo->prepare("DELETE FROM cimetiere_concessions WHERE parent_id = ?");
            $stmt_enfants->execute([(int)$_POST['id']]);
            
            // Puis on supprime la structure
            $stmt = $pdo->prepare("DELETE FROM cimetiere_concessions WHERE id = ?");
            $stmt->execute([(int)$_POST['id']]);
            echo json_encode(['status' => 'ok']);
            exit();
        }

        // --- NOUVEAU : Récupération des VRAIES cases pour la grille du columbarium ---
        if ($_POST['action'] === 'get_colom_cases') {
            $id_parent = (int)$_POST['id_concession'];
            
            $stmt = $pdo->prepare("SELECT id, numero_tombe, statut FROM cimetiere_concessions WHERE parent_id = ? ORDER BY id ASC");
            $stmt->execute([$id_parent]);
            $cases = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Pour chaque case, on récupère ses défunts
            foreach($cases as &$case) {
                $stmt_def = $pdo->prepare("SELECT id, nom, prenom, date_deces FROM cimetiere_defunts WHERE concession_id = ? ORDER BY date_deces DESC");
                $stmt_def->execute([$case['id']]);
                $case['defunts'] = $stmt_def->fetchAll(PDO::FETCH_ASSOC);
            }
            
            echo json_encode(['status' => 'ok', 'cases' => $cases]);
            exit();
        }

        // --- Récupération classique (Caveau / Fosse) ---
        if ($_POST['action'] === 'get_defunts') {
            $id_concession = (int)$_POST['id_concession'];
            
            $check = $pdo->query("SHOW COLUMNS FROM cimetiere_defunts LIKE 'numero_case'");
            $has_case = $check->fetch() ? true : false;
            
            if ($has_case) {
                $stmt = $pdo->prepare("SELECT id, nom, prenom, date_deces, numero_case FROM cimetiere_defunts WHERE concession_id = ? ORDER BY date_deces DESC");
            } else {
                $stmt = $pdo->prepare("SELECT id, nom, prenom, date_deces, NULL as numero_case FROM cimetiere_defunts WHERE concession_id = ? ORDER BY date_deces DESC");
            }
            
            $stmt->execute([$id_concession]);
            echo json_encode(['status' => 'ok', 'defunts' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
            exit();
        }

    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        exit();
    }
}

$edit_mode_actif = (isset($_GET['edit']) && $_GET['edit'] == '1') ? 'true' : 'false';
$concessions = $pdo->query("SELECT c.*, (SELECT COUNT(*) FROM cimetiere_defunts d WHERE d.concession_id = c.id) as nb_defunts FROM cimetiere_concessions c")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Plan Interactif - Memoria</title>
    <link rel="stylesheet" href="css/global.css">
    <link rel="stylesheet" href="css/cimetiere.css">
    <style>
        .plan-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; background: white; padding: 15px 25px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .map-container-wrapper { width: 100%; height: calc(100vh - 160px); overflow: auto; background: #e0e0e0; border-radius: 15px; border: 2px solid #ccc; position: relative; }
        
        #scaleContainer { transform-origin: 0 0; position: absolute; top: 0; left: 0; }
        #rotateContainer { transform-origin: center center; transition: transform 0.3s ease; position: relative; display: inline-block; background-color: #ffffff; box-shadow: 0 0 20px rgba(0,0,0,0.05); }
        
        .map-image { width: 1800px; max-width: none !important; height: auto; display: block; pointer-events: none; user-select: none; opacity: 0; transition: opacity 0.3s ease; }
        .map-svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: block; }

        .tombe-group { cursor: pointer; }
        .tombe-rect { stroke: #333; stroke-width: 1.5; opacity: 0.8; transition: fill 0.2s; }
        .tombe-group:hover .tombe-rect { opacity: 1; stroke-width: 3; }
        .tombe-group.selected .tombe-rect { stroke: #3498db; stroke-width: 3; stroke-dasharray: 4; opacity: 1; }
        
        .tombe-text { fill: #111; font-weight: 800; pointer-events: none; text-shadow: 1px 1px 0px rgba(255,255,255,0.8), -1px -1px 0px rgba(255,255,255,0.8); }

        .resize-handle { fill: #3498db; stroke: white; stroke-width: 2; cursor: nwse-resize; transition: fill 0.2s; }
        .resize-handle:hover { fill: #2980b9; } 
        
        .dragging .tombe-rect { opacity: 0.5; stroke: white; stroke-dasharray: 4; cursor: grabbing !important; }

        .statut-Occupee { fill: #95a5a6; } .statut-Libre { fill: #2ecc71; } .statut-Expiree { fill: #e74c3c; } .statut-Abandonnee { fill: #f39c12; }

        .edit-mode-active { cursor: crosshair !important; border-color: #e74c3c !important; }
        .btn-toggle-edit { background: #e74c3c; color: white; border: none; padding: 10px 20px; border-radius: 8px; font-weight: bold; cursor: pointer; transition: 0.3s; }
        .btn-toggle-edit.active { background: #27ae60; }

        .map-controls button { background: white; border: 1px solid #ccc; padding: 5px 15px; cursor: pointer; font-weight: bold; border-radius: 5px; margin-left: 5px; transition: 0.2s; }
        .map-controls button:hover { background: #f0f0f0; }
        .map-controls button.active-toggle { background: #e1ede0; color: #4a7c44; border-color: #4a7c44; }

        .editor-panel { display: none; position: fixed; right: 30px; top: 100px; width: 320px; background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(10px); padding: 25px; border-radius: 15px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); z-index: 2000; border: 1px solid #ddd; }
        .editor-panel h3 { margin-top: 0; color: #4a7c44; border-bottom: 2px solid #eee; padding-bottom: 10px; }
        .editor-panel label { display: block; font-weight: bold; font-size: 0.9em; margin-top: 15px; color: #333; }
        .editor-panel input[type="text"], .editor-panel input[type="number"], .editor-panel select { width: 100%; padding: 10px; margin-top: 5px; border: 1px solid #ccc; border-radius: 8px; box-sizing: border-box; }
        
        .range-container { display: flex; align-items: center; gap: 10px; margin-top: 5px; }
        .range-container input[type="range"] { flex-grow: 1; }
        .range-value { font-weight: bold; color: #4a7c44; width: 45px; text-align: right; }
        
        .rot-btn { background: #f0f4f0; color: #4a7c44; border: 1px solid #c8e6c9; padding: 8px 10px; flex: 1; border-radius: 8px; font-weight: bold; cursor: pointer; transition: 0.2s; }
        .rot-btn:hover { background: #e1ede0; }

        .btn-save { background: #4a7c44; color: white; border: none; padding: 12px; width: 100%; border-radius: 8px; font-weight: bold; cursor: pointer; margin-top: 20px;}
        .btn-delete { background: #e74c3c; margin-top: 10px; }
        .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;}
        .btn-secondary { background: #e0e0e0; color: #333; border: none; padding: 10px 20px; border-radius: 8px; font-weight: bold; cursor: pointer; }
        .close-panel { position: absolute; top: 15px; right: 20px; cursor: pointer; font-size: 24px; color: #999; line-height: 1; padding: 5px;}
        .close-panel:hover { color: #e74c3c; }
        
        #toast { display: none; position: fixed; bottom: 30px; right: 30px; background: #2ecc71; color: white; padding: 15px 25px; border-radius: 8px; font-weight: bold; box-shadow: 0 4px 10px rgba(0,0,0,0.2); z-index: 3000; }
        
        .colombarium-options { background: #f9fbf9; padding: 15px; border-radius: 8px; border: 1px dashed #c8e6c9; margin-top: 10px; display: none; }
        .colombarium-options label { margin-top: 5px; }
        .colombarium-options .grid-inputs { display: flex; gap: 10px; }

        .modal { display: none; position: fixed; z-index: 4000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); align-items: center; justify-content: center; }
        .modal-content { background-color: #fff; padding: 30px; border-radius: 15px; width: 90%; max-width: 800px; box-shadow: 0 5px 30px rgba(0,0,0,0.3); }
        .colom-grid { display: grid; gap: 15px; background: #f9fbf9; padding: 20px; border-radius: 12px; border: 1px solid #e1ede0; margin-top: 20px; overflow: auto; max-height: 60vh; }
        .colom-case { background: white; border: 2px solid #ddd; border-radius: 8px; padding: 20px 10px; text-align: center; cursor: pointer; transition: 0.2s; display: flex; flex-direction: column; align-items: center; justify-content: center; box-shadow: 0 2px 5px rgba(0,0,0,0.02); }
        .colom-case:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
        
        .colom-case.free { border-color: #2ecc71; }
        .colom-case.free:hover { background-color: #f0fdf4; }
        .colom-case.occupied { border-color: #e67e22; background-color: #fdfaf6; }
        .colom-case.occupied:hover { background-color: #faeedf; }
        
        .btn-fermer-modal { background: #999; color: white; border: none; padding: 10px 20px; border-radius: 8px; font-weight: bold; cursor: pointer; margin-top: 20px; width: 100%; font-size: 1.1em; }
        
        .defunt-list-item { background: #f9fbf9; padding: 10px; border-radius: 8px; border: 1px solid #eee; margin-bottom: 8px; font-size: 0.9em; }
    </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"><span class="memoria-nav-icon">📊</span> Tableau de bord</a>
            <a href="cimetiere_plan.php" class="memoria-nav-item active"><span class="memoria-nav-icon">🗺️</span> Plan interactif</a>
            <a href="cimetiere_concessions.php" class="memoria-nav-item"><span class="memoria-nav-icon">📜</span> Concessions</a>
            <a href="cimetiere_defunts.php" class="memoria-nav-item"><span class="memoria-nav-icon">⚱️</span> Registre des 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">
        <div class="plan-header">
            <h2 style="margin: 0;">Plan du Cimetière</h2>
            <div style="display: flex; gap: 20px; align-items:center;">
                <div class="map-controls">
                    <button onclick="rotateGlobalMap(-90)" title="Tourner le plan entier à gauche">⟲</button>
                    <button onclick="rotateGlobalMap(90)" title="Tourner le plan entier à droite">⟳</button>
                    <button onclick="resetMapView()" title="Réinitialiser le zoom et centrer la vue">🎯</button>
                    
                    <span style="border-left: 1px solid #ccc; margin: 0 5px;"></span>
                    
                    <button id="btnToggleImage" onclick="toggleMapImage()" title="Afficher ou masquer l'image dessinée">👁️ Afficher le calque</button>
                    
                    <span style="border-left: 1px solid #ccc; margin: 0 5px;"></span>
                    <button onclick="zoomMap(-0.1)">-</button> 
                    <span id="zoom-level" style="margin:0 5px; font-weight:bold;">100%</span> 
                    <button onclick="zoomMap(0.1)">+</button>
                </div>
                <button id="btnEditMode" class="btn-toggle-edit" onclick="toggleEditMode()">Mode Édition : OFF</button>
            </div>
        </div>

        <div class="map-container-wrapper" id="mapWrapper">
            <div id="scrollSpacer" style="position: absolute; top: 0; left: 0; z-index: -1;"></div>
            
            <div id="scaleContainer">
                <div id="rotateContainer">
                    <img src="images/cimetiere/plan_cimetiere.jpg" class="map-image" id="mapImage" onload="updateMapTransform()">
                    <svg class="map-svg" id="mapSvg" onmousedown="handleMapClick(event)">
                        
                        <circle id="resizeHandle" class="resize-handle" r="8" cx="0" cy="0" style="display:none;" onmousedown="startResize(event)"></circle>

                        <?php foreach($concessions as $c): 
                            if ($c['coord_x'] === null) continue;
                            $x = number_format((float)$c['coord_x'], 2, '.', '');
                            $y = number_format((float)$c['coord_y'], 2, '.', '');
                            $w = number_format((float)$c['largeur'], 2, '.', '');
                            $h = number_format((float)$c['hauteur'], 2, '.', '');
                            $rot = number_format((float)$c['rotation'], 2, '.', '');
                            $type_concession = htmlspecialchars($c['type_concession'] ?? 'Caveau');
                            $lignes = max(1, (int)($c['nb_lignes'] ?? 1));
                            $cases = max(1, (int)($c['cases_par_ligne'] ?? 1));
                            
                            $fontSize = max(4, min($w, $h) * 0.40);
                            $texte = trim($c['numero_tombe']);
                            $textLen = mb_strlen($texte);
                            
                            if ($textLen > 0) {
                                $largeurEstimee = $textLen * ($fontSize * 0.65);
                                $largeurMaxAutorisee = $w * 0.85; 
                                if ($largeurEstimee > $largeurMaxAutorisee) {
                                    $fontSize = $fontSize * ($largeurMaxAutorisee / $largeurEstimee);
                                }
                            }
                        ?>
                            <g class="tombe-group" 
                               transform="translate(<?= $x ?>, <?= $y ?>) rotate(<?= $rot ?>)"
                               data-id="<?= $c['id'] ?>" data-num="<?= htmlspecialchars($texte) ?>" 
                               data-statut="<?= $c['statut'] ?>" data-defunts="<?= $c['nb_defunts'] ?>"
                               data-x="<?= $x ?>" data-y="<?= $y ?>" data-w="<?= $w ?>" data-h="<?= $h ?>" data-rot="<?= $rot ?>"
                               data-type="<?= $type_concession ?>" data-lignes="<?= $lignes ?>" data-cases="<?= $cases ?>"
                               onmousedown="startDrag(event, this)" onclick="selectTombe(this, event)">
                               
                                <rect class="tombe-rect statut-<?= htmlspecialchars(str_replace('é', 'e', $c['statut'])) ?>" 
                                      x="0" y="0" width="<?= $w ?>" height="<?= $h ?>"></rect>
                                      
                                <text class="tombe-text" x="<?= $w/2 ?>" y="<?= $h/2 ?>" 
                                      font-size="<?= number_format($fontSize, 2, '.', '') ?>" text-anchor="middle" dominant-baseline="central"
                                      transform="rotate(<?= -$rot ?>, <?= $w/2 ?>, <?= $h/2 ?>)">
                                    <?= htmlspecialchars($texte) ?>
                                </text>
                            </g>
                        <?php endforeach; ?>
                    </svg>
                </div>
            </div>
        </div>
    </main>

    <div id="modalColombarium" class="modal">
        <div class="modal-content">
            <h3 style="margin-top: 0; color: #4a7c44; font-size: 1.5em; border-bottom: 2px solid #eee; padding-bottom: 15px;">
                Colombarium : <span id="colom_title"></span>
            </h3>
            <p style="color: #666; margin-bottom: 0;">Cliquez sur une case pour en voir les détails ou y affecter un défunt.</p>
            <div id="colom_grid" class="colom-grid"></div>
            <button type="button" class="btn-fermer-modal" onclick="document.getElementById('modalColombarium').style.display='none'">Fermer le colombarium</button>
        </div>
    </div>

    <div id="modalCaseDetails" class="modal" style="z-index: 5000;">
        <div class="modal-content" style="max-width: 500px;">
            <h3 id="case_detail_title" style="margin-top: 0; color: #e67e22; border-bottom: 2px solid #eee; padding-bottom: 10px;">Détails de la case</h3>
            <div id="case_defunts_list" style="margin: 20px 0; max-height: 250px; overflow-y: auto;"></div>
            
            <div style="display: flex; gap: 10px;">
                <a id="btn_add_defunt_case" href="#" class="btn-primary" style="flex:1; text-align:center;">+ Attribuer un défunt</a>
                <button type="button" class="btn-secondary" style="flex:1;" onclick="document.getElementById('modalCaseDetails').style.display='none'">Retour</button>
            </div>
        </div>
    </div>

    <div id="editorPanel" class="editor-panel">
        <span class="close-panel" onclick="deselectTombe()">&times;</span>
        <h3 id="panelTitle">Détails</h3>
        
       <div id="viewModeContent">
            <p><strong>Emplacement :</strong> <span id="view_num"></span></p>
            <p><strong>Statut :</strong> <span id="view_statut"></span></p>
            <p><strong>Type :</strong> <span id="view_type"></span></p>
            
            <h4 style="margin-bottom: 5px; color: #4a7c44; border-top: 1px solid #eee; padding-top: 15px;">Défunts enregistrés :</h4>
            <div id="view_defunts_list" style="max-height: 200px; overflow-y: auto;"></div>
            
            <a id="btn_add_defunt_caveau" href="#" class="btn-primary" style="display:block; text-align:center; margin-top: 15px; font-size: 0.9em;">+ Attribuer un défunt</a>
        </div>

        <div id="editModeContent" style="display: none;">
            <label>Numéro / Référence :</label>
            <input type="text" id="edit_num" placeholder="Ex: A-01, COL-01" onkeyup="updateLiveText(this.value)">
            
            <label>Type d'emplacement :</label>
<select id="edit_type" onchange="toggleColombariumOptions()">
                <option value="Caveau">Tombe / Caveau</option>
                <option value="Columbarium">Columbarium</option>
                <option value="Jardin du souvenir">Jardin du souvenir</option>
                <option value="Cave urne">Cave urne</option>
                <option value="Fosse commune">Fosse commune</option>
            </select>

            <div id="colombarium_options" class="colombarium-options">
                <div class="grid-inputs">
                    <div style="flex:1;">
                        <label>Lignes :</label>
                        <input type="number" id="edit_lignes" min="1" value="1">
                    </div>
                    <div style="flex:1;">
                        <label>Cases / ligne :</label>
                        <input type="number" id="edit_cases" min="1" value="1">
                    </div>
                </div>
            </div>
            
            <label>Statut global :</label>
            <select id="edit_statut" onchange="updateTombeColor(this.value)">
                <option value="Libre">Libre</option><option value="Occupée">Occupée</option>
                <option value="Expirée">Expirée</option><option value="Abandonnée">Abandonnée</option>
            </select>
            
            <label>Rotation de la zone :</label>
            <div class="range-container">
                <input type="range" id="edit_rot" min="0" max="360" value="0" oninput="updateLiveRotation(this.value)" onchange="saveGeometry()">
                <span class="range-value" id="rot_display">0°</span>
            </div>
            
            <div style="display: flex; gap: 10px; margin-top: 10px;">
                <button type="button" class="rot-btn" onclick="rotateTombe90(-90)">⟲ -90°</button>
                <button type="button" class="rot-btn" onclick="rotateTombe90(90)">⟳ +90°</button>
            </div>

            <button class="btn-save" onclick="saveTombeInfo()">Enregistrer les infos</button>
            <button class="btn-save btn-delete" id="btnDelete" onclick="deleteTombe()">Supprimer du plan</button>
        </div>
    </div>
    
    <div id="toast">✅ Enregistré avec succès !</div>

    <script>
        let currentZoom = 1;
        let mapRotation = parseInt(localStorage.getItem('memoriaMapRotation')) || 0;
        let isEditMode = false;
        let selectedTomb = null;
        let isImageVisible = false;

        updateMapTransform();
        if (<?= $edit_mode_actif ?>) toggleEditMode();

        function adjustTextSize(groupElement) {
            let textEl = groupElement.querySelector('.tombe-text');
            if (!textEl) return;
            
            let rectW = parseFloat(groupElement.getAttribute('data-w'));
            let rectH = parseFloat(groupElement.getAttribute('data-h'));
            let texte = textEl.textContent.trim();
            
            let baseFontSize = Math.max(4, Math.min(rectW, rectH) * 0.40);
            
            if (texte.length > 0) {
                let largeurEstimee = texte.length * (baseFontSize * 0.65);
                let largeurMaxAutorisee = rectW * 0.85; 
                if (largeurEstimee > largeurMaxAutorisee) {
                    baseFontSize = baseFontSize * (largeurMaxAutorisee / largeurEstimee);
                }
            }
            textEl.setAttribute('font-size', baseFontSize);
        }

        function toggleColombariumOptions() {
            let type = document.getElementById('edit_type').value;
            // On vérifie les deux orthographes pour être tranquille
            document.getElementById('colombarium_options').style.display = (type === 'Columbarium' || type === 'Colombarium') ? 'block' : 'none';
        }

        // --- NOUVEAU : GÉNÉRATION DU MODAL BASÉ SUR LES VRAIES CASES ---
        function openColombariumModal(id_parent, num, lignes, cases) {
            document.getElementById('colom_title').innerText = num;
            const grid = document.getElementById('colom_grid');
            
            grid.style.gridTemplateColumns = `repeat(${cases}, 1fr)`;
            grid.innerHTML = '<p style="grid-column: 1 / -1; text-align: center;">Chargement des données...</p>';
            document.getElementById('modalColombarium').style.display = 'flex';

            let fd = new FormData();
            fd.append('ajax', '1');
            fd.append('action', 'get_colom_cases');
            fd.append('id_concession', id_parent);

            fetch('cimetiere_plan.php', { method: 'POST', body: fd })
            .then(r => r.json())
            .then(data => {
                grid.innerHTML = '';
                
                if (data.status === 'ok') {
                    if (data.cases.length === 0) {
                        grid.innerHTML = '<p style="grid-column: 1 / -1; text-align: center; color: #888;">Ce meuble n\'a pas encore ses cases. Veuillez le supprimer du plan et le recréer pour générer les cases administratives.</p>';
                        return;
                    }

                    data.cases.forEach((caseData, index) => {
                        let isOccupied = (caseData.statut !== 'Libre' && caseData.statut !== 'Abandonnée');
                        
                        let colorText = isOccupied ? '#e67e22' : '#2ecc71';
                        let colorNum = isOccupied ? '#d35400' : '#27ae60';

                        let div = document.createElement('div');
                        div.className = 'colom-case ' + (isOccupied ? 'occupied' : 'free');
                        div.innerHTML = `
                            <span style="color:#888; font-size:0.85em; text-transform:uppercase;">Case</span>
                            <span style="font-size:1.8em; color:${colorNum}; margin-top:5px; font-weight:bold;">${index + 1}</span>
                            <span style="font-size:0.85em; margin-top:5px; font-weight:bold; color:${colorText};">${caseData.statut}</span>
                        `;
                        
                        div.onclick = function() {
                            // On passe l'ID de la CASE (caseData.id), et non plus l'ID de la structure !
                            openCaseDetails(caseData.id, num, index + 1, caseData.defunts);
                        };
                        
                        grid.appendChild(div);
                    });
                }
            })
            .catch(err => grid.innerHTML = '<p style="color:red; grid-column: 1 / -1;">Erreur de chargement.</p>');
        }

        function openCaseDetails(id_case, ref_colombarium, num_case, defuntsArray) {
            document.getElementById('case_detail_title').innerText = `Colombarium ${ref_colombarium} - Case n°${num_case}`;
            
            let listContainer = document.getElementById('case_defunts_list');
            let btnAdd = document.getElementById('btn_add_defunt_case');
            
            // Le défunt sera maintenant lié directement à la case administrative !
            btnAdd.href = `cimetiere_defunts.php?action=ajouter&concession_id=${id_case}`;
            
            if (defuntsArray.length === 0) {
                listContainer.innerHTML = '<p style="color:#888; font-style:italic;">Aucun défunt enregistré pour le moment.</p>';
            } else {
                let html = '';
                defuntsArray.forEach(d => {
                    let dateD = d.date_deces ? new Date(d.date_deces).toLocaleDateString('fr-FR') : 'Inconnue';
                    html += `
                        <div class="defunt-list-item">
                            <strong style="color:#333; font-size:1.1em;">${d.nom} ${d.prenom}</strong><br>
                            <span style="color:#666;">Décès : ${dateD}</span>
                        </div>
                    `;
                });
                listContainer.innerHTML = html;
            }
            
            document.getElementById('modalCaseDetails').style.display = 'flex';
        }

        function toggleMapImage() {
            isImageVisible = !isImageVisible;
            let img = document.getElementById('mapImage');
            let btn = document.getElementById('btnToggleImage');
            
            if (isImageVisible) {
                img.style.opacity = '1';
                btn.innerText = "👁️ Masquer le calque";
                btn.classList.add('active-toggle');
            } else {
                img.style.opacity = '0';
                btn.innerText = "👁️ Afficher le calque";
                btn.classList.remove('active-toggle');
            }
        }

        document.getElementById('mapWrapper').addEventListener('wheel', function(e) {
            e.preventDefault();
            let zoomFactor = e.deltaY > 0 ? 0.95 : 1.05; 
            let newZoom = Math.min(Math.max(0.3, currentZoom * zoomFactor), 4);
            if (newZoom === currentZoom) return;

            let wrapper = document.getElementById('mapWrapper');
            let rect = wrapper.getBoundingClientRect();
            let mouseX = e.clientX - rect.left;
            let mouseY = e.clientY - rect.top;

            let mapX = (wrapper.scrollLeft + mouseX) / currentZoom;
            let mapY = (wrapper.scrollTop + mouseY) / currentZoom;

            currentZoom = newZoom;
            updateMapTransform();
            document.getElementById('zoom-level').innerText = Math.round(currentZoom * 100) + '%';

            wrapper.scrollLeft = (mapX * currentZoom) - mouseX;
            wrapper.scrollTop = (mapY * currentZoom) - mouseY;
        }, { passive: false });

        function zoomMap(delta) {
            currentZoom = Math.min(Math.max(0.3, currentZoom + delta), 4);
            updateMapTransform();
            document.getElementById('zoom-level').innerText = Math.round(currentZoom * 100) + '%';
        }

        function rotateGlobalMap(deg) {
            mapRotation = (mapRotation + deg) % 360;
            localStorage.setItem('memoriaMapRotation', mapRotation);
            updateMapTransform();
        }

        function updateMapTransform() {
            let scaleC = document.getElementById('scaleContainer');
            let rotateC = document.getElementById('rotateContainer');
            let spacer = document.getElementById('scrollSpacer');
            
            scaleC.style.transform = `scale(${currentZoom})`;
            rotateC.style.transform = `rotate(${mapRotation}deg)`;
            
            spacer.style.width = (rotateC.offsetWidth * currentZoom) + 'px';
            spacer.style.height = (rotateC.offsetHeight * currentZoom) + 'px';
        }

        function resetMapView() {
            currentZoom = 1; mapRotation = 0;
            localStorage.setItem('memoriaMapRotation', 0);
            updateMapTransform();
            document.getElementById('zoom-level').innerText = '100%';
            
            let wrapper = document.getElementById('mapWrapper');
            setTimeout(() => {
                wrapper.scrollLeft = (wrapper.scrollWidth - wrapper.clientWidth) / 2;
                wrapper.scrollTop = (wrapper.scrollHeight - wrapper.clientHeight) / 2;
            }, 10);
        }

        function toggleEditMode() {
            isEditMode = !isEditMode;
            document.getElementById('btnEditMode').innerText = isEditMode ? "Mode Édition : ON" : "Mode Édition : OFF";
            document.getElementById('btnEditMode').classList.toggle('active', isEditMode);
            document.getElementById('mapWrapper').classList.toggle('edit-mode-active', isEditMode);
            deselectTombe();
        }

        function getSVGCoords(evt, targetElement) {
            let pt = document.getElementById('mapSvg').createSVGPoint();
            pt.x = evt.clientX; pt.y = evt.clientY;
            return pt.matrixTransform(targetElement.getScreenCTM().inverse());
        }

        function showToast(msg = "✅ Enregistré avec succès !") {
            let t = document.getElementById('toast');
            t.innerText = msg; t.style.display = 'block';
            setTimeout(() => { t.style.display = 'none'; }, 3000);
        }

        function selectTombe(gElement, evt) {
            if (evt) evt.stopPropagation();
            if (selectedTomb === gElement) {
                document.getElementById('editorPanel').style.display = 'block';
                return;
            }
            deselectTombe();
            
            selectedTomb = gElement;
            selectedTomb.classList.add('selected');
            
            const handle = document.getElementById('resizeHandle');
            selectedTomb.appendChild(handle);
            handle.setAttribute('cx', selectedTomb.getAttribute('data-w'));
            handle.setAttribute('cy', selectedTomb.getAttribute('data-h'));
            
            let id_concession = selectedTomb.getAttribute('data-id');
            
            // --- CORRECTION ANTI-BUG ORTHOGRAPHE ---
            let type = selectedTomb.getAttribute('data-type') || 'Caveau';
            if (type === 'Colombarium') type = 'Columbarium'; // Force le U
            
            if (isEditMode) {
                handle.style.display = 'block';
                document.getElementById('editModeContent').style.display = 'block';
                document.getElementById('viewModeContent').style.display = 'none';
                
                document.getElementById('edit_num').value = selectedTomb.getAttribute('data-num');
                document.getElementById('edit_statut').value = selectedTomb.getAttribute('data-statut');
                document.getElementById('edit_rot').value = selectedTomb.getAttribute('data-rot');
                document.getElementById('rot_display').innerText = selectedTomb.getAttribute('data-rot') + '°';
                document.getElementById('panelTitle').innerText = id_concession === 'new' ? "Nouvelle Zone" : "Édition de Zone";
                
                // Ici, "type" est maintenant garanti d'être "Columbarium"
                document.getElementById('edit_type').value = type;
                document.getElementById('edit_lignes').value = selectedTomb.getAttribute('data-lignes') || 1;
                document.getElementById('edit_cases').value = selectedTomb.getAttribute('data-cases') || 1;
                toggleColombariumOptions();
                
                document.getElementById('btnDelete').style.display = id_concession === 'new' ? 'none' : 'block';
                document.getElementById('editorPanel').style.display = 'block';
            } else {
                handle.style.display = 'none';
                document.getElementById('editModeContent').style.display = 'none';
                
                if(type === 'Columbarium') {
                    document.getElementById('editorPanel').style.display = 'none';
                    let num = selectedTomb.getAttribute('data-num');
                    let l = parseInt(selectedTomb.getAttribute('data-lignes')) || 1;
                    let c = parseInt(selectedTomb.getAttribute('data-cases')) || 1;
                    openColombariumModal(id_concession, num, l, c);
                    return; 
                }
                
                document.getElementById('viewModeContent').style.display = 'block';
                document.getElementById('view_num').innerText = selectedTomb.getAttribute('data-num');
                document.getElementById('view_statut').innerText = selectedTomb.getAttribute('data-statut');
                document.getElementById('view_type').innerText = type;
                document.getElementById('panelTitle').innerText = "Consultation";
                
                document.getElementById('btn_add_defunt_caveau').href = `cimetiere_defunts.php?action=ajouter&concession_id=${id_concession}`;
                
                let listContainer = document.getElementById('view_defunts_list');
                listContainer.innerHTML = '<p style="color:#888; font-style:italic;">Chargement...</p>';
                
                let fd = new FormData();
                fd.append('ajax', '1');
                fd.append('action', 'get_defunts');
                fd.append('id_concession', id_concession);

                fetch('cimetiere_plan.php', { method: 'POST', body: fd })
                .then(r => r.json())
                .then(data => {
                    if (data.status === 'ok') {
                        if(data.defunts.length === 0) {
                            listContainer.innerHTML = '<p style="color:#888; font-style:italic;">Aucun défunt enregistré.</p>';
                        } else {
                            let html = '';
                            data.defunts.forEach(d => {
                                let dateD = d.date_deces ? new Date(d.date_deces).toLocaleDateString('fr-FR') : 'Inconnue';
                                html += `<div class="defunt-list-item"><strong>${d.nom} ${d.prenom}</strong><br><small>Décès : ${dateD}</small></div>`;
                            });
                            listContainer.innerHTML = html;
                        }
                    } else {
                        listContainer.innerHTML = '<p style="color:red;">Erreur de chargement.</p>';
                    }
                }).catch(err => {
                    listContainer.innerHTML = '<p style="color:red;">Erreur réseau.</p>';
                });

                document.getElementById('editorPanel').style.display = 'block';
            }
        }

        function deselectTombe() {
            try {
                document.getElementById('editorPanel').style.display = 'none';
                
                const handle = document.getElementById('resizeHandle');
                if (handle) {
                    handle.style.display = 'none';
                    document.getElementById('mapSvg').appendChild(handle);
                }

                if (selectedTomb) {
                    if (selectedTomb.getAttribute('data-id') === 'new') {
                        selectedTomb.remove(); 
                    } else {
                        selectedTomb.classList.remove('selected');
                    }
                    selectedTomb = null;
                }
            } catch (error) { console.error(error); }
        }

        function handleMapClick(e) {
            if (!isEditMode) return;
            if (e.target.tagName === 'rect' || e.target.tagName === 'circle' || e.target.tagName === 'text' || e.target.tagName === 'line') return; 

            deselectTombe(); 
            let coords = getSVGCoords(e, document.getElementById('mapSvg'));
            
            const svgNS = "http://www.w3.org/2000/svg";
            let g = document.createElementNS(svgNS, "g");
            g.setAttribute('class', 'tombe-group');
            g.setAttribute('transform', `translate(${coords.x}, ${coords.y}) rotate(0)`);
            g.setAttribute('data-id', 'new');
            g.setAttribute('data-num', '');
            g.setAttribute('data-statut', 'Libre');
            g.setAttribute('data-type', 'Caveau');
            g.setAttribute('data-lignes', '1');
            g.setAttribute('data-cases', '1');
            g.setAttribute('data-defunts', '0');
            g.setAttribute('data-w', '40');
            g.setAttribute('data-h', '40');
            g.setAttribute('data-rot', '0');
            g.setAttribute('data-x', coords.x);
            g.setAttribute('data-y', coords.y);
            g.onmousedown = function(evt) { startDrag(evt, this); };
            g.onclick = function(evt) { selectTombe(this, evt); };

            let rect = document.createElementNS(svgNS, "rect");
            rect.setAttribute('class', 'tombe-rect statut-Libre');
            rect.setAttribute('x', '0'); rect.setAttribute('y', '0');
            rect.setAttribute('width', '40'); rect.setAttribute('height', '40');
            
            let text = document.createElementNS(svgNS, "text");
            text.setAttribute('class', 'tombe-text');
            text.setAttribute('x', '20'); text.setAttribute('y', '20');
            text.setAttribute('font-size', '10');
            text.setAttribute('text-anchor', 'middle');
            text.setAttribute('dominant-baseline', 'central');
            text.setAttribute('transform', 'rotate(0, 20, 20)'); 
            text.textContent = '...';
            
            g.appendChild(rect);
            g.appendChild(text);
            document.getElementById('mapSvg').appendChild(g);
            selectTombe(g);
        }

        let isDragging = false, isResizing = false;
        let offset = { x: 0, y: 0 };

        function startDrag(evt, el) {
            if (!isEditMode || evt.button !== 0) return;
            selectTombe(el, evt);
            isDragging = true;
            
            let tx = parseFloat(el.getAttribute('data-x')) || 0;
            let ty = parseFloat(el.getAttribute('data-y')) || 0;

            let mousePt = getSVGCoords(evt, document.getElementById('mapSvg'));
            offset.x = mousePt.x - tx;
            offset.y = mousePt.y - ty;
            el.classList.add('dragging');
        }

        function startResize(evt) {
            if (!isEditMode) return;
            evt.stopPropagation(); 
            isResizing = true;
        }

        window.addEventListener('mousemove', function(evt) {
            if (!selectedTomb) return;
            
            if (isDragging) {
                evt.preventDefault();
                let mousePt = getSVGCoords(evt, document.getElementById('mapSvg'));
                let newX = mousePt.x - offset.x;
                let newY = mousePt.y - offset.y;
                let rot = selectedTomb.getAttribute('data-rot') || 0;
                
                selectedTomb.setAttribute('data-x', newX);
                selectedTomb.setAttribute('data-y', newY);
                selectedTomb.setAttribute('transform', `translate(${newX}, ${newY}) rotate(${rot})`);
            }
            
            if (isResizing) {
                evt.preventDefault();
                let localPt = getSVGCoords(evt, selectedTomb);
                let newW = Math.max(10, localPt.x);
                let newH = Math.max(10, localPt.y);
                
                selectedTomb.setAttribute('data-w', newW);
                selectedTomb.setAttribute('data-h', newH);
                
                selectedTomb.querySelector('.tombe-rect').setAttribute('width', newW);
                selectedTomb.querySelector('.tombe-rect').setAttribute('height', newH);
                
                let textEl = selectedTomb.querySelector('.tombe-text');
                if (textEl) {
                    textEl.setAttribute('x', newW / 2);
                    textEl.setAttribute('y', newH / 2);
                    let currentRot = selectedTomb.getAttribute('data-rot') || 0;
                    textEl.setAttribute('transform', `rotate(-${currentRot}, ${newW/2}, ${newH/2})`); 
                    adjustTextSize(selectedTomb);
                }
                
                document.getElementById('resizeHandle').setAttribute('cx', newW);
                document.getElementById('resizeHandle').setAttribute('cy', newH);
            }
        });

        window.addEventListener('mouseup', function() {
            if (isDragging || isResizing) {
                isDragging = false;
                isResizing = false;
                if(selectedTomb) selectedTomb.classList.remove('dragging');
                saveGeometry(); 
            }
        });

        function updateLiveRotation(val) {
            if(!selectedTomb) return;
            document.getElementById('rot_display').innerText = val + '°';
            selectedTomb.setAttribute('data-rot', val);
            
            let x = selectedTomb.getAttribute('data-x');
            let y = selectedTomb.getAttribute('data-y');
            selectedTomb.setAttribute('transform', `translate(${x}, ${y}) rotate(${val})`);
            
            let textEl = selectedTomb.querySelector('.tombe-text');
            if (textEl) {
                let w = selectedTomb.getAttribute('data-w');
                let h = selectedTomb.getAttribute('data-h');
                textEl.setAttribute('transform', `rotate(-${val}, ${w/2}, ${h/2})`);
            }
        }
        
        function rotateTombe90(deg) {
            if(!selectedTomb) return;
            let currentRot = parseFloat(selectedTomb.getAttribute('data-rot')) || 0;
            let newRot = Math.round((currentRot + deg + 360) % 360); 
            
            document.getElementById('edit_rot').value = newRot;
            updateLiveRotation(newRot);
            saveGeometry();
            showToast("Rotation enregistrée");
        }

        function updateTombeColor(statut) {
            if(!selectedTomb) return;
            let rect = selectedTomb.querySelector('.tombe-rect');
            rect.className.baseVal = `tombe-rect statut-${statut.replace('é', 'e')}`;
            selectedTomb.setAttribute('data-statut', statut);
        }
        
        function updateLiveText(val) {
            if(!selectedTomb) return;
            let textEl = selectedTomb.querySelector('.tombe-text');
            if (textEl) {
                textEl.textContent = val;
                adjustTextSize(selectedTomb);
            }
        }

        function saveGeometry() {
            if(!selectedTomb || selectedTomb.getAttribute('data-id') === 'new') return;
            
            let fd = new FormData();
            fd.append('ajax', '1'); fd.append('action', 'update_geom');
            fd.append('id', selectedTomb.getAttribute('data-id')); 
            fd.append('x', selectedTomb.getAttribute('data-x')); 
            fd.append('y', selectedTomb.getAttribute('data-y'));
            fd.append('w', selectedTomb.getAttribute('data-w')); 
            fd.append('h', selectedTomb.getAttribute('data-h')); 
            fd.append('rot', selectedTomb.getAttribute('data-rot'));
            
            fetch('cimetiere_plan.php', { method: 'POST', body: fd });
        }

        function saveTombeInfo() {
            let id = selectedTomb.getAttribute('data-id');
            let num = document.getElementById('edit_num').value;
            let statut = document.getElementById('edit_statut').value;
            let rot = document.getElementById('edit_rot').value;
            
            let type_concession = document.getElementById('edit_type').value;
            let nb_lignes = document.getElementById('edit_lignes').value;
            let cases_par_ligne = document.getElementById('edit_cases').value;
            
            if(!num) { alert("Saisissez une référence pour cette zone."); return; }

            selectedTomb.setAttribute('data-num', num);
            selectedTomb.setAttribute('data-type', type_concession);
            selectedTomb.setAttribute('data-lignes', nb_lignes);
            selectedTomb.setAttribute('data-cases', cases_par_ligne);
            
            updateLiveText(num); 
            
            let fd = new FormData();
            fd.append('ajax', '1'); fd.append('numero_tombe', num); fd.append('statut', statut); fd.append('rot', rot);
            fd.append('type_concession', type_concession); fd.append('nb_lignes', nb_lignes); fd.append('cases_par_ligne', cases_par_ligne);

            if (id === 'new') {
                fd.append('action', 'save_tombe'); 
                fd.append('x', selectedTomb.getAttribute('data-x')); 
                fd.append('y', selectedTomb.getAttribute('data-y'));
                fd.append('w', selectedTomb.getAttribute('data-w')); 
                fd.append('h', selectedTomb.getAttribute('data-h'));
                
                fetch('cimetiere_plan.php', { method: 'POST', body: fd })
                .then(r => r.json()).then(data => {
                    if(data.status === 'error') {
                        alert("Erreur de sauvegarde : " + data.message);
                    } else {
                        selectedTomb.setAttribute('data-id', data.id); 
                        document.getElementById('btnDelete').style.display = 'block';
                        document.getElementById('panelTitle').innerText = "Édition de Zone";
                        showToast("Zone et cases créées !");
                        // On force la fermeture pour obliger l'utilisateur à cliquer à nouveau et recharger les ID
                        deselectTombe();
                    }
                })
                .catch(err => alert("Erreur réseau: " + err));
            } else {
                fd.append('action', 'edit_tombe'); fd.append('id', id);
                fetch('cimetiere_plan.php', { method: 'POST', body: fd })
                .then(r => r.json()).then(data => {
                    if(data.status === 'error') {
                        alert("Erreur de mise à jour : " + data.message);
                    } else {
                        showToast("Infos mises à jour !");
                    }
                })
                .catch(err => alert("Erreur réseau: " + err));
            }
        }

        function deleteTombe() {
            if(!confirm('Supprimer définitivement la zone du plan et toutes ses cases ?')) return;
            let id = selectedTomb.getAttribute('data-id');
            
            let fd = new FormData();
            fd.append('ajax', '1'); fd.append('action', 'delete_tombe'); fd.append('id', id);
            
            fetch('cimetiere_plan.php', { method: 'POST', body: fd })
            .then(r => r.json()).then(data => {
                if(data.status === 'error') {
                    alert("Erreur lors de la suppression : " + data.message);
                } else {
                    let temp = selectedTomb;
                    deselectTombe(); 
                    temp.remove(); 
                    showToast("🗑️ Zone supprimée.");
                }
            })
            .catch(err => alert("Erreur réseau: " + err));
        }
    </script>
</body>
</html>