<?php
/**
 * Plugin Name: TD Archives CSV Rencontres
 * Description: Gestionnaire de fichiers CSV pour les rencontres scientifiques avec interface drag & drop, modification des noms de fichiers, recherche et tri
 * Version: 2.1.0
 * Author: Thomas Dufranne
 * Author URI: https://td-plugins.com
 * Text Domain: td-archives-rencontres
 */

if (!defined('ABSPATH')) {
    exit;
}

define('TD_ARCHIVES_PLUGIN_URL', plugin_dir_url(__FILE__));
define('TD_ARCHIVES_PLUGIN_PATH', plugin_dir_path(__FILE__));

class TD_Archives_Rencontres_V2_Enhanced {
    
    public function __construct() {
        add_action('init', [$this, 'td_init']);
        add_action('admin_menu', [$this, 'td_add_admin_menu']);
        add_action('admin_enqueue_scripts', [$this, 'td_enqueue_scripts']);
        add_action('wp_ajax_td_upload_csv', [$this, 'td_handle_csv_upload']);
        add_action('wp_ajax_td_delete_csv', [$this, 'td_delete_csv']);
        add_action('wp_ajax_td_download_csv', [$this, 'td_download_csv']);
        add_action('wp_ajax_td_rename_csv', [$this, 'td_rename_csv']);
        add_action('wp_ajax_td_convert_html_to_csv', [$this, 'td_convert_html_to_csv']);
        add_action('wp_ajax_td_search_csv_files', [$this, 'td_search_csv_files']);
        add_action('admin_post_td_save_options', [$this, 'td_save_options']);
        register_activation_hook(__FILE__, [$this, 'td_create_upload_directory']);
    }
    
    public function td_init() {
        load_plugin_textdomain('td-archives-rencontres', false, dirname(plugin_basename(__FILE__)) . '/languages');
    }
    
    public function td_create_upload_directory() {
        $upload_dir = wp_upload_dir();
        $csv_dir = $upload_dir['basedir'] . '/td-archives-csv';
        
        if (!file_exists($csv_dir)) {
            wp_mkdir_p($csv_dir);
            file_put_contents($csv_dir . '/.htaccess', "Options -Indexes\nOrder deny,allow\nDeny from all");
        }
    }
    
    public function td_add_admin_menu() {
        add_menu_page(
            'TD Archives Rencontres',
            'Archives CSV',
            'manage_options',
            'td-archives-list',
            [$this, 'td_list_page'],
            'dashicons-media-spreadsheet',
            30
        );
        
        add_submenu_page(
            'td-archives-list',
            'Liste des CSV',
            'Liste des CSV',
            'manage_options',
            'td-archives-list',
            [$this, 'td_list_page']
        );
        
        add_submenu_page(
            'td-archives-list',
            'Ajouter un CSV',
            'Ajouter un CSV',
            'manage_options',
            'td-archives-add',
            [$this, 'td_add_page']
        );
        
        add_submenu_page(
            'td-archives-list',
            'Convertisseur HTML → CSV',
            'HTML → CSV',
            'manage_options',
            'td-archives-converter',
            [$this, 'td_converter_page']
        );
        
        add_submenu_page(
            'td-archives-list',
            'Options',
            'Options',
            'manage_options',
            'td-archives-options',
            [$this, 'td_options_page']
        );
        
        add_submenu_page(
            null,
            'Détail CSV',
            'Détail CSV',
            'manage_options',
            'td-archives-detail',
            [$this, 'td_detail_page']
        );
    }
    
    public function td_enqueue_scripts($hook) {
        if (strpos($hook, 'td-archives') === false) {
            return;
        }
        
        wp_enqueue_script('td-archives-js', TD_ARCHIVES_PLUGIN_URL . 'assets/td-archives-v2.js', ['jquery'], '2.1.0', true);
        wp_enqueue_style('td-archives-css', TD_ARCHIVES_PLUGIN_URL . 'assets/td-archives-v2.css', [], '2.1.0');
        
        wp_enqueue_style('td-archives-search-styles-css', TD_ARCHIVES_PLUGIN_URL . 'assets/td-archives-search-styles.css', [], '2.1.0');
        

        wp_localize_script('td-archives-js', 'tdArchives', [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('td_archives_nonce'),
            'messages' => [
                'upload_success' => __('Fichier uploadé avec succès', 'td-archives-rencontres'),
                'upload_error' => __('Erreur lors de l\'upload', 'td-archives-rencontres'),
                'file_exists' => __('Un fichier avec ce nom existe déjà. Voulez-vous le remplacer ?', 'td-archives-rencontres'),
                'invalid_file' => __('Seuls les fichiers CSV sont autorisés', 'td-archives-rencontres'),
                'delete_confirm' => __('Êtes-vous sûr de vouloir supprimer ce fichier ?', 'td-archives-rencontres'),
                'rename_success' => __('Fichier renommé avec succès', 'td-archives-rencontres'),
                'rename_error' => __('Erreur lors du renommage', 'td-archives-rencontres'),
                'conversion_success' => __('Conversion réussie', 'td-archives-rencontres'),
                'conversion_error' => __('Erreur lors de la conversion', 'td-archives-rencontres'),
                'invalid_html' => __('HTML invalide ou aucun tableau trouvé', 'td-archives-rencontres'),
                'missing_fields' => __('Veuillez remplir tous les champs requis', 'td-archives-rencontres')
            ]
        ]);
    }
    
    // Nouvelle fonction pour extraire la date d'événement d'un CSV
    private function td_get_event_date_from_csv($file_path) {
        if (!file_exists($file_path)) {
            return null;
        }
        
        $handle = fopen($file_path, 'r');
        if (!$handle) {
            return null;
        }
        
        // Lire l'en-tête
        $first_line = fgets($handle);
        $delimiter = (substr_count($first_line, ';') > substr_count($first_line, ',')) ? ';' : ',';
        rewind($handle);
        
        $headers = fgetcsv($handle, 0, $delimiter);
        if (!$headers) {
            fclose($handle);
            return null;
        }
        
        // Chercher la colonne Date_Evenement
        $event_date_index = array_search('Date_Evenement', $headers);
        if ($event_date_index === false) {
            fclose($handle);
            return null;
        }
        
        // Lire la première ligne de données
        $first_row = fgetcsv($handle, 0, $delimiter);
        fclose($handle);
        
        if ($first_row && isset($first_row[$event_date_index]) && !empty($first_row[$event_date_index])) {
            return $first_row[$event_date_index];
        }
        
        return null;
    }
    
