<?php
// Enregistrer le type de publication personnalisé
add_action('init', 'wprg_register_post_type');
function wprg_register_post_type() {
    $labels = array(
        'name'               => 'Reels',
        'singular_name'      => 'Reel',
        'menu_name'          => 'Reels Gallery',
        'add_new'            => 'Ajouter un Reel',
        'add_new_item'       => 'Ajouter un nouveau Reel',
        'edit_item'          => 'Éditer le Reel',
        'new_item'           => 'Nouveau Reel',
        'view_item'          => 'Voir le Reel',
        'search_items'       => 'Rechercher des Reels',
        'not_found'          => 'Aucun Reel trouvé',
        'not_found_in_trash' => 'Aucun Reel trouvé dans la corbeille'
    );

    $args = array(
        'labels'              => $labels,
        'public'              => true,
        'publicly_queryable'  => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'query_var'           => true,
        'rewrite'             => array('slug' => 'reel'),
        'capability_type'     => 'post',
        'has_archive'         => true,
        'hierarchical'        => false,
        'menu_position'       => 20,
        'menu_icon'           => 'dashicons-video-alt3',
        'supports'            => array('title', 'thumbnail'),
        'show_in_rest'        => true,
        'taxonomies'          => array('wprg_gallery')
    );

    register_post_type('wprg_reel', $args);
    
    // Enregistrer la taxonomie pour les galeries
    register_taxonomy(
        'wprg_gallery',
        'wprg_reel',
        array(
            'labels' => array(
                'name'              => 'Galeries',
                'singular_name'     => 'Galerie',
                'search_items'      => 'Rechercher des galeries',
                'all_items'         => 'Toutes les galeries',
                'parent_item'       => 'Galerie parente',
                'parent_item_colon' => 'Galerie parente:',
                'edit_item'         => 'Éditer la galerie',
                'update_item'       => 'Mettre à jour la galerie',
                'add_new_item'      => 'Ajouter une nouvelle galerie',
                'new_item_name'     => 'Nouveau nom de galerie',
                'menu_name'         => 'Galeries'
            ),
            'hierarchical'      => true,
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'rewrite'           => array('slug' => 'galerie-reels'),
            'show_in_rest'      => true,
            'show_in_nav_menus' => true,
            'show_tagcloud'     => false,
            'meta_box_cb'       => 'post_categories_meta_box'
        )
    );
}

// AMÉLIORATION : Définir les colonnes personnalisées
add_filter('manage_wprg_reel_posts_columns', 'wprg_set_custom_columns');
function wprg_set_custom_columns($columns) {
    $new_columns = array();
    
    // Première colonne : case à cocher (conservée)
    $new_columns['cb'] = $columns['cb'];
    
    // Nouvelle colonne : Thumbnail
    $new_columns['wprg_thumbnail'] = '<span class="dashicons dashicons-format-image"></span> <span class="wprg-column-label">Miniature</span>';
    
    // Colonne Titre
    $new_columns['title'] = 'Titre';
    
    // Colonne Type (YouTube/Upload)
    $new_columns['wprg_type'] = '<span class="dashicons dashicons-video-alt3"></span> <span class="wprg-column-label">Type</span>';
    
    // Colonne Galerie
    $new_columns['wprg_gallery'] = '<span class="dashicons dashicons-category"></span> <span class="wprg-column-label">Galerie</span>';
    
    // Colonne Likes
    $new_columns['wprg_likes'] = '<span class="dashicons dashicons-heart" style="color:#e1306c;"></span> <span class="wprg-column-label">J\'aime</span>';
    
    // Colonne Vues
    $new_columns['wprg_views'] = '<span class="dashicons dashicons-visibility"></span> <span class="wprg-column-label">Vues</span>';
    
    // Date
    $new_columns['date'] = $columns['date'];
    
    return $new_columns;
}

