<?php 
// Gestion du téléchargement de template CSV
if (isset($_GET['download_template'])) {
    $type = $_GET['download_template'];
    
    // Définir les en-têtes selon le type de table
    $headers = [];
    $exampleData = [];
    
    switch ($type) {
        case 'maintenance_types':
            $headers = ['name', 'active'];
            $exampleData = ['Maintenance préventive', '1'];
            break;
        case 'locations':
            $headers = ['name', 'client_id', 'address', 'city', 'postal_code', 'latitude', 'longitude', 'active'];
            $exampleData = ['MARC ANADER', '1', '', '', '', '5.3500000', '-3.9800000', '1'];
            break;
        case 'liaisons':
            $headers = ['name', 'description', 'site_a_name', 'site_b_name', 'site_a_latitude', 'site_a_longitude', 'site_b_latitude', 'site_b_longitude', 'active'];
            // Coordonnées: auto-déduites depuis le référentiel "Sites" (locations). Laissez vide dans le template.
            $exampleData = ['FO_AC002-TO-ET082 [MARC_ANADER vers ECG_BIETRY]', 'Description exemple', 'MARC_ANADER', 'ECG_BIETRY', '', '', '', '', '1'];
            break;
        case 'sites':
            $headers = ['name', 'description', 'active'];
            $exampleData = ['Site A', 'Description exemple', '1'];
            break;
        case 'incident_causes':
            $headers = ['name', 'category', 'description', 'active'];
            $exampleData = ['Panne matérielle', 'Technique', 'Description exemple', '1'];
            break;
        case 'priority_levels':
            $headers = ['name', 'sort_order', 'color', 'description'];
            $exampleData = ['Critique', '1', '#FF0000', 'Priorité maximale'];
            break;
        case 'equipments':
            $headers = ['name', 'category', 'description', 'active'];
            $exampleData = ['Routeur', 'Réseau', 'Description exemple', '1'];
            break;
        default:
            header('HTTP/1.1 400 Bad Request');
            die('Type invalide');
    }
    
    // Générer le template CSV
    $filename = 'template_' . $type . '.csv';
    
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Pragma: no-cache');
    header('Expires: 0');
    
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // BOM UTF-8
    
    // En-têtes
    fputcsv($output, $headers);
    
    // Ligne d'exemple
    fputcsv($output, $exampleData);
    
    fclose($output);
    exit;
}