    // Nouvelle fonction pour la recherche AJAX
    public function td_search_csv_files() {
        if (!wp_verify_nonce($_POST['nonce'], 'td_archives_nonce')) {
            wp_send_json_error('Nonce invalide');
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permissions insuffisantes');
        }
        
        $search_query = sanitize_text_field($_POST['search_query']);
        $upload_dir = wp_upload_dir();
        $csv_dir = $upload_dir['basedir'] . '/td-archives-csv';
        
        if (!is_dir($csv_dir)) {
            wp_send_json_success([]);
            return;
        }
        
        $files = glob($csv_dir . '/*.csv');
        $results = [];
        
        foreach ($files as $file) {
            $filename = basename($file);
            if (empty($search_query) || stripos($filename, $search_query) !== false) {
                $event_date = $this->td_get_event_date_from_csv($file);
                $results[] = [
                    'filename' => $filename,
                    'event_date' => $event_date,
                    'url' => admin_url('admin.php?page=td-archives-detail&file=' . urlencode($filename))
                ];
            }
        }
        
        // Trier par date d'événement
        usort($results, function($a, $b) {
            $a_time = $a['event_date'] ? strtotime($a['event_date']) : 0;
            $b_time = $b['event_date'] ? strtotime($b['event_date']) : 0;
            return $b_time - $a_time; // Plus récent d'abord
        });
        
        wp_send_json_success($results);
    }
    
    public function td_list_page() {
        $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        $per_page = 10;
        $search_query = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : '';
        $sort_by = isset($_GET['sort']) ? sanitize_text_field($_GET['sort']) : 'event_date';
        $sort_order = isset($_GET['order']) ? sanitize_text_field($_GET['order']) : 'desc';
        
        $upload_dir = wp_upload_dir();
        $csv_dir = $upload_dir['basedir'] . '/td-archives-csv';
        
        if (!is_dir($csv_dir)) {
            $files = [];
        } else {
            $files = glob($csv_dir . '/*.csv');
        }
        
        // Filtrer par recherche si nécessaire
        if (!empty($search_query)) {
            $files = array_filter($files, function($file) use ($search_query) {
                $filename = basename($file);
                return stripos($filename, $search_query) !== false;
            });
        }
        
        // Enrichir les fichiers avec les métadonnées pour le tri
        $files_with_meta = [];
        foreach ($files as $file) {
            $filename = basename($file);
            $upload_time = get_option('td_csv_upload_time_' . md5($filename), filemtime($file));
            $mod_time = filemtime($file);
            $event_date = $this->td_get_event_date_from_csv($file);
            
            $files_with_meta[] = [
                'path' => $file,
                'filename' => $filename,
                'upload_time' => $upload_time,
                'mod_time' => $mod_time,
                'event_date' => $event_date,
                'event_timestamp' => $event_date ? strtotime($event_date) : 0
            ];
        }
        
        // Trier les fichiers
        usort($files_with_meta, function($a, $b) use ($sort_by, $sort_order) {
            $result = 0;
            
            switch ($sort_by) {
                case 'event_date':
                    $result = $a['event_timestamp'] - $b['event_timestamp'];
                    break;
                case 'name':
                    $result = strcasecmp($a['filename'], $b['filename']);
                    break;
                case 'upload_date':
                    $result = $a['upload_time'] - $b['upload_time'];
                    break;
                case 'mod_date':
                    $result = $a['mod_time'] - $b['mod_time'];
                    break;
                default:
                    $result = $a['event_timestamp'] - $b['event_timestamp'];
            }
            
            return $sort_order === 'desc' ? -$result : $result;
        });
        
        $total_files = count($files_with_meta);
        $total_pages = ceil($total_files / $per_page);
        $offset = ($current_page - 1) * $per_page;
        $current_files = array_slice($files_with_meta, $offset, $per_page);
        
        ?>
        <div class="wrap">
            <h1>
                Liste des fichiers CSV
                <a href="<?php echo admin_url('admin.php?page=td-archives-add'); ?>" class="page-title-action">Ajouter nouveau</a>
                <a href="<?php echo admin_url('admin.php?page=td-archives-converter'); ?>" class="page-title-action">HTML → CSV</a>
            </h1>
            
            <!-- Barre de recherche et filtres -->
            <div class="td-search-controls">
                <form method="get" action="" class="td-search-form">
                    <input type="hidden" name="page" value="td-archives-list">
                    
                    <div class="td-search-group">
                        <input type="search" 
                               id="td-search-input" 
                               name="s" 
                               value="<?php echo esc_attr($search_query); ?>" 
                               placeholder="Rechercher dans les noms de fichiers..." 
                               class="td-search-field">
                        <button type="submit" class="button td-search-btn">
                            <span class="dashicons dashicons-search"></span>
                            Rechercher
                        </button>
                        <?php if (!empty($search_query)): ?>
                            <a href="<?php echo admin_url('admin.php?page=td-archives-list'); ?>" class="button td-clear-search">
                                <span class="dashicons dashicons-no-alt"></span>
                                Effacer
                            </a>
                        <?php endif; ?>
                    </div>
                    
                    <div class="td-sort-group">
                        <label for="sort-select">Trier par :</label>
                        <select name="sort" id="sort-select" class="td-sort-select">
                            <option value="event_date" <?php selected($sort_by, 'event_date'); ?>>Date d'événement</option>
                            <option value="name" <?php selected($sort_by, 'name'); ?>>Nom de fichier</option>
                            <option value="upload_date" <?php selected($sort_by, 'upload_date'); ?>>Date d'envoi</option>
                            <option value="mod_date" <?php selected($sort_by, 'mod_date'); ?>>Date de modification</option>
                        </select>
                        
                        <select name="order" class="td-order-select">
                            <option value="desc" <?php selected($sort_order, 'desc'); ?>>Plus récent d'abord</option>
                            <option value="asc" <?php selected($sort_order, 'asc'); ?>>Plus ancien d'abord</option>
                        </select>
                        
                        <button type="submit" class="button">Appliquer</button>
                    </div>
                </form>
            </div>
            
            <?php if (!empty($search_query)): ?>
                <div class="td-search-results">
                    <p><strong><?php echo $total_files; ?></strong> résultat(s) pour "<em><?php echo esc_html($search_query); ?></em>"</p>
                </div>
            <?php endif; ?>
            
            <?php if (empty($files_with_meta)): ?>
                <div class="td-empty-state">
                    <?php if (!empty($search_query)): ?>
                        <p>Aucun fichier trouvé pour cette recherche.</p>
                        <div class="td-empty-actions">
                            <a href="<?php echo admin_url('admin.php?page=td-archives-list'); ?>" class="button button-secondary">Voir tous les fichiers</a>
                            <a href="<?php echo admin_url('admin.php?page=td-archives-add'); ?>" class="button button-primary">Ajouter un fichier</a>
                        </div>
                    <?php else: ?>
                        <p>Aucun fichier CSV trouvé.</p>
                        <div class="td-empty-actions">
                            <a href="<?php echo admin_url('admin.php?page=td-archives-add'); ?>" class="button button-primary">Ajouter votre premier fichier CSV</a>
                            <a href="<?php echo admin_url('admin.php?page=td-archives-converter'); ?>" class="button button-secondary">Convertir HTML → CSV</a>
                        </div>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="td-list-container">
                    <?php foreach ($current_files as $file_meta): 
                        $file = $file_meta['path'];
                        $filename = $file_meta['filename'];
                        $upload_time = $file_meta['upload_time'];
                        $mod_time = $file_meta['mod_time'];
                        $event_date = $file_meta['event_date'];
                        $lines_count = $this->td_count_csv_lines($file);
                        $file_size = size_format(filesize($file));
                    ?>
                        <div class="td-file-card" data-filename="<?php echo esc_attr($filename); ?>">
                            <div class="td-file-header">
                                <h3 class="td-file-title">
                                    <span class="td-filename-display"><?php echo esc_html($filename); ?></span>
                                    <input type="text" class="td-filename-edit" value="<?php echo esc_attr(pathinfo($filename, PATHINFO_FILENAME)); ?>" style="display: none;">
                                    <?php if ($event_date): ?>
                                        <span class="td-event-date-badge"><?php echo esc_html($event_date); ?></span>
                                    <?php endif; ?>
                                </h3>
                                <div class="td-file-actions">
                                    <button class="button button-secondary td-rename-btn" title="Renommer le fichier">
                                        <span class="dashicons dashicons-edit"></span>
                                    </button>
                                    <a href="<?php echo admin_url('admin.php?page=td-archives-detail&file=' . urlencode($filename)); ?>" class="button button-primary">Voir le détail</a>
                                    <a href="<?php echo wp_nonce_url(admin_url('admin-ajax.php?action=td_download_csv&file=' . urlencode($filename)), 'td_download_nonce'); ?>" class="button">Télécharger</a>
                                    <button class="button button-link-delete td-delete-csv" data-file="<?php echo esc_attr($filename); ?>">Supprimer</button>
                                </div>
                            </div>
                            <div class="td-file-meta">
                                <div class="td-meta-item">
                                    <strong>Date d'envoi</strong>
                                    <span><?php echo date('d/m/Y à H:i', $upload_time); ?></span>
                                </div>
                                <div class="td-meta-item">
                                    <strong>Dernière modification</strong>
                                    <span><?php echo date('d/m/Y à H:i', $mod_time); ?></span>
                                </div>
                                <?php if ($event_date): ?>
                                    <div class="td-meta-item">
                                        <strong>Date d'événement</strong>
                                        <span><?php echo esc_html($event_date); ?></span>
                                    </div>
                                <?php endif; ?>
                                <div class="td-meta-item">
                                    <strong>Nombre de lignes</strong>
                                    <span><?php echo number_format($lines_count); ?></span>
                                </div>
                                <div class="td-meta-item">
                                    <strong>Taille</strong>
                                    <span><?php echo $file_size; ?></span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <?php if ($total_pages > 1): ?>
                    <div class="td-pagination">
                        <?php
                        $page_links = paginate_links([
                            'base' => add_query_arg([
                                'paged' => '%#%',
                                's' => $search_query,
                                'sort' => $sort_by,
                                'order' => $sort_order
                            ]),
                            'format' => '',
                            'prev_text' => '&laquo; Précédent',
                            'next_text' => 'Suivant &raquo;',
                            'total' => $total_pages,
                            'current' => $current_page,
                            'type' => 'array'
                        ]);
                        
                        if ($page_links) {
                            echo '<nav class="pagination-wrapper">';
                            echo '<ul class="pagination">';
                            foreach ($page_links as $link) {
                                echo '<li>' . $link . '</li>';
                            }
                            echo '</ul>';
                            echo '</nav>';
                        }
                        ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
        <?php
    }
    