// AMÉLIORATION : Remplir les colonnes personnalisées
add_action('manage_wprg_reel_posts_custom_column', 'wprg_custom_column_content', 10, 2);
function wprg_custom_column_content($column, $post_id) {
    switch ($column) {
        
        // Colonne Thumbnail
        case 'wprg_thumbnail':
            if (has_post_thumbnail($post_id)) {
                $thumbnail_url = get_the_post_thumbnail_url($post_id, 'thumbnail');
                echo '<div class="wprg-admin-thumbnail">';
                echo '<img src="' . esc_url($thumbnail_url) . '" alt="' . esc_attr(get_the_title($post_id)) . '">';
                echo '</div>';
            } else {
                // Essayer de générer une miniature depuis YouTube
                $video_type = get_post_meta($post_id, '_wprg_video_type', true);
                if ($video_type == 'youtube') {
                    $video_url = get_post_meta($post_id, '_wprg_video_url', true);
                    $youtube_id = wprg_get_youtube_id($video_url);
                    if ($youtube_id) {
                        echo '<div class="wprg-admin-thumbnail wprg-admin-thumbnail-youtube">';
                        echo '<img src="https://img.youtube.com/vi/' . $youtube_id . '/default.jpg" alt="YouTube thumbnail">';
                        echo '<span class="wprg-thumbnail-badge">YT</span>';
                        echo '</div>';
                    } else {
                        echo '<div class="wprg-admin-thumbnail wprg-admin-thumbnail-placeholder">';
                        echo '<span class="dashicons dashicons-video-alt3"></span>';
                        echo '</div>';
                    }
                } else {
                    echo '<div class="wprg-admin-thumbnail wprg-admin-thumbnail-placeholder">';
                    echo '<span class="dashicons dashicons-format-video"></span>';
                    echo '</div>';
                }
            }
            break;
        
        // Colonne Type
        case 'wprg_type':
            $type = get_post_meta($post_id, '_wprg_video_type', true);
            if ($type == 'youtube') {
                echo '<span class="wprg-type-badge wprg-type-youtube">';
                echo '<span class="dashicons dashicons-youtube"></span> YouTube';
                echo '</span>';
            } else {
                echo '<span class="wprg-type-badge wprg-type-upload">';
                echo '<span class="dashicons dashicons-upload"></span> Upload';
                echo '</span>';
            }
            break;
        
        // Colonne Galerie
        case 'wprg_gallery':
            $terms = get_the_terms($post_id, 'wprg_gallery');
            if ($terms && !is_wp_error($terms)) {
                $term_links = array();
                foreach ($terms as $term) {
                    $term_links[] = '<a href="edit.php?post_type=wprg_reel&wprg_gallery=' . $term->slug . '" class="wprg-gallery-tag">' . $term->name . '</a>';
                }
                echo implode(' ', $term_links);
            } else {
                echo '<span class="wprg-no-gallery">—</span>';
            }
            break;
        
        // Colonne Likes
        case 'wprg_likes':
            $likes = get_post_meta($post_id, '_wprg_likes', true) ?: 0;
            $liked_ips = get_post_meta($post_id, '_wprg_liked_ips', true) ?: array();
            $unique_likes = count($liked_ips);
            
            // Utiliser le plus élevé des deux (par sécurité)
            $display_likes = max($likes, $unique_likes);
            
            if ($display_likes > 0) {
                echo '<span class="wprg-likes-badge">';
                echo '<span class="dashicons dashicons-heart"></span>';
                echo ' <span class="wprg-likes-count">' . number_format($display_likes) . '</span>';
                echo '</span>';
            } else {
                echo '<span class="wprg-likes-badge wprg-likes-zero">';
                echo '<span class="dashicons dashicons-heart"></span>';
                echo ' 0';
                echo '</span>';
            }
            break;
        
        // Colonne Vues
        case 'wprg_views':
            $views = get_post_meta($post_id, '_wprg_views', true) ?: 0;
            if ($views > 0) {
                echo '<span class="wprg-views-badge">';
                echo '<span class="dashicons dashicons-visibility"></span>';
                echo ' ' . number_format($views);
                echo '</span>';
            } else {
                echo '<span class="wprg-views-badge wprg-views-zero">';
                echo '<span class="dashicons dashicons-visibility"></span> 0';
                echo '</span>';
            }
            break;
    }
}

// AMÉLIORATION : Rendre les colonnes triables
add_filter('manage_edit-wprg_reel_sortable_columns', 'wprg_sortable_columns');
function wprg_sortable_columns($columns) {
    $columns['wprg_likes'] = 'wprg_likes';
    $columns['wprg_views'] = 'wprg_views';
    $columns['wprg_type'] = 'wprg_type';
    return $columns;
}