// Gestion de l'import CSV
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_type']) && isset($_FILES['import_file'])) {
    header('Content-Type: application/json');
    
    $type = $_POST['import_type'];
    $file = $_FILES['import_file'];
    
    if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'error' => 'Erreur de téléchargement du fichier']);
        exit;
    }
    
    if (strtolower(substr($file['name'], -4)) !== '.csv') {
        echo json_encode(['success' => false, 'error' => 'Le fichier doit être au format CSV']);
        exit;
    }
    
    try {
        require_once __DIR__ . '/../../Core/Database.php';
        $pdo = Database::pdo();
        
        $handle = fopen($file['tmp_name'], 'r');
        if (!$handle) {
            echo json_encode(['success' => false, 'error' => 'Impossible de lire le fichier CSV']);
            exit;
        }
        
        $imported = 0;
        $headers = fgetcsv($handle); // Ligne d'en-têtes
        
        while (($row = fgetcsv($handle)) !== false) {
            if (empty(array_filter($row))) continue; // Ignorer les lignes vides
            
            $data = array_combine($headers, $row);
            
            // Insert selon le type
            switch ($type) {
                case 'maintenance_types':
                    $stmt = $pdo->prepare('INSERT INTO maintenance_types (name, active) VALUES (?, ?) ON DUPLICATE KEY UPDATE active = VALUES(active)');
                    $stmt->execute([$data['name'] ?? '', $data['active'] ?? 1]);
                    break;
                case 'locations':
                    // Support coordonnées + infos adresse (si colonnes présentes)
                    try {
                        $cols = [
                            'address' => "ALTER TABLE locations ADD COLUMN address TEXT NULL",
                            'city' => "ALTER TABLE locations ADD COLUMN city VARCHAR(100) NULL",
                            'postal_code' => "ALTER TABLE locations ADD COLUMN postal_code VARCHAR(20) NULL",
                            'latitude' => "ALTER TABLE locations ADD COLUMN latitude DECIMAL(10,8) NULL",
                            'longitude' => "ALTER TABLE locations ADD COLUMN longitude DECIMAL(11,8) NULL",
                        ];
                        foreach ($cols as $col => $sql) {
                            $st = $pdo->prepare('SHOW COLUMNS FROM locations LIKE ?');
                            $st->execute([$col]);
                            if (!$st->fetch()) { $pdo->exec($sql); }
                        }
                    } catch (Exception $e) {}

                    $normDec = function($v){ $v = trim((string)$v); if ($v==='') return null; $v=str_replace(',', '.', $v); return is_numeric($v)?$v:null; };
                    $name = trim((string)($data['name'] ?? ''));
                    $clientId = (int)($data['client_id'] ?? 1);
                    $active = (int)($data['active'] ?? 1);
                    $address = (string)($data['address'] ?? '');
                    $city = (string)($data['city'] ?? '');
                    $postal = (string)($data['postal_code'] ?? '');
                    $lat = $normDec($data['latitude'] ?? null);
                    $lng = $normDec($data['longitude'] ?? null);

                    // Sur certaines bases, locations.name n'est pas UNIQUE => éviter les doublons
                    $upd = $pdo->prepare(
                        'UPDATE locations '
                        . 'SET client_id = ?, address = ?, city = ?, postal_code = ?, '
                        . 'latitude = COALESCE(?, latitude), longitude = COALESCE(?, longitude), active = ? '
                        . 'WHERE name = ?'
                    );
                    $upd->execute([$clientId, $address, $city, $postal, $lat, $lng, $active, $name]);

                    if ($upd->rowCount() === 0) {
                        $ins = $pdo->prepare(
                            'INSERT INTO locations (name, client_id, address, city, postal_code, latitude, longitude, active) '
                            . 'VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
                        );
                        $ins->execute([$name, $clientId, $address, $city, $postal, $lat, $lng, $active]);
                    }
                    break;
                case 'liaisons':
                    // Assurer les colonnes géo
                    try {
                        $pdo->exec("CREATE TABLE IF NOT EXISTS liaisons (
                          id INT AUTO_INCREMENT PRIMARY KEY,
                          name VARCHAR(255) NOT NULL,
                          description TEXT NULL,
                          site_a_name VARCHAR(255) NULL,
                          site_b_name VARCHAR(255) NULL,
                          site_a_latitude DECIMAL(10,7) NULL,
                          site_a_longitude DECIMAL(10,7) NULL,
                          site_b_latitude DECIMAL(10,7) NULL,
                          site_b_longitude DECIMAL(10,7) NULL,
                          active TINYINT(1) DEFAULT 1,
                          created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                          updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                          UNIQUE KEY name (name)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

                        $cols = [
                            'site_a_name' => "ALTER TABLE liaisons ADD COLUMN site_a_name VARCHAR(255) NULL AFTER description",
                            'site_b_name' => "ALTER TABLE liaisons ADD COLUMN site_b_name VARCHAR(255) NULL AFTER site_a_name",
                            'site_a_latitude' => "ALTER TABLE liaisons ADD COLUMN site_a_latitude DECIMAL(10,7) NULL AFTER site_b_name",
                            'site_a_longitude' => "ALTER TABLE liaisons ADD COLUMN site_a_longitude DECIMAL(10,7) NULL AFTER site_a_latitude",
                            'site_b_latitude' => "ALTER TABLE liaisons ADD COLUMN site_b_latitude DECIMAL(10,7) NULL AFTER site_a_longitude",
                            'site_b_longitude' => "ALTER TABLE liaisons ADD COLUMN site_b_longitude DECIMAL(10,7) NULL AFTER site_b_latitude",
                        ];
                        foreach ($cols as $col=>$sql) {
                            $st = $pdo->prepare('SHOW COLUMNS FROM liaisons LIKE ?');
                            $st->execute([$col]);
                            if (!$st->fetch()) { $pdo->exec($sql); }
                        }
                    } catch (Exception $e) {}

                    $name = trim((string)($data['name'] ?? ''));
                    $desc = (string)($data['description'] ?? '');
                    $active = (int)($data['active'] ?? 1);
                    $siteA = trim((string)($data['site_a_name'] ?? ''));
                    $siteB = trim((string)($data['site_b_name'] ?? ''));

                    // Parsing [Site A vers Site B]
                    if (($siteA === '' || $siteB === '') && preg_match('/\[(.*?)\]/u', $name, $m)) {
                        $inside = trim((string)$m[1]);
                        if (preg_match('/^(.*?)\s+(?:vers|to)\s+(.*)$/iu', $inside, $m2)) {
                            if ($siteA === '') $siteA = trim((string)$m2[1]);
                            if ($siteB === '') $siteB = trim((string)$m2[2]);
                        }
                    }

                    // Si le CSV fournit des coordonnées, on alimente automatiquement le référentiel locations
                    $norm = function($v){ $v = trim((string)$v); if ($v==='') return null; $v=str_replace(',', '.', $v); return is_numeric($v)?$v:null; };
                    $latA = $norm($data['site_a_latitude'] ?? null);
                    $lngA = $norm($data['site_a_longitude'] ?? null);
                    $latB = $norm($data['site_b_latitude'] ?? null);
                    $lngB = $norm($data['site_b_longitude'] ?? null);

                    try {
                        // Assurer colonnes geo sur locations
                        $colsLoc = [
                            'latitude' => "ALTER TABLE locations ADD COLUMN latitude DECIMAL(10,8) NULL",
                            'longitude' => "ALTER TABLE locations ADD COLUMN longitude DECIMAL(11,8) NULL",
                        ];
                        foreach ($colsLoc as $col=>$sql) {
                            $st = $pdo->prepare('SHOW COLUMNS FROM locations LIKE ?');
                            $st->execute([$col]);
                            if (!$st->fetch()) { $pdo->exec($sql); }
                        }

                        $upLoc = function($site, $lat, $lng) use ($pdo) {
                            $site = trim((string)$site);
                            if ($site === '' || $lat === null || $lng === null) return;
                            $upd = $pdo->prepare('UPDATE locations SET latitude = COALESCE(?, latitude), longitude = COALESCE(?, longitude), active = 1 WHERE name = ?');
                            $upd->execute([$lat, $lng, $site]);
                            if ($upd->rowCount() === 0) {
                                $ins = $pdo->prepare('INSERT INTO locations (name, client_id, latitude, longitude, active) VALUES (?, ?, ?, ?, 1)');
                                $ins->execute([$site, 1, $lat, $lng]);
                            }
                        };
                        $upLoc($siteA, $latA, $lngA);
                        $upLoc($siteB, $latB, $lngB);
                    } catch (Exception $e) {}

                    // Ne pas stocker les coordonnées sur liaisons: seulement site A/B
                    $stmt = $pdo->prepare(
                        'INSERT INTO liaisons (name, description, site_a_name, site_b_name, active) '
                        . 'VALUES (?, ?, ?, ?, ?) '
                        . 'ON DUPLICATE KEY UPDATE '
                        . 'description = VALUES(description), '
                        . 'site_a_name = COALESCE(NULLIF(VALUES(site_a_name), \'\'), site_a_name), '
                        . 'site_b_name = COALESCE(NULLIF(VALUES(site_b_name), \'\'), site_b_name), '
                        . 'active = VALUES(active)'
                    );
                    $stmt->execute([$name, $desc, $siteA, $siteB, $active]);
                    break;
                case 'sites':
                    $stmt = $pdo->prepare('INSERT INTO sites (name, description, active) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE description = VALUES(description), active = VALUES(active)');
                    $stmt->execute([$data['name'] ?? '', $data['description'] ?? '', $data['active'] ?? 1]);
                    break;
                case 'incident_causes':
                    $stmt = $pdo->prepare('INSERT INTO incident_causes (name, category, description, active) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE category = VALUES(category), description = VALUES(description), active = VALUES(active)');
                    $stmt->execute([$data['name'] ?? '', $data['category'] ?? '', $data['description'] ?? '', $data['active'] ?? 1]);
                    break;
                case 'priority_levels':
                    $stmt = $pdo->prepare('INSERT INTO priority_levels (name, sort_order, color, description) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE sort_order = VALUES(sort_order), color = VALUES(color), description = VALUES(description)');
                    $stmt->execute([$data['name'] ?? '', $data['sort_order'] ?? 1, $data['color'] ?? '#000000', $data['description'] ?? '']);
                    break;
                case 'equipments':
                    $stmt = $pdo->prepare('INSERT INTO equipments (name, category, description, active) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE category = VALUES(category), description = VALUES(description), active = VALUES(active)');
                    $stmt->execute([$data['name'] ?? '', $data['category'] ?? '', $data['description'] ?? '', $data['active'] ?? 1]);
                    break;
            }
            $imported++;
        }
        
        fclose($handle);
        echo json_encode(['success' => true, 'imported' => $imported]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

$title = 'Gestion des Référentiels'; 
?>
<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Gestion des Référentiels</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="<?= route_url('/dashboard') ?>">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="<?= route_url('/settings') ?>">Paramètres</a></li>
                        <li class="breadcrumb-item active">Référentiels</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <?php if (isset($_GET['success'])): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    <i class="fas fa-check-circle me-2"></i>Référentiel mis à jour avec succès.
                </div>
            <?php endif; ?>

            <?php if (isset($_GET['deleted'])): ?>
                <div class="alert alert-info alert-dismissible fade show">
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    <i class="fas fa-info-circle me-2"></i>Élément supprimé ou désactivé.
                </div>
            <?php endif; ?>

            <?php if (isset($_GET['error'])): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <?php
                    switch ($_GET['error']) {
                        case 'missing_data':
                            echo 'Données obligatoires manquantes.';
                            break;
                        case 'database':
                            echo 'Erreur de base de données.';
                            break;
                        case 'invalid_type':
                            echo 'Type de référentiel invalide.';
                            break;
                        case 'delete_failed':
                            echo 'Échec de la suppression.';
                            break;
                        default:
                            echo 'Une erreur est survenue.';
                    }
                    ?>
                </div>
            <?php endif; ?>

            <!-- Onglets pour chaque type de référentiel -->
            <div class="card">
                <div class="card-header">
                    <ul class="nav nav-tabs card-header-tabs" id="referentialTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="maintenance-tab" data-bs-toggle="tab" data-bs-target="#maintenance" type="button" role="tab">
                                <i class="fas fa-tools me-1"></i> Types de maintenance
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="locations-tab" data-bs-toggle="tab" data-bs-target="#locations" type="button" role="tab">
                                <i class="fas fa-map-marker-alt me-1"></i> Localisations
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="liaisons-tab" data-bs-toggle="tab" data-bs-target="#liaisons" type="button" role="tab">
                                <i class="fas fa-link me-1"></i> Liaisons
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="sites-tab" data-bs-toggle="tab" data-bs-target="#sites" type="button" role="tab">
                                <i class="fas fa-building me-1"></i> Sites
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="causes-tab" data-bs-toggle="tab" data-bs-target="#causes" type="button" role="tab">
                                <i class="fas fa-question-circle me-1"></i> Causes probables
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="priorities-tab" data-bs-toggle="tab" data-bs-target="#priorities" type="button" role="tab">
                                <i class="fas fa-exclamation me-1"></i> Priorités
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="equipments-tab" data-bs-toggle="tab" data-bs-target="#equipments" type="button" role="tab">
                                <i class="fas fa-server me-1"></i> Équipements
                            </button>
                        </li>
                    </ul>
                </div>

                <div class="card-body">
                    <div class="tab-content" id="referentialTabsContent">
                        <!-- Types de maintenance -->
                        <div class="tab-pane fade show active" id="maintenance" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5>Types de maintenance</h5>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="downloadTemplate('maintenance_types')" title="Télécharger le modèle CSV">
                                        <i class="fas fa-file-csv me-1"></i> Template
                                    </button>
                                    <button type="button" class="btn btn-success btn-sm" onclick="exportData('maintenance_types')">
                                        <i class="fas fa-download me-1"></i> Export
                                    </button>
                                    <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#importModal" onclick="setImportType('maintenance_types', 'Types de maintenance')">
                                        <i class="fas fa-upload me-1"></i> Import
                                    </button>
                                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#maintenanceModal">
                                        <i class="fas fa-plus me-1"></i> Ajouter
                                    </button>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Nom</th>
                                            <th>Description</th>
                                            <th width="100">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($referentials['maintenance_types'] as $item): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($item['name']) ?></td>
                                            <td><?= htmlspecialchars($item['description'] ?? '') ?></td>
                                            <td>
                                                <a href="<?= route_url('/referentials/delete?type=maintenance_type&id=' . $item['id']) ?>" 
                                                   class="btn btn-sm btn-outline-danger delete-btn">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Localisations -->
                        <div class="tab-pane fade" id="locations" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5>Localisations</h5>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="downloadTemplate('locations')" title="Télécharger le modèle CSV">
                                        <i class="fas fa-file-csv me-1"></i> Template
                                    </button>
                                    <button type="button" class="btn btn-success btn-sm" onclick="exportData('locations')">
                                        <i class="fas fa-download me-1"></i> Export
                                    </button>
                                    <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#importModal" onclick="setImportType('locations', 'Localisations')">
                                        <i class="fas fa-upload me-1"></i> Import
                                    </button>
                                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#locationModal">
                                        <i class="fas fa-plus me-1"></i> Ajouter
                                    </button>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Nom</th>
                                            <th>Description</th>
                                            <th width="80">Statut</th>
                                            <th width="100">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($referentials['locations'] as $item): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($item['name']) ?></td>
                                            <td><?= htmlspecialchars($item['description'] ?? '') ?></td>
                                            <td>
                                                <span class="badge <?= $item['active'] ? 'bg-success' : 'bg-secondary' ?>">
                                                    <?= $item['active'] ? 'Actif' : 'Inactif' ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="<?= route_url('/referentials/delete?type=location&id=' . $item['id']) ?>" 
                                                   class="btn btn-sm btn-outline-danger delete-btn">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Liaisons -->
                        <div class="tab-pane fade" id="liaisons" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5>Liaisons</h5>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="downloadTemplate('liaisons')" title="Télécharger le modèle CSV">
                                        <i class="fas fa-file-csv me-1"></i> Template
                                    </button>
                                    <button type="button" class="btn btn-success btn-sm" onclick="exportData('liaisons')">
                                        <i class="fas fa-download me-1"></i> Export
                                    </button>
                                    <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#importModal" onclick="setImportType('liaisons', 'Liaisons')">
                                        <i class="fas fa-upload me-1"></i> Import
                                    </button>
                                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#liaisonModal">
                                        <i class="fas fa-plus me-1"></i> Ajouter
                                    </button>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Nom</th>
                                            <th>Site A</th>
                                            <th>Coordonnées Site A</th>
                                            <th>Site B</th>
                                            <th>Coordonnées Site B</th>
                                            <th>Description</th>
                                            <th width="80">Statut</th>
                                            <th width="100">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                            $locationsByName = [];
                                            $normKey = function($s) {
                                                $s = trim((string)$s);
                                                if ($s === '') return '';
                                                // Normalisation: underscore/tiret => espace, suppression ponctuation, casse/espaces
                                                $s = str_replace(['_', '-'], ' ', $s);
                                                $s = preg_replace('/[^\pL\pN\s]+/u', ' ', $s);
                                                $s = preg_replace('/\s+/u', ' ', $s);
                                                return mb_strtoupper($s, 'UTF-8');
                                            };
                                            foreach (($referentials['locations'] ?? []) as $loc) {
                                                $locName = (string)($loc['name'] ?? '');
                                                if ($locName !== '') {
                                                    $k = $normKey($locName);
                                                    $lat = $loc['latitude'] ?? null;
                                                    $lng = $loc['longitude'] ?? null;

                                                    // Si déjà une entrée avec coords, ne pas l'écraser par une entrée vide
                                                    if (isset($locationsByName[$k])) {
                                                        $hasExisting = ($locationsByName[$k]['lat'] ?? null) !== null && ($locationsByName[$k]['lat'] ?? '') !== ''
                                                            && ($locationsByName[$k]['lng'] ?? null) !== null && ($locationsByName[$k]['lng'] ?? '') !== '';
                                                        $hasNew = ($lat !== null && $lat !== '') && ($lng !== null && $lng !== '');
                                                        if ($hasExisting && !$hasNew) {
                                                            continue;
                                                        }
                                                    }

                                                    $locationsByName[$k] = [
                                                        'lat' => $lat,
                                                        'lng' => $lng,
                                                    ];
                                                }
                                            }
                                        ?>
                                        <?php foreach ($referentials['liaisons'] as $item): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($item['name']) ?></td>
                                            <?php
                                                $siteA = $item['site_a_name'] ?? '';
                                                $siteB = $item['site_b_name'] ?? '';
                                                if (($siteA === '' || $siteB === '') && preg_match('/\[(.*?)\]/u', (string)($item['name'] ?? ''), $m)) {
                                                    $inside = trim((string)$m[1]);
                                                    if (preg_match('/^(.*?)\s+(?:vers|to)\s+(.*)$/iu', $inside, $m2)) {
                                                        if ($siteA === '') $siteA = trim((string)$m2[1]);
                                                        if ($siteB === '') $siteB = trim((string)$m2[2]);
                                                    }
                                                }
                                                // Coordonnées: priorité au référentiel des sites (locations)
                                                $latA = $locationsByName[$normKey($siteA)]['lat'] ?? null;
                                                $lngA = $locationsByName[$normKey($siteA)]['lng'] ?? null;
                                                $latB = $locationsByName[$normKey($siteB)]['lat'] ?? null;
                                                $lngB = $locationsByName[$normKey($siteB)]['lng'] ?? null;

                                                // Fallback (si coordonnées stockées dans liaisons)
                                                if (($latA === null || $latA === '') && ($item['site_a_latitude'] ?? '') !== '') $latA = $item['site_a_latitude'];
                                                if (($lngA === null || $lngA === '') && ($item['site_a_longitude'] ?? '') !== '') $lngA = $item['site_a_longitude'];
                                                if (($latB === null || $latB === '') && ($item['site_b_latitude'] ?? '') !== '') $latB = $item['site_b_latitude'];
                                                if (($lngB === null || $lngB === '') && ($item['site_b_longitude'] ?? '') !== '') $lngB = $item['site_b_longitude'];
                                            ?>
                                            <td><?= htmlspecialchars($siteA ?: '—') ?></td>
                                            <td class="small text-muted">
                                                <?= ($latA !== null && $latA !== '' && $lngA !== null && $lngA !== '') ? htmlspecialchars($lngA . ', ' . $latA) : '—' ?>
                                            </td>
                                            <td><?= htmlspecialchars($siteB ?: '—') ?></td>
                                            <td class="small text-muted">
                                                <?= ($latB !== null && $latB !== '' && $lngB !== null && $lngB !== '') ? htmlspecialchars($lngB . ', ' . $latB) : '—' ?>
                                            </td>
                                            <td><?= htmlspecialchars($item['description'] ?? '') ?></td>
                                            <td>
                                                <span class="badge <?= $item['active'] ? 'bg-success' : 'bg-secondary' ?>">
                                                    <?= $item['active'] ? 'Actif' : 'Inactif' ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="<?= route_url('/referentials/delete?type=liaison&id=' . $item['id']) ?>" 
                                                   class="btn btn-sm btn-outline-danger delete-btn">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Sites -->
                        <div class="tab-pane fade" id="sites" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5>Sites</h5>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="downloadTemplate('sites')" title="Télécharger le modèle CSV">
                                        <i class="fas fa-file-csv me-1"></i> Template
                                    </button>
                                    <button type="button" class="btn btn-success btn-sm" onclick="exportData('sites')">
                                        <i class="fas fa-download me-1"></i> Export
                                    </button>
                                    <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#importModal" onclick="setImportType('sites', 'Sites')">
                                        <i class="fas fa-upload me-1"></i> Import
                                    </button>
                                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#siteModal">
                                        <i class="fas fa-plus me-1"></i> Ajouter
                                    </button>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Nom</th>
                                            <th>Description</th>
                                            <th width="80">Statut</th>
                                            <th width="100">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($referentials['sites'] as $item): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($item['name']) ?></td>
                                            <td><?= htmlspecialchars($item['description'] ?? '') ?></td>
                                            <td>
                                                <span class="badge <?= $item['active'] ? 'bg-success' : 'bg-secondary' ?>">
                                                    <?= $item['active'] ? 'Actif' : 'Inactif' ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="<?= route_url('/referentials/delete?type=site&id=' . $item['id']) ?>" 
                                                   class="btn btn-sm btn-outline-danger delete-btn">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Causes probables -->
                        <div class="tab-pane fade" id="causes" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5>Causes probables</h5>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="downloadTemplate('incident_causes')" title="Télécharger le modèle CSV">
                                        <i class="fas fa-file-csv me-1"></i> Template
                                    </button>
                                    <button type="button" class="btn btn-success btn-sm" onclick="exportData('incident_causes')">
                                        <i class="fas fa-download me-1"></i> Export
                                    </button>
                                    <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#importModal" onclick="setImportType('incident_causes', 'Causes probables')">
                                        <i class="fas fa-upload me-1"></i> Import
                                    </button>
                                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#causeModal">
                                        <i class="fas fa-plus me-1"></i> Ajouter
                                    </button>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Nom</th>
                                            <th>Catégorie</th>
                                            <th>Description</th>
                                            <th width="80">Statut</th>
                                            <th width="100">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($referentials['incident_causes'] as $item): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($item['name']) ?></td>
                                            <td><?= htmlspecialchars($item['category'] ?? '') ?></td>
                                            <td><?= htmlspecialchars($item['description'] ?? '') ?></td>
                                            <td>
                                                <span class="badge <?= $item['active'] ? 'bg-success' : 'bg-secondary' ?>">
                                                    <?= $item['active'] ? 'Actif' : 'Inactif' ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="<?= route_url('/referentials/delete?type=incident_cause&id=' . $item['id']) ?>" 
                                                   class="btn btn-sm btn-outline-danger delete-btn">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Priorités -->
                        <div class="tab-pane fade" id="priorities" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5>Niveaux de priorité</h5>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="downloadTemplate('priority_levels')" title="Télécharger le modèle CSV">
                                        <i class="fas fa-file-csv me-1"></i> Template
                                    </button>
                                    <button type="button" class="btn btn-success btn-sm" onclick="exportData('priority_levels')">
                                        <i class="fas fa-download me-1"></i> Export
                                    </button>
                                    <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#importModal" onclick="setImportType('priority_levels', 'Niveaux de priorité')">
                                        <i class="fas fa-upload me-1"></i> Import
                                    </button>
                                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#priorityModal">
                                        <i class="fas fa-plus me-1"></i> Ajouter
                                    </button>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Nom</th>
                                            <th>Ordre</th>
                                            <th>Couleur</th>
                                            <th>Description</th>
                                            <th width="100">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($referentials['priority_levels'] as $item): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($item['name']) ?></td>
                                            <td><?= $item['sort_order'] ?></td>
                                            <td>
                                                <span class="badge" style="background-color: <?= htmlspecialchars($item['color']) ?>">
                                                    <?= htmlspecialchars($item['color']) ?>
                                                </span>
                                            </td>
                                            <td><?= htmlspecialchars($item['description'] ?? '') ?></td>
                                            <td>
                                                <a href="<?= route_url('/referentials/delete?type=priority_level&id=' . $item['id']) ?>" 
                                                   class="btn btn-sm btn-outline-danger delete-btn">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Équipements -->
                        <div class="tab-pane fade" id="equipments" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5>Équipements impactés</h5>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="downloadTemplate('equipments')" title="Télécharger le modèle CSV">
                                        <i class="fas fa-file-csv me-1"></i> Template
                                    </button>
                                    <button type="button" class="btn btn-success btn-sm" onclick="exportData('equipments')">
                                        <i class="fas fa-download me-1"></i> Export
                                    </button>
                                    <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#importModal" onclick="setImportType('equipments', 'Équipements impactés')">
                                        <i class="fas fa-upload me-1"></i> Import
                                    </button>
                                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#equipmentModal">
                                        <i class="fas fa-plus me-1"></i> Ajouter
                                    </button>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Nom</th>
                                            <th>Catégorie</th>
                                            <th>Description</th>
                                            <th width="80">Statut</th>
                                            <th width="100">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($referentials['equipments'] as $item): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($item['name']) ?></td>
                                            <td><?= htmlspecialchars($item['category'] ?? '') ?></td>
                                            <td><?= htmlspecialchars($item['description'] ?? '') ?></td>
                                            <td>
                                                <span class="badge <?= $item['active'] ? 'bg-success' : 'bg-secondary' ?>">
                                                    <?= $item['active'] ? 'Actif' : 'Inactif' ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="<?= route_url('/referentials/delete?type=equipment&id=' . $item['id']) ?>" 
                                                   class="btn btn-sm btn-outline-danger delete-btn">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Modal de confirmation de suppression -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteConfirmModalLabel">
                    <i class="fas fa-exclamation-triangle me-2"></i>Confirmation de suppression
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p class="mb-0"><strong>Êtes-vous sûr de vouloir supprimer cet élément ?</strong></p>
                <p class="text-muted mt-2 mb-0">Cette action est irréversible.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>Annuler
                </button>
                <a href="#" id="confirmDeleteBtn" class="btn btn-danger">
                    <i class="fas fa-trash me-1"></i>Supprimer
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Modal d'import professionnel -->
<div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="importModalLabel">
                    <i class="fas fa-upload me-2"></i>Importer des données - <span id="importTypeLabel"></span>
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>Instructions :</strong>
                    <ol class="mb-0 mt-2">
                        <li>Téléchargez le modèle CSV en cliquant sur le bouton "Template"</li>
                        <li>Remplissez le fichier CSV avec vos données</li>
                        <li>Sélectionnez le fichier ci-dessous pour l'importer</li>
                    </ol>
                </div>
                
                <div class="mb-3">
                    <h6>Champs requis :</h6>
                    <div id="requiredFields" class="border rounded p-3 bg-light">
                        <!-- Sera rempli dynamiquement -->
                    </div>
                </div>
                
                <div class="mb-3">
                    <label for="importFile" class="form-label fw-bold">Sélectionnez votre fichier CSV</label>
                    <input type="file" class="form-control" id="importFile" accept=".csv">
                    <div class="form-text">Format accepté : CSV uniquement</div>
                </div>
                
                <div id="importProgress" class="d-none">
                    <div class="progress">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%"></div>
                    </div>
                    <p class="text-center mt-2 mb-0">Import en cours...</p>
                </div>
                
                <div id="importResult" class="alert d-none mt-3"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>Annuler
                </button>
                <button type="button" class="btn btn-primary" id="confirmImportBtn">
                    <i class="fas fa-upload me-1"></i>Importer
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Modales pour l'ajout d'éléments -->
<?php include 'modals.php'; ?>

<script>
// Variables globales
let deleteUrl = '';
let currentImportType = '';
let currentImportLabel = '';

// Schéma des champs pour chaque type de table
const tableSchemas = {
    'maintenance_types': {
        required: ['name'],
        optional: ['active'],
        description: '<strong>name</strong> : Nom du type de maintenance<br><strong>active</strong> : Statut (1 pour actif, 0 pour inactif)'
    },
    'locations': {
        required: ['name', 'client_id'],
        optional: ['active'],
        description: '<strong>name</strong> : Nom de la localisation<br><strong>client_id</strong> : ID du client<br><strong>active</strong> : Statut (1 pour actif, 0 pour inactif)'
    },
    'liaisons': {
        required: ['name'],
        optional: ['description', 'site_a_name', 'site_b_name', 'site_a_latitude', 'site_a_longitude', 'site_b_latitude', 'site_b_longitude', 'active'],
        description: '<strong>name</strong> : Nom de la liaison (ex: FO_... [SITE_A vers SITE_B])<br><strong>description</strong> : Description (optionnel)<br><strong>site_a_name</strong> / <strong>site_b_name</strong> : Sites A/B (optionnel si présent dans [..])<br><strong>Coordonnées</strong> : auto-déduites depuis <em>Sites/Locations</em> (ne pas saisir manuellement). Colonnes <strong>site_a_longitude</strong>/<strong>site_a_latitude</strong> et <strong>site_b_longitude</strong>/<strong>site_b_latitude</strong> peuvent rester vides.<br><strong>active</strong> : Statut (1 pour actif, 0 pour inactif)'
    },
    'sites': {
        required: ['name'],
        optional: ['description', 'active'],
        description: '<strong>name</strong> : Nom du site<br><strong>description</strong> : Description (optionnel)<br><strong>active</strong> : Statut (1 pour actif, 0 pour inactif)'
    },
    'incident_causes': {
        required: ['name'],
        optional: ['category', 'description', 'active'],
        description: '<strong>name</strong> : Nom de la cause<br><strong>category</strong> : Catégorie (optionnel)<br><strong>description</strong> : Description (optionnel)<br><strong>active</strong> : Statut (1 pour actif, 0 pour inactif)'
    },
    'priority_levels': {
        required: ['name', 'sort_order', 'color'],
        optional: ['description'],
        description: '<strong>name</strong> : Nom du niveau<br><strong>sort_order</strong> : Ordre de tri (numérique)<br><strong>color</strong> : Code couleur (ex: #FF0000)<br><strong>description</strong> : Description (optionnel)'
    },
    'equipments': {
        required: ['name'],
        optional: ['category', 'description', 'active'],
        description: '<strong>name</strong> : Nom de l\'équipement<br><strong>category</strong> : Catégorie (optionnel)<br><strong>description</strong> : Description (optionnel)<br><strong>active</strong> : Statut (1 pour actif, 0 pour inactif)'
    }
};

// Confirmation de suppression avec modal Bootstrap
document.addEventListener('DOMContentLoaded', function() {
    const deleteModal = document.getElementById('deleteConfirmModal');
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
    
    document.querySelectorAll('.delete-btn').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            deleteUrl = this.getAttribute('href');
            
            // Utiliser l'API Bootstrap via les attributs data ou l'objet Modal si disponible
            if (typeof bootstrap !== 'undefined') {
                const modal = new bootstrap.Modal(deleteModal);
                modal.show();
            } else if (typeof $ !== 'undefined' && $.fn.modal) {
                // Fallback pour Bootstrap 4 avec jQuery
                $(deleteModal).modal('show');
            } else {
                // Fallback si Bootstrap n'est pas chargé
                if (confirm('Êtes-vous sûr de vouloir supprimer cet élément ?')) {
                    window.location.href = deleteUrl;
                }
            }
        });
    });
    
    if (confirmDeleteBtn) {
        confirmDeleteBtn.addEventListener('click', function() {
            if (deleteUrl) {
                window.location.href = deleteUrl;
            }
        });
    }
    
    // Gestionnaire du bouton d'import dans le modal
    const confirmImportBtn = document.getElementById('confirmImportBtn');
    if (confirmImportBtn) {
        confirmImportBtn.addEventListener('click', function() {
            const fileInput = document.getElementById('importFile');
            const file = fileInput.files[0];
            
            if (!file) {
                showImportResult('Veuillez sélectionner un fichier CSV', 'danger');
                return;
            }
            
            if (!file.name.endsWith('.csv')) {
                showImportResult('Le fichier doit être au format CSV', 'danger');
                return;
            }
            
            performImport(currentImportType, file);
        });
    }
});