    // Autres fonctions (converter_page, add_page, options_page, detail_page, etc.)
    public function td_converter_page() {
        ?>
        <div class="wrap">
            <h1>Convertisseur HTML vers CSV</h1>
            <p class="description">Convertissez vos tableaux HTML en fichiers CSV compatibles avec les rencontres scientifiques.</p>
            
            <div class="td-converter-container">
                <form id="td-html-converter-form" class="td-converter-form">
                    <?php wp_nonce_field('td_converter_nonce', 'td_converter_nonce'); ?>
                    
                    <div class="td-converter-section">
                        <h2>Informations générales de l'événement</h2>
                        <div class="td-form-grid">
                            <div class="td-form-group">
                                <label for="td_event_name">Nom de la journée *</label>
                                <input type="text" id="td_event_name" name="event_name" placeholder="Ex: Journée GBP 2024" required>
                            </div>
                            
                            <div class="td-form-group">
                                <label for="td_event_date">Date de l'événement *</label>
                                <input type="date" id="td_event_date" name="event_date" required>
                            </div>
                            
                            <div class="td-form-group">
                                <label for="td_event_location">Lieu de l'événement *</label>
                                <input type="text" id="td_event_location" name="event_location" placeholder="Ex: Université de Paris" required>
                            </div>
                            
                            <div class="td-form-group">
                                <label for="td_output_filename">Nom du fichier CSV</label>
                                <input type="text" id="td_output_filename" name="output_filename" placeholder="participants_journee_gbp_2024.csv">
                                <small>Laissez vide pour génération automatique</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="td-converter-section">
                        <h2>Code HTML du tableau</h2>
                        <div class="td-form-group">
                            <label for="td_html_content">Collez votre code HTML contenant le tableau des participants</label>
                            <textarea id="td_html_content" name="html_content" rows="15" placeholder="Collez ici le code HTML de votre tableau contenant : nom, prénom, laboratoire, ville..." required></textarea>
                            <small>Le tableau doit contenir au minimum les colonnes : nom, prénom. Colonnes optionnelles : nom2 (deuxième nom), laboratoire, ville (lieu du laboratoire).</small>
                        </div>
                    </div>
                    
                    <div class="td-converter-actions">
                        <button type="button" id="td_preview_conversion" class="button button-secondary">Prévisualiser</button>
                        <button type="submit" id="td_convert_and_save" class="button button-primary">Convertir et sauvegarder</button>
                    </div>
                </form>
                
                <div id="td_conversion_preview" class="td-conversion-preview" style="display: none;">
                    <h3>Aperçu de la conversion</h3>
                    <div id="td_preview_content"></div>
                </div>
            </div>
        </div>
        <?php
    }
    