// AMÉLIORATION : Gérer le tri
add_action('pre_get_posts', 'wprg_sort_columns_query');
function wprg_sort_columns_query($query) {
    if (!is_admin() || !$query->is_main_query() || $query->get('post_type') != 'wprg_reel') {
        return;
    }
    
    $orderby = $query->get('orderby');
    
    if ($orderby == 'wprg_likes') {
        $query->set('meta_key', '_wprg_likes');
        $query->set('orderby', 'meta_value_num');
    }
    
    if ($orderby == 'wprg_views') {
        $query->set('meta_key', '_wprg_views');
        $query->set('orderby', 'meta_value_num');
    }
}

// Ajouter des champs personnalisés pour les paramètres de galerie
add_action('wprg_gallery_add_form_fields', 'wprg_add_gallery_fields');
function wprg_add_gallery_fields() {
    ?>
    <div class="wprg-gallery-settings-panel">
        <div class="wprg-settings-header">
            <span class="dashicons dashicons-slides"></span>
            <h3>Paramètres du carrousel</h3>
        </div>
        
        <div class="wprg-settings-grid">
            <div class="wprg-settings-field">
                <label for="wprg_carousel_limit">
                    <span class="wprg-field-icon">📊</span>
                    <span class="wprg-field-label">Nombre maximum de publications</span>
                </label>
                <input type="number" name="wprg_carousel_limit" id="wprg_carousel_limit" value="12" min="1" max="100">
                <p class="description">Nombre total de reels à afficher</p>
            </div>
            
            <div class="wprg-settings-field">
                <label>
                    <span class="wprg-field-icon">💻</span>
                    <span class="wprg-field-label">Éléments visibles</span>
                </label>
                <div class="wprg-device-inputs">
                    <div class="wprg-device-item">
                        <span class="wprg-device-icon">🖥️</span>
                        <input type="number" name="wprg_desktop_items" value="6" min="1" max="10" placeholder="Desktop">
                        <span class="wprg-device-label">Desktop</span>
                    </div>
                    <div class="wprg-device-item">
                        <span class="wprg-device-icon">📱</span>
                        <input type="number" name="wprg_tablet_items" value="4" min="1" max="8" placeholder="Tablet">
                        <span class="wprg-device-label">Tablet</span>
                    </div>
                    <div class="wprg-device-item">
                        <span class="wprg-device-icon">📱</span>
                        <input type="number" name="wprg_mobile_items" value="2" min="1" max="5" placeholder="Mobile">
                        <span class="wprg-device-label">Mobile</span>
                    </div>
                </div>
            </div>
            
            <div class="wprg-settings-field">
                <label for="wprg_gap">
                    <span class="wprg-field-icon">↔️</span>
                    <span class="wprg-field-label">Espacement (px)</span>
                </label>
                <input type="number" name="wprg_gap" id="wprg_gap" value="20" min="0" max="50">
            </div>
        </div>
    </div>

    <div class="wprg-gallery-settings-panel">
        <div class="wprg-settings-header">
            <span class="dashicons dashicons-controls-play"></span>
            <h3>Lecture automatique</h3>
        </div>
        
        <div class="wprg-settings-grid">
            <div class="wprg-settings-field wprg-checkbox-field">
                <label>
                    <input type="checkbox" name="wprg_autoplay" id="wprg_autoplay" value="1">
                    <span class="wprg-checkbox-label">
                        <span class="wprg-field-icon">▶️</span>
                        Activer l'autoplay
                    </span>
                </label>
                <p class="description">Le carrousel défile automatiquement</p>
            </div>
            
            <div class="wprg-settings-field">
                <label for="wprg_autoplay_speed">
                    <span class="wprg-field-icon">⚡</span>
                    <span class="wprg-field-label">Vitesse d'autoplay (ms)</span>
                </label>
                <input type="number" name="wprg_autoplay_speed" id="wprg_autoplay_speed" value="3000" min="1000" max="10000" step="500">
                <p class="description">1000 ms = 1 seconde</p>
            </div>
            
            <div class="wprg-settings-field wprg-checkbox-field">
                <label>
                    <input type="checkbox" name="wprg_pause_hover" id="wprg_pause_hover" value="1" checked>
                    <span class="wprg-checkbox-label">
                        <span class="wprg-field-icon">⏸️</span>
                        Pause au survol
                    </span>
                </label>
            </div>
            
            <div class="wprg-settings-field wprg-checkbox-field">
                <label>
                    <input type="checkbox" name="wprg_loop" id="wprg_loop" value="1" checked>
                    <span class="wprg-checkbox-label">
                        <span class="wprg-field-icon">🔄</span>
                        Lecture en boucle (défilement infini)
                    </span>
                </label>
                <p class="description">Le carrousel défile en continu sans fin</p>
            </div>
        </div>
    </div>

    <div class="wprg-gallery-settings-panel">
        <div class="wprg-settings-header">
            <span class="dashicons dashicons-leftright"></span>
            <h3>Navigation</h3>
        </div>
        
        <div class="wprg-settings-grid">
            <div class="wprg-settings-field wprg-checkbox-field">
                <label>
                    <input type="checkbox" name="wprg_show_arrows" id="wprg_show_arrows" value="1" checked>
                    <span class="wprg-checkbox-label">
                        <span class="wprg-field-icon">⬅️ ➡️</span>
                        Afficher les flèches
                    </span>
                </label>
            </div>
            
            <div class="wprg-settings-field wprg-checkbox-field">
                <label>
                    <input type="checkbox" name="wprg_show_dots" id="wprg_show_dots" value="1" checked>
                    <span class="wprg-checkbox-label">
                        <span class="wprg-field-icon">⚪</span>
                        Afficher la pagination
                    </span>
                </label>
            </div>
            
            <div class="wprg-settings-field">
                <label for="wprg_animation_speed">
                    <span class="wprg-field-icon">⏱️</span>
                    <span class="wprg-field-label">Vitesse d'animation (ms)</span>
                </label>
                <input type="number" name="wprg_animation_speed" id="wprg_animation_speed" value="300" min="100" max="1000" step="50">
            </div>
        </div>
    </div>

    <div class="wprg-gallery-settings-panel">
        <div class="wprg-settings-header">
            <span class="dashicons dashicons-admin-generic"></span>
            <h3>Comportement</h3>
        </div>
        
        <div class="wprg-settings-grid">
            <div class="wprg-settings-field wprg-checkbox-field">
                <label>
                    <input type="checkbox" name="wprg_drag_scroll" id="wprg_drag_scroll" value="1" checked>
                    <span class="wprg-checkbox-label">
                        <span class="wprg-field-icon">👆</span>
                        Glissement
                    </span>
                </label>
                <p class="description">Activer le défilement par glissement</p>
            </div>
            
            <!-- Champ caché pour conserver la valeur de l'ancienne option infinite si elle existe -->
            <input type="hidden" name="wprg_infinite" value="0">
        </div>
    </div>
    <?php
}