// Définir le type d'import et afficher les champs requis
function setImportType(type, label) {
    currentImportType = type;
    currentImportLabel = label;
    
    document.getElementById('importTypeLabel').textContent = label;
    document.getElementById('importFile').value = '';
    document.getElementById('importResult').classList.add('d-none');
    
    // Afficher les champs requis
    const schema = tableSchemas[type];
    if (schema) {
        const requiredFieldsDiv = document.getElementById('requiredFields');
        requiredFieldsDiv.innerHTML = schema.description;
    }
}

// Télécharger le template CSV
function downloadTemplate(type) {
    // Utiliser la page referentials avec un paramètre GET
    window.location.href = `<?= route_url('/referentials') ?>?download_template=${type}`;
}

// Afficher le résultat de l'import
function showImportResult(message, type) {
    const resultDiv = document.getElementById('importResult');
    resultDiv.className = `alert alert-${type}`;
    resultDiv.innerHTML = `<i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>${message}`;
    resultDiv.classList.remove('d-none');
}

// Effectuer l'import
function performImport(tableName, file) {
        const progressDiv = document.getElementById('importProgress');
        const resultDiv = document.getElementById('importResult');
        const confirmBtn = document.getElementById('confirmImportBtn');

        progressDiv.classList.remove('d-none');
        resultDiv.classList.add('d-none');
        confirmBtn.disabled = true;

        // Préparer les deux formats compatibles (fallback inclus)
        const fdApi = new FormData();
        fdApi.append('file', file);
        fdApi.append('type', tableName);

        const fdInline = new FormData();
        fdInline.append('import_file', file);
        fdInline.append('import_type', tableName);

        const importUrl = '<?= route_url('/referentials/import') ?>';
        const inlineUrl = '<?= route_url('/referentials') ?>';

        // Helpers JSON tolérants aux réponses HTML
        const toJson = async (resp) => {
            if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
            const text = await resp.text();
            try { return JSON.parse(text); } catch { throw new Error('Réponse non JSON'); }
        };

        // Chaîne de fallbacks: import API, import API /public, inline, inline /public, puis script standalone
        const endpoints = [
            { url: importUrl, body: fdApi },
            { url: '/public/referentials/import', body: fdApi },
            { url: inlineUrl, body: fdInline },
            { url: '/public/referentials', body: fdInline },
            { url: '/public/import-referentials.php', body: fdApi }, // Script standalone
        ];

        let p = Promise.reject();
        endpoints.forEach((ep, i) => {
            const step = () => fetch(ep.url, { method: 'POST', body: ep.body }).then(toJson);
            p = i === 0 ? step() : p.catch(step);
        });

        p.then((data) => {
            progressDiv.classList.add('d-none');
            confirmBtn.disabled = false;

            if (data && data.success) {
                showImportResult(`Import réussi ! ${data.imported} élément(s) importé(s)`, 'success');
                setTimeout(() => { window.location.reload(); }, 1500);
            } else {
                showImportResult(`Erreur lors de l'import : ${(data && data.error) || 'Réponse invalide'}`, 'danger');
            }
        }).catch((error) => {
            progressDiv.classList.add('d-none');
            confirmBtn.disabled = false;
            showImportResult(`Erreur : ${error.message}`, 'danger');
        });
}

// Fonction d'export de données
function exportData(tableName) {
    const baseUrl = '<?= route_url('/referentials/export') ?>';
    window.location.href = `${baseUrl}?type=${tableName}`;
}
</script>