    public function td_add_page() {
        ?>
        <div class="wrap">
            <h1>Ajouter un fichier CSV</h1>
            
            <div class="td-add-container">
                <div class="td-upload-section">
                    <div id="td-drop-zone" class="td-drop-zone">
                        <div class="td-drop-content">
                            <span class="dashicons dashicons-upload"></span>
                            <p>Glissez votre fichier CSV ici ou <button type="button" id="td-file-select">sélectionnez un fichier</button></p>
                            <input type="file" id="td-file-input" accept=".csv" style="display: none;">
                        </div>
                    </div>
                    <div id="td-upload-progress" class="td-upload-progress" style="display: none;">
                        <div class="td-progress-bar">
                            <div class="td-progress-fill"></div>
                        </div>
                        <p class="td-progress-text">Upload en cours...</p>
                    </div>
                </div>
                
                <div class="td-upload-info">
                    <h3>Informations</h3>
                    <ul>
                        <li>Seuls les fichiers au format CSV sont acceptés</li>
                        <li>La première ligne doit contenir les en-têtes des colonnes</li>
                        <li>Taille maximale : <?php echo ini_get('upload_max_filesize'); ?></li>
                        <li>Si un fichier avec le même nom existe, vous serez invité à le remplacer</li>
                    </ul>
                    
                    <div class="td-quick-link">
                        <h4>Vous avez un tableau HTML ?</h4>
                        <p>Utilisez notre <a href="<?php echo admin_url('admin.php?page=td-archives-converter'); ?>" class="button button-secondary">Convertisseur HTML → CSV</a></p>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
    
    public function td_options_page() {
        if (isset($_GET['settings-updated'])) {
            echo '<div class="notice notice-success is-dismissible"><p>Options sauvegardées avec succès !</p></div>';
        }
        
        $hidden_columns = get_option('td_archives_hidden_columns', '');
        ?>
        <div class="wrap">
            <h1>Options - TD Archives Rencontres</h1>
            
            <div class="td-options-container">
                <form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
                    <?php wp_nonce_field('td_options_nonce', 'td_options_nonce'); ?>
                    <input type="hidden" name="action" value="td_save_options">
                    
                    <div class="td-option-section">
                        <h2>Colonnes à masquer</h2>
                        <p class="description">
                            Indiquez les noms exacts des colonnes à toujours masquer dans l'affichage, 
                            une par ligne ou séparées par des virgules. Ces colonnes ne seront jamais affichées, 
                            même si elles contiennent des données.
                        </p>
                        
                        <textarea 
                            name="td_hidden_columns" 
                            id="td_hidden_columns" 
                            rows="10" 
                            cols="50" 
                            class="large-text"
                            placeholder="Exemple :&#10;UID&#10;CASID&#10;URL, MIDDLENAME&#10;Adresse de facturation Paybox"
                        ><?php echo esc_textarea($hidden_columns); ?></textarea>
                        
                        <div class="td-columns-help">
                            <h4>Colonnes détectées dans vos fichiers :</h4>
                            <div class="td-detected-columns">
                                <?php echo $this->td_get_detected_columns_list(); ?>
                            </div>
                        </div>
                    </div>
                    
                    <p class="submit">
                        <input type="submit" name="submit" class="button-primary" value="Sauvegarder les options">
                    </p>
                </form>
            </div>
        </div>
        <?php
    }
    
    public function td_detail_page() {
        if (!isset($_GET['file'])) {
            wp_die('Fichier non spécifié');
        }
        
        $filename = sanitize_file_name($_GET['file']);
        $upload_dir = wp_upload_dir();
        $file_path = $upload_dir['basedir'] . '/td-archives-csv/' . $filename;
        
        if (!file_exists($file_path)) {
            wp_die('Fichier non trouvé');
        }
        
        $handle = fopen($file_path, 'r');
        if (!$handle) {
            wp_die('Impossible de lire le fichier');
        }
        
        $data = [];
        $first_line = fgets($handle);
        $delimiter = (substr_count($first_line, ';') > substr_count($first_line, ',')) ? ';' : ',';
        rewind($handle);
        
        while (($row = fgetcsv($handle, 0, $delimiter)) !== false) {
            $data[] = array_map(function($cell) {
                return mb_convert_encoding($cell, 'UTF-8', 'auto');
            }, $row);
        }
        fclose($handle);
        
        $original_columns_count = count($data[0]);
        $data = $this->td_filter_empty_columns($data);
        $filtered_columns_count = count($data[0]);
        $hidden_columns_count = $original_columns_count - $filtered_columns_count;
        
        $upload_time = get_option('td_csv_upload_time_' . md5($filename), filemtime($file_path));
        $mod_time = filemtime($file_path);
        $file_size = size_format(filesize($file_path));
        $lines_count = count($data) - 1;
        
        ?>
        <div class="wrap">
            <h1>
                <?php echo esc_html($filename); ?>
                <a href="<?php echo admin_url('admin.php?page=td-archives-list'); ?>" class="page-title-action">← Retour à la liste</a>
            </h1>
            
            <div class="td-detail-container">
                <div class="td-file-info">
                    <div class="td-info-grid">
                        <div class="td-info-item">
                            <strong>Nom du fichier :</strong>
                            <span><?php echo esc_html($filename); ?></span>
                        </div>
                        <div class="td-info-item">
                            <strong>Date d'envoi :</strong>
                            <span><?php echo date('d/m/Y à H:i', $upload_time); ?></span>
                        </div>
                        <div class="td-info-item">
                            <strong>Dernière modification :</strong>
                            <span><?php echo date('d/m/Y à H:i', $mod_time); ?></span>
                        </div>
                        <div class="td-info-item">
                            <strong>Nombre de lignes :</strong>
                            <span><?php echo number_format($lines_count); ?></span>
                        </div>
                        <div class="td-info-item">
                            <strong>Taille du fichier :</strong>
                            <span><?php echo $file_size; ?></span>
                        </div>
                        <div class="td-info-item">
                            <strong>Actions :</strong>
                            <span>
                                <a href="<?php echo wp_nonce_url(admin_url('admin-ajax.php?action=td_download_csv&file=' . urlencode($filename)), 'td_download_nonce'); ?>" class="button">Télécharger</a>
                                <button class="button button-link-delete td-delete-csv" data-file="<?php echo esc_attr($filename); ?>" data-redirect="list">Supprimer</button>
                            </span>
                        </div>
                    </div>
                </div>
                
                <?php if (!empty($data)): ?>
                    <div class="td-csv-content">
                        <h2>Liste des participants (<?php echo count($data) - 1; ?> inscriptions)</h2>
                        
                        <?php if (count($data) > 1): ?>
                            <div class="td-summary-stats">
                                <?php echo $this->td_get_registration_stats($data); ?>
                            </div>
                            
                            <?php if ($hidden_columns_count > 0): ?>
                                <div class="td-hidden-columns-notice">
                                    <p><strong>Note :</strong> <?php echo $hidden_columns_count; ?> colonne(s) masquée(s) pour améliorer la lisibilité.</p>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                        
                        <div class="td-table-container">
                            <table class="td-csv-table wp-list-table widefat fixed striped">
                                <?php if (!empty($data[0])): ?>
                                    <thead>
                                        <tr>
                                            <?php foreach ($data[0] as $index => $header): ?>
                                                <th class="<?php echo $this->td_get_column_class($header); ?>">
                                                    <?php echo esc_html($this->td_format_header($header)); ?>
                                                </th>
                                            <?php endforeach; ?>
                                        </tr>
                                    </thead>
                                <?php endif; ?>
                                <tbody>
                                    <?php for ($i = 1; $i < count($data); $i++): ?>
                                        <tr class="<?php echo $this->td_get_row_class($data[$i], $data[0]); ?>">
                                            <?php foreach ($data[$i] as $index => $cell): ?>
                                                <td class="<?php echo $this->td_get_column_class($data[0][$index] ?? ''); ?>" <?php echo strlen($cell) > 30 ? 'title="' . esc_attr($cell) . '"' : ''; ?>>
                                                    <?php echo $this->td_format_cell_content($cell, $data[0][$index] ?? ''); ?>
                                                </td>
                                            <?php endforeach; ?>
                                        </tr>
                                    <?php endfor; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="td-empty-content">
                        <p>Le fichier est vide ou ne peut pas être lu.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }
    
    // Fonctions AJAX et utilitaires
    public function td_convert_html_to_csv() {
        if (!wp_verify_nonce($_POST['nonce'], 'td_archives_nonce')) {
            wp_send_json_error('Nonce invalide');
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permissions insuffisantes');
        }
        
        $html_content = stripslashes($_POST['html_content']);
        $event_name = sanitize_text_field($_POST['event_name']);
        $event_date = sanitize_text_field($_POST['event_date']);
        $event_location = sanitize_text_field($_POST['event_location']);
        $output_filename = sanitize_file_name($_POST['output_filename']);
        $preview_only = isset($_POST['preview_only']) && $_POST['preview_only'] === 'true';
        
        if (empty($html_content) || empty($event_name) || empty($event_date) || empty($event_location)) {
            wp_send_json_error('Tous les champs sont requis');
        }
        
        // Parser le HTML
        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        
        if (!$dom->loadHTML('<?xml encoding="UTF-8">' . $html_content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD)) {
            wp_send_json_error('HTML invalide');
        }
        
        $tables = $dom->getElementsByTagName('table');
        if ($tables->length === 0) {
            wp_send_json_error('Aucun tableau trouvé dans le HTML');
        }
        
        $table = $tables->item(0);
        $rows = $table->getElementsByTagName('tr');
        
        if ($rows->length < 2) {
            wp_send_json_error('Le tableau doit contenir au moins une ligne d\'en-tête et une ligne de données');
        }
        
        // Analyser l'en-tête
        $header_row = $rows->item(0);
        $headers = [];
        $header_cells = $header_row->getElementsByTagName('th');
        if ($header_cells->length === 0) {
            $header_cells = $header_row->getElementsByTagName('td');
        }
        
        foreach ($header_cells as $cell) {
            $headers[] = trim(strtolower($cell->textContent));
        }
        
        // Mapper les colonnes
        $column_map = $this->td_map_html_columns($headers);
        
        if ($column_map['nom'] === -1 && $column_map['prenom'] === -1) {
            wp_send_json_error('Colonnes nom et prénom requises non trouvées');
        }
        
        // Extraire les données
        $parsed_data = [];
        for ($i = 1; $i < $rows->length; $i++) {
            $row = $rows->item($i);
            $cells = $row->getElementsByTagName('td');
            if ($cells->length === 0) continue;
            
            $row_data = [
                'nom' => $column_map['nom'] !== -1 ? trim($cells->item($column_map['nom'])->textContent ?? '') : '',
                'nom2' => $column_map['nom2'] !== -1 ? trim($cells->item($column_map['nom2'])->textContent ?? '') : '',
                'prenom' => $column_map['prenom'] !== -1 ? trim($cells->item($column_map['prenom'])->textContent ?? '') : '',
                'laboratoire' => $column_map['laboratoire'] !== -1 ? trim($cells->item($column_map['laboratoire'])->textContent ?? '') : '',
                'villeLabo' => $column_map['ville'] !== -1 ? trim($cells->item($column_map['ville'])->textContent ?? '') : '',
                'eventName' => $event_name,
                'eventDate' => $event_date,
                'eventLocation' => $event_location
            ];
            
            // Nettoyer les espaces multiples
            foreach ($row_data as $key => $value) {
                $row_data[$key] = preg_replace('/\s+/', ' ', trim($value));
            }
            
            if (!empty($row_data['nom']) || !empty($row_data['prenom'])) {
                $parsed_data[] = $row_data;
            }
        }
        
        if (empty($parsed_data)) {
            wp_send_json_error('Aucune donnée valide trouvée');
        }
        
        // Si c'est juste pour la prévisualisation
        if ($preview_only) {
            $preview_html = $this->td_generate_preview_html($parsed_data);
            wp_send_json_success(['preview' => $preview_html]);
            return;
        }
        
        // Générer le CSV
        $csv_content = $this->td_generate_csv_content($parsed_data, $event_date);
        
        // Générer le nom de fichier
        if (empty($output_filename)) {
            $safe_event_name = sanitize_file_name(strtolower($event_name));
            $safe_event_name = preg_replace('/[^a-z0-9_-]/', '_', $safe_event_name);
            $output_filename = 'participants_' . $safe_event_name . '.csv';
        } else {
            if (!str_ends_with($output_filename, '.csv')) {
                $output_filename .= '.csv';
            }
        }
        
        // Sauvegarder le fichier
        $upload_dir = wp_upload_dir();
        $csv_dir = $upload_dir['basedir'] . '/td-archives-csv';
        $file_path = $csv_dir . '/' . $output_filename;
        
        if (file_put_contents($file_path, $csv_content) === false) {
            wp_send_json_error('Erreur lors de la sauvegarde du fichier');
        }
        
        // Enregistrer la date d'upload
        update_option('td_csv_upload_time_' . md5($output_filename), current_time('timestamp'));
        
        wp_send_json_success([
            'message' => 'Conversion réussie et fichier sauvegardé',
            'filename' => $output_filename,
            'count' => count($parsed_data),
            'redirect' => admin_url('admin.php?page=td-archives-list')
        ]);
    }
    
    public function td_rename_csv() {
        if (!wp_verify_nonce($_POST['nonce'], 'td_archives_nonce')) {
            wp_send_json_error('Nonce invalide');
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permissions insuffisantes');
        }
        
        $old_filename = sanitize_file_name($_POST['old_filename']);
        $new_filename = sanitize_file_name($_POST['new_filename']);
        
        if (!str_ends_with($new_filename, '.csv')) {
            $new_filename .= '.csv';
        }
        
        $upload_dir = wp_upload_dir();
        $csv_dir = $upload_dir['basedir'] . '/td-archives-csv';
        $old_path = $csv_dir . '/' . $old_filename;
        $new_path = $csv_dir . '/' . $new_filename;
        
        if (!file_exists($old_path)) {
            wp_send_json_error('Fichier source non trouvé');
        }
        
        if (file_exists($new_path) && $old_filename !== $new_filename) {
            wp_send_json_error('Un fichier avec ce nom existe déjà');
        }
        
        if (rename($old_path, $new_path)) {
            // Mettre à jour les métadonnées
            $old_meta_key = 'td_csv_upload_time_' . md5($old_filename);
            $new_meta_key = 'td_csv_upload_time_' . md5($new_filename);
            $upload_time = get_option($old_meta_key, current_time('timestamp'));
            
            update_option($new_meta_key, $upload_time);
            delete_option($old_meta_key);
            
            wp_send_json_success([
                'message' => 'Fichier renommé avec succès',
                'new_filename' => $new_filename
            ]);
        } else {
            wp_send_json_error('Erreur lors du renommage');
        }
    }
    
    // Fonctions utilitaires privées
    private function td_map_html_columns($headers) {
        $map = [
            'nom' => -1,
            'nom2' => -1,
            'prenom' => -1,
            'laboratoire' => -1,
            'ville' => -1
        ];
        
        $nom_count = 0;
        foreach ($headers as $index => $header) {
            if (strpos($header, 'nom') !== false && strpos($header, 'prenom') === false && strpos($header, 'prénom') === false) {
                if ($nom_count === 0) {
                    $map['nom'] = $index;
                    $nom_count++;
                } elseif ($nom_count === 1) {
                    $map['nom2'] = $index;
                    $nom_count++;
                }
            } elseif (strpos($header, 'prenom') !== false || strpos($header, 'prénom') !== false) {
                $map['prenom'] = $index;
            } elseif (strpos($header, 'lab') !== false || strpos($header, 'laboratoire') !== false) {
                $map['laboratoire'] = $index;
            } elseif (strpos($header, 'ville') !== false || strpos($header, 'city') !== false) {
                $map['ville'] = $index;
            }
        }
        
        return $map;
    }
    
    private function td_generate_preview_html($data) {
        if (empty($data)) return '<p>Aucune donnée à prévisualiser</p>';
        
        $html = '<div class="td-preview-stats">';
        $html .= '<strong>' . count($data) . '</strong> participants détectés';
        $html .= '</div>';
        
        $html .= '<table class="td-preview-table wp-list-table widefat fixed striped">';
        $html .= '<thead><tr>';
        $html .= '<th>Nom</th><th>Nom2</th><th>Prénom</th><th>Laboratoire</th><th>Ville Labo</th><th>Événement</th><th>Date</th><th>Lieu Événement</th>';
        $html .= '</tr></thead>';
        $html .= '<tbody>';
        
        $preview_data = array_slice($data, 0, 5);
        foreach ($preview_data as $row) {
            $formatted_date = $this->td_format_date_to_french($row['eventDate']);
            $html .= '<tr>';
            $html .= '<td>' . esc_html($row['nom']) . '</td>';
            $html .= '<td>' . esc_html($row['nom2']) . '</td>';
            $html .= '<td>' . esc_html($row['prenom']) . '</td>';
            $html .= '<td>' . esc_html($row['laboratoire']) . '</td>';
            $html .= '<td>' . esc_html($row['villeLabo']) . '</td>';
            $html .= '<td>' . esc_html($row['eventName']) . '</td>';
            $html .= '<td>' . esc_html($formatted_date) . '</td>';
            $html .= '<td>' . esc_html($row['eventLocation']) . '</td>';
            $html .= '</tr>';
        }
        
        $html .= '</tbody></table>';
        
        if (count($data) > 5) {
            $html .= '<p class="td-preview-note">... et ' . (count($data) - 5) . ' autres participants</p>';
        }
        
        return $html;
    }
    
    private function td_generate_csv_content($data, $event_date) {
        $headers = [
            "CASID", "USERNAME", "LASTNAME", "LASTNAME2", "FIRSTNAME", "MAIL", "CIV", "URL", "PHONE",
            "Adresse de facturation Paybox", "Code postal de facturation Paybox", 
            "Ville de facturation Paybox", "Pays de facturation Paybox",
            "Affiliation sur le badge (labo+ville)", 
            "Si vous souhaitez faire une présentation à la réunion GBP, merci d'indiquer le titre",
            "Avez-vous des demandes particulières?", "Etablissement d'appartenance",
            "Adresse postale de l'organisme", "Pays de votre organisme", "Laboratoire",
            "Evenement", "Date_Evenement", "Lieu_Evenement", "Ville_Laboratoire"
        ];
        
        $csv_content = implode(',', $headers) . "\n";
        
        foreach ($data as $index => $row) {
            $formatted_date = $this->td_format_date_to_french($row['eventDate']);
            $username = strtolower(preg_replace('/\s/', '', $row['prenom'] . $row['nom'] . $row['nom2']));
            
            $csv_row = [
                '"' . ($index + 1) . '"',
                '"' . $username . '"',
                '"' . $row['nom'] . '"',
                '"' . $row['nom2'] . '"',
                '"' . $row['prenom'] . '"',
                '""', '""', '""', '""', '""', '""', '""', '""',
                '"' . $row['laboratoire'] . ' ' . $row['villeLabo'] . '"',
                '""', '""', '""', '""', '""',
                '"' . $row['laboratoire'] . '"',
                '"' . $row['eventName'] . '"',
                '"' . $formatted_date . '"',
                '"' . $row['eventLocation'] . '"',
                '"' . $row['villeLabo'] . '"'
            ];
            
            $csv_content .= implode(',', $csv_row) . "\n";
        }
        
        return $csv_content;
    }
    
    private function td_format_date_to_french($date_string) {
        if (empty($date_string)) return '';
        
        $date = DateTime::createFromFormat('Y-m-d', $date_string);
        if (!$date) return $date_string;
        
        return $date->format('d/m/Y');
    }
    
    // Fonctions d'affichage et de traitement des données
    public function td_count_csv_lines($file) {
        if (!file_exists($file)) {
            return 0;
        }
        
        $handle = fopen($file, 'r');
        if (!$handle) {
            return 0;
        }
        
        $first_line = fgets($handle);
        $delimiter = (substr_count($first_line, ';') > substr_count($first_line, ',')) ? ';' : ',';
        rewind($handle);
        
        $lines = 0;
        while (fgetcsv($handle, 0, $delimiter) !== false) {
            $lines++;
        }
        fclose($handle);
        
        return max(0, $lines - 1);
    }
    
    public function td_format_header($header) {
        $formatted_headers = [
            'UID' => 'ID Utilisateur',
            'CASID' => 'ID CAS',
            'USERNAME' => 'Nom d\'utilisateur',
            'LASTNAME' => 'Nom',
            'LASTNAME2' => 'Nom 2',
            'FIRSTNAME' => 'Prénom',
            'MAIL' => 'Email',
            'VALID' => 'Validé',
            'CIV' => 'Civilité',
            'MIDDLENAME' => 'Deuxième prénom',
            'URL' => 'Site web',
            'LANGUEID' => 'Langue',
            'PHONE' => 'Téléphone',
            'DATE' => 'Date d\'inscription',
            'Affiliation sur le badge (labo+ville)' => 'Affiliation',
            'Inscription à la journée RMN-GBP' => 'Journée RMN-GBP',
            'STATUS' => 'Statut',
            'Evenement' => 'Événement',
            'Date_Evenement' => 'Date événement',
            'Lieu_Evenement' => 'Lieu événement',
            'Ville_Laboratoire' => 'Ville laboratoire'
        ];
        
        return $formatted_headers[$header] ?? $header;
    }
    
    public function td_get_column_class($header) {
        $classes = [
            'LASTNAME' => 'td-col-name',
            'LASTNAME2' => 'td-col-name',
            'FIRSTNAME' => 'td-col-name',
            'MAIL' => 'td-col-email',
            'DATE' => 'td-col-date',
            'Date_Evenement' => 'td-col-date',
            'STATUS' => 'td-col-status',
            'VALID' => 'td-col-valid',
            'Affiliation sur le badge (labo+ville)' => 'td-col-affiliation',
            'Evenement' => 'td-col-event',
            'Lieu_Evenement' => 'td-col-location',
            'Ville_Laboratoire' => 'td-col-location'
        ];
        
        return $classes[$header] ?? 'td-col-default';
    }
    
    public function td_get_row_class($row_data, $headers) {
        $status_index = array_search('STATUS', $headers);
        if ($status_index !== false && isset($row_data[$status_index])) {
            $status = strtolower($row_data[$status_index]);
            return 'td-row-' . sanitize_html_class($status);
        }
        return '';
    }
    
    public function td_format_cell_content($cell, $header) {
        switch ($header) {
            case 'MAIL':
                return '<a href="mailto:' . esc_attr($cell) . '">' . esc_html($cell) . '</a>';
                
            case 'DATE':
            case 'Date_Evenement':
                if (!empty($cell)) {
                    $date = DateTime::createFromFormat('d/m/Y H:i', $cell);
                    if (!$date) {
                        $date = DateTime::createFromFormat('d/m/Y', $cell);
                    }
                    return $date ? $date->format('d/m/Y à H:i') : esc_html($cell);
                }
                return '';
                
            case 'VALID':
                return $cell == '1' ? '<span class="td-badge td-valid">✓ Validé</span>' : '<span class="td-badge td-invalid">✗ Non validé</span>';
                
            case 'STATUS':
                $status_class = 'td-status-' . sanitize_html_class(strtolower($cell));
                return '<span class="td-badge ' . $status_class . '">' . esc_html($cell) . '</span>';
                
            case 'Inscription à la journée RMN-GBP':
            case 'Assisterez-vous à la réunion d\'échange sur la spectroscopie oxygène 17?':
                if (strtolower($cell) === 'oui') {
                    return '<span class="td-badge td-yes">✓ Oui</span>';
                } elseif (strtolower($cell) === 'non') {
                    return '<span class="td-badge td-no">✗ Non</span>';
                }
                return esc_html($cell);
                
            default:
                return esc_html($cell);
        }
    }
    
    public function td_get_registration_stats($data) {
        if (count($data) < 2) {
            return '';
        }
        
        $headers = $data[0];
        $participants = array_slice($data, 1);
        $total_participants = count($participants);
        
        $affiliation_index = array_search('Affiliation sur le badge (labo+ville)', $headers);
        $lab_index = array_search('Laboratoire', $headers);
        $ville_lab_index = array_search('Ville_Laboratoire', $headers);
        
        $unique_affiliations = [];
        
        // Chercher les affiliations dans différentes colonnes
        $affiliation_column = $affiliation_index !== false ? $affiliation_index : 
                            ($lab_index !== false ? $lab_index : $ville_lab_index);
        
        if ($affiliation_column !== false) {
            foreach ($participants as $participant) {
                if (isset($participant[$affiliation_column]) && !empty(trim($participant[$affiliation_column]))) {
                    $affiliation = trim($participant[$affiliation_column]);
                    $unique_affiliations[$affiliation] = true;
                }
            }
        }
        
        $total_labs = count($unique_affiliations);
        
        // Détecter si c'est un CSV converti (avec informations d'événement)
        $event_index = array_search('Evenement', $headers);
        $event_date_index = array_search('Date_Evenement', $headers);
        $event_location_index = array_search('Lieu_Evenement', $headers);
        
        $output = '<div class="td-stats-grid">';
        $output .= '<div class="td-stat-item"><strong>' . $total_participants . '</strong><span>Participants</span></div>';
        $output .= '<div class="td-stat-item"><strong>' . $total_labs . '</strong><span>Laboratoires</span></div>';
        
        // Afficher les infos d'événement si disponibles (séparément)
        if ($event_index !== false && !empty($participants[0][$event_index])) {
            $output .= '<div class="td-stat-item"><strong>' . esc_html($participants[0][$event_index]) . '</strong><span>Événement</span></div>';
        }
        
        if ($event_date_index !== false && !empty($participants[0][$event_date_index])) {
            $output .= '<div class="td-stat-item"><strong>' . esc_html($participants[0][$event_date_index]) . '</strong><span>Date</span></div>';
        }
        
        if ($event_location_index !== false && !empty($participants[0][$event_location_index])) {
            $output .= '<div class="td-stat-item"><strong>' . esc_html($participants[0][$event_location_index]) . '</strong><span>Lieu</span></div>';
        }
        
        $output .= '</div>';
        
        return $output;
    }
    
    public function td_filter_empty_columns($data) {
        if (empty($data)) {
            return $data;
        }
        
        $hidden_columns_option = get_option('td_archives_hidden_columns', '');
        $configured_hidden_columns = [];
        
        if (!empty($hidden_columns_option)) {
            $lines = explode("\n", $hidden_columns_option);
            foreach ($lines as $line) {
                $columns = explode(',', $line);
                foreach ($columns as $column) {
                    $column = trim($column);
                    if (!empty($column)) {
                        $configured_hidden_columns[] = $column;
                    }
                }
            }
        }
        
        $headers = $data[0];
        $participants = array_slice($data, 1);
        $columns_to_keep = [];
        
        for ($col = 0; $col < count($headers); $col++) {
            $header = trim($headers[$col]);
            
            if (in_array($header, $configured_hidden_columns)) {
                continue;
            }
            
            $has_content = false;
            foreach ($participants as $participant) {
                if (isset($participant[$col]) && !empty(trim($participant[$col]))) {
                    $has_content = true;
                    break;
                }
            }
            
            if ($has_content) {
                $columns_to_keep[] = $col;
            }
        }
        
        $filtered_data = [];
        foreach ($data as $row) {
            $filtered_row = [];
            foreach ($columns_to_keep as $col_index) {
                $filtered_row[] = isset($row[$col_index]) ? $row[$col_index] : '';
            }
            $filtered_data[] = $filtered_row;
        }
        
        return $filtered_data;
    }
    
    public function td_save_options() {
        if (!wp_verify_nonce($_POST['td_options_nonce'], 'td_options_nonce')) {
            wp_die('Nonce invalide');
        }
        
        if (!current_user_can('manage_options')) {
            wp_die('Permissions insuffisantes');
        }
        
        $hidden_columns = stripslashes(sanitize_textarea_field($_POST['td_hidden_columns']));
        update_option('td_archives_hidden_columns', $hidden_columns);
        
        wp_redirect(admin_url('admin.php?page=td-archives-options&settings-updated=1'));
        exit;
    }
    
    public function td_get_detected_columns_list() {
        $upload_dir = wp_upload_dir();
        $csv_dir = $upload_dir['basedir'] . '/td-archives-csv';
        
        if (!is_dir($csv_dir)) {
            return '<p>Aucun fichier CSV trouvé.</p>';
        }
        
        $hidden_columns_option = stripslashes(get_option('td_archives_hidden_columns', ''));
        $hidden_columns = [];
        if (!empty($hidden_columns_option)) {
            foreach (explode("\n", $hidden_columns_option) as $line) {
                foreach (explode(',', $line) as $column) {
                    $column = trim($column);
                    if (!empty($column)) {
                        $hidden_columns[] = $column;
                    }
                }
            }
        }
        
        $files = glob($csv_dir . '/*.csv');
        $all_columns = [];
        
        foreach ($files as $file) {
            $handle = fopen($file, 'r');
            if ($handle) {
                $first_line = fgets($handle);
                $delimiter = (substr_count($first_line, ';') > substr_count($first_line, ',')) ? ';' : ',';
                rewind($handle);
                
                $headers = fgetcsv($handle, 0, $delimiter);
                if ($headers) {
                    foreach ($headers as $header) {
                        $all_columns[trim($header)] = true;
                    }
                }
                fclose($handle);
            }
        }
        
        if (empty($all_columns)) {
            return '<p>Aucune colonne détectée.</p>';
        }
        
        $output = '<div class="td-columns-list">';
        foreach (array_keys($all_columns) as $column) {
            $is_hidden = in_array($column, $hidden_columns);
            $class = $is_hidden ? 'td-column-tag td-tag-selected' : 'td-column-tag';
            $output .= '<span class="' . $class . '">' . esc_html($column) . '</span>';
        }
        $output .= '</div>';
        
        return $output;
    }
    
    public function td_handle_csv_upload() {
        if (!wp_verify_nonce($_POST['nonce'], 'td_archives_nonce')) {
            wp_die('Nonce invalide');
        }
        
        if (!current_user_can('manage_options')) {
            wp_die('Permissions insuffisantes');
        }
        
        if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
            wp_send_json_error('Erreur lors de l\'upload du fichier');
        }
        
        $file = $_FILES['csv_file'];
        $filename = sanitize_file_name($file['name']);
        
        $file_ext = pathinfo($filename, PATHINFO_EXTENSION);
        if (strtolower($file_ext) !== 'csv') {
            wp_send_json_error('Seuls les fichiers CSV sont autorisés');
        }
        
        $upload_dir = wp_upload_dir();
        $csv_dir = $upload_dir['basedir'] . '/td-archives-csv';
        $destination = $csv_dir . '/' . $filename;
        
        $file_exists = file_exists($destination);
        if ($file_exists && !isset($_POST['replace'])) {
            wp_send_json(['status' => 'exists', 'filename' => $filename]);
        }
        
        if (move_uploaded_file($file['tmp_name'], $destination)) {
            update_option('td_csv_upload_time_' . md5($filename), current_time('timestamp'));
            
            wp_send_json_success([
                'message' => 'Fichier uploadé avec succès',
                'redirect' => admin_url('admin.php?page=td-archives-list')
            ]);
        } else {
            wp_send_json_error('Erreur lors de la sauvegarde du fichier');
        }
    }
    