add_action('wprg_gallery_edit_form_fields', 'wprg_edit_gallery_fields');
function wprg_edit_gallery_fields($term) {
    $limit = get_term_meta($term->term_id, 'wprg_carousel_limit', true) ?: 12;
    $desktop = get_term_meta($term->term_id, 'wprg_desktop_items', true) ?: 6;
    $tablet = get_term_meta($term->term_id, 'wprg_tablet_items', true) ?: 4;
    $mobile = get_term_meta($term->term_id, 'wprg_mobile_items', true) ?: 2;
    $gap = get_term_meta($term->term_id, 'wprg_gap', true) ?: 20;
    
    $autoplay = get_term_meta($term->term_id, 'wprg_autoplay', true);
    $autoplay_speed = get_term_meta($term->term_id, 'wprg_autoplay_speed', true) ?: 3000;
    $pause_hover = get_term_meta($term->term_id, 'wprg_pause_hover', true);
    $loop = get_term_meta($term->term_id, 'wprg_loop', true);
    
    $show_arrows = get_term_meta($term->term_id, 'wprg_show_arrows', true);
    $show_dots = get_term_meta($term->term_id, 'wprg_show_dots', true);
    $animation_speed = get_term_meta($term->term_id, 'wprg_animation_speed', true) ?: 300;
    
    $drag_scroll = get_term_meta($term->term_id, 'wprg_drag_scroll', true);
    // On ignore wprg_infinite car on utilise loop à la place
    ?>
    <tr class="wprg-edit-section">
        <td colspan="2">
            <div class="wprg-gallery-settings-panel">
                <div class="wprg-settings-header">
                    <span class="dashicons dashicons-slides"></span>
                    <h3>Paramètres du carrousel</h3>
                </div>
                
                <div class="wprg-settings-grid">
                    <div class="wprg-settings-field">
                        <label for="wprg_carousel_limit">
                            <span class="wprg-field-icon">📊</span>
                            <span class="wprg-field-label">Nombre maximum de publications</span>
                        </label>
                        <input type="number" name="wprg_carousel_limit" id="wprg_carousel_limit" value="<?php echo esc_attr($limit); ?>" min="1" max="100">
                        <p class="description">Nombre total de reels à afficher</p>
                    </div>
                    
                    <div class="wprg-settings-field">
                        <label>
                            <span class="wprg-field-icon">💻</span>
                            <span class="wprg-field-label">Éléments visibles</span>
                        </label>
                        <div class="wprg-device-inputs">
                            <div class="wprg-device-item">
                                <span class="wprg-device-icon">🖥️</span>
                                <input type="number" name="wprg_desktop_items" value="<?php echo esc_attr($desktop); ?>" min="1" max="10">
                                <span class="wprg-device-label">Desktop</span>
                            </div>
                            <div class="wprg-device-item">
                                <span class="wprg-device-icon">📱</span>
                                <input type="number" name="wprg_tablet_items" value="<?php echo esc_attr($tablet); ?>" min="1" max="8">
                                <span class="wprg-device-label">Tablet</span>
                            </div>
                            <div class="wprg-device-item">
                                <span class="wprg-device-icon">📱</span>
                                <input type="number" name="wprg_mobile_items" value="<?php echo esc_attr($mobile); ?>" min="1" max="5">
                                <span class="wprg-device-label">Mobile</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="wprg-settings-field">
                        <label for="wprg_gap">
                            <span class="wprg-field-icon">↔️</span>
                            <span class="wprg-field-label">Espacement (px)</span>
                        </label>
                        <input type="number" name="wprg_gap" id="wprg_gap" value="<?php echo esc_attr($gap); ?>" min="0" max="50">
                    </div>
                </div>
            </div>
        </td>
    </tr>

    <tr class="wprg-edit-section">
        <td colspan="2">
            <div class="wprg-gallery-settings-panel">
                <div class="wprg-settings-header">
                    <span class="dashicons dashicons-controls-play"></span>
                    <h3>Lecture automatique</h3>
                </div>
                
                <div class="wprg-settings-grid">
                    <div class="wprg-settings-field wprg-checkbox-field">
                        <label>
                            <input type="checkbox" name="wprg_autoplay" id="wprg_autoplay" value="1" <?php checked($autoplay, 1); ?>>
                            <span class="wprg-checkbox-label">
                                <span class="wprg-field-icon">▶️</span>
                                Activer l'autoplay
                            </span>
                        </label>
                    </div>
                    
                    <div class="wprg-settings-field">
                        <label for="wprg_autoplay_speed">
                            <span class="wprg-field-icon">⚡</span>
                            <span class="wprg-field-label">Vitesse d'autoplay (ms)</span>
                        </label>
                        <input type="number" name="wprg_autoplay_speed" id="wprg_autoplay_speed" value="<?php echo esc_attr($autoplay_speed); ?>" min="1000" max="10000" step="500">
                    </div>
                    
                    <div class="wprg-settings-field wprg-checkbox-field">
                        <label>
                            <input type="checkbox" name="wprg_pause_hover" value="1" <?php checked($pause_hover, 1); ?>>
                            <span class="wprg-checkbox-label">
                                <span class="wprg-field-icon">⏸️</span>
                                Pause au survol
                            </span>
                        </label>
                    </div>
                    
                    <div class="wprg-settings-field wprg-checkbox-field">
                        <label>
                            <input type="checkbox" name="wprg_loop" value="1" <?php checked($loop, 1); ?>>
                            <span class="wprg-checkbox-label">
                                <span class="wprg-field-icon">🔄</span>
                                Lecture en boucle (défilement infini)
                            </span>
                        </label>
                        <p class="description">Le carrousel défile en continu sans fin</p>
                    </div>
                </div>
            </div>
        </td>
    </tr>

    <tr class="wprg-edit-section">
        <td colspan="2">
            <div class="wprg-gallery-settings-panel">
                <div class="wprg-settings-header">
                    <span class="dashicons dashicons-leftright"></span>
                    <h3>Navigation</h3>
                </div>
                
                <div class="wprg-settings-grid">
                    <div class="wprg-settings-field wprg-checkbox-field">
                        <label>
                            <input type="checkbox" name="wprg_show_arrows" value="1" <?php checked($show_arrows, 1); ?>>
                            <span class="wprg-checkbox-label">
                                <span class="wprg-field-icon">⬅️ ➡️</span>
                                Afficher les flèches
                            </span>
                        </label>
                    </div>
                    
                    <div class="wprg-settings-field wprg-checkbox-field">
                        <label>
                            <input type="checkbox" name="wprg_show_dots" value="1" <?php checked($show_dots, 1); ?>>
                            <span class="wprg-checkbox-label">
                                <span class="wprg-field-icon">⚪</span>
                                Afficher la pagination
                            </span>
                        </label>
                    </div>
                    
                    <div class="wprg-settings-field">
                        <label for="wprg_animation_speed">
                            <span class="wprg-field-icon">⏱️</span>
                            <span class="wprg-field-label">Vitesse d'animation (ms)</span>
                        </label>
                        <input type="number" name="wprg_animation_speed" id="wprg_animation_speed" value="<?php echo esc_attr($animation_speed); ?>" min="100" max="1000" step="50">
                    </div>
                </div>
            </div>
        </td>
    </tr>

    <tr class="wprg-edit-section">
        <td colspan="2">
            <div class="wprg-gallery-settings-panel">
                <div class="wprg-settings-header">
                    <span class="dashicons dashicons-admin-generic"></span>
                    <h3>Comportement</h3>
                </div>
                
                <div class="wprg-settings-grid">
                    <div class="wprg-settings-field wprg-checkbox-field">
                        <label>
                            <input type="checkbox" name="wprg_drag_scroll" value="1" <?php checked($drag_scroll, 1); ?>>
                            <span class="wprg-checkbox-label">
                                <span class="wprg-field-icon">👆</span>
                                Glissement
                            </span>
                        </label>
                        <p class="description">Activer le défilement par glissement</p>
                    </div>
                    
                    <!-- Champ caché pour conserver la valeur de l'ancienne option infinite -->
                    <input type="hidden" name="wprg_infinite" value="0">
                </div>
            </div>
        </td>
    </tr>
    <?php
}

add_action('created_wprg_gallery', 'wprg_save_gallery_fields');
add_action('edited_wprg_gallery', 'wprg_save_gallery_fields');
function wprg_save_gallery_fields($term_id) {
    $fields = [
        'wprg_carousel_limit', 
        'wprg_desktop_items', 
        'wprg_tablet_items', 
        'wprg_mobile_items',
        'wprg_gap', 
        'wprg_autoplay_speed', 
        'wprg_animation_speed'
    ];
    
    // Sauvegarder les champs numériques
    foreach ($fields as $field) {
        if (isset($_POST[$field])) {
            update_term_meta($term_id, $field, sanitize_text_field($_POST[$field]));
        }
    }
    
    // Sauvegarder les checkboxes - IMPORTANT: gérer le cas où la checkbox n'est pas cochée
    $checkbox_fields = [
        'wprg_autoplay',
        'wprg_pause_hover', 
        'wprg_loop', 
        'wprg_show_arrows', 
        'wprg_show_dots', 
        'wprg_drag_scroll'
        // wprg_infinite a été supprimé - on utilise loop à la place
    ];
    
    foreach ($checkbox_fields as $field) {
        $value = isset($_POST[$field]) ? 1 : 0;
        update_term_meta($term_id, $field, $value);
    }
    
    // Si wprg_infinite existe dans $_POST, on le sauvegarde mais on ne l'utilisera pas
    // Cela permet de conserver les anciennes données sans les perdre
    if (isset($_POST['wprg_infinite'])) {
        update_term_meta($term_id, 'wprg_infinite', 0); // On force à 0 car on utilise loop
    }
}