    public function td_delete_csv() {
        if (!wp_verify_nonce($_POST['nonce'], 'td_archives_nonce')) {
            wp_die('Nonce invalide');
        }
        
        if (!current_user_can('manage_options')) {
            wp_die('Permissions insuffisantes');
        }
        
        $filename = sanitize_file_name($_POST['filename']);
        $upload_dir = wp_upload_dir();
        $file_path = $upload_dir['basedir'] . '/td-archives-csv/' . $filename;
        
        if (!file_exists($file_path)) {
            wp_send_json_error('Fichier non trouvé');
        }
        
        if (unlink($file_path)) {
            delete_option('td_csv_upload_time_' . md5($filename));
            
            $redirect = isset($_POST['redirect']) && $_POST['redirect'] === 'list' 
                ? admin_url('admin.php?page=td-archives-list')
                : false;
            
            wp_send_json_success([
                'message' => 'Fichier supprimé avec succès',
                'redirect' => $redirect
            ]);
        } else {
            wp_send_json_error('Erreur lors de la suppression');
        }
    }
    
    public function td_download_csv() {
        if (!wp_verify_nonce($_GET['_wpnonce'], 'td_download_nonce')) {
            wp_die('Nonce invalide');
        }
        
        if (!current_user_can('manage_options')) {
            wp_die('Permissions insuffisantes');
        }
        
        $filename = sanitize_file_name($_GET['file']);
        $upload_dir = wp_upload_dir();
        $file_path = $upload_dir['basedir'] . '/td-archives-csv/' . $filename;
        
        if (!file_exists($file_path)) {
            wp_die('Fichier non trouvé');
        }
        
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($file_path));
        
        readfile($file_path);
        exit;
    }
}

// Initialiser le plugin
new TD_Archives_Rencontres_V2_Enhanced();
