<?php
// Enregistrer le shortcode
add_shortcode('reels_gallery', 'wprg_reels_gallery_shortcode');
function wprg_reels_gallery_shortcode($atts) {
    $atts = shortcode_atts(array(
        'gallery_id' => 0,
        'limit' => 12
    ), $atts);
    
    if (!$atts['gallery_id']) {
        return '<p style="padding: 20px; background: #f8d7da; color: #721c24; border-radius: 5px;">⚠️ Veuillez spécifier un ID de galerie.</p>';
    }
    
    // Récupérer les paramètres de la galerie
    $term_id = $atts['gallery_id'];
    
    $carousel_limit = get_term_meta($term_id, 'wprg_carousel_limit', true) ?: 12;
    $desktop_items = get_term_meta($term_id, 'wprg_desktop_items', true) ?: 6;
    $tablet_items = get_term_meta($term_id, 'wprg_tablet_items', true) ?: 4;
    $mobile_items = get_term_meta($term_id, 'wprg_mobile_items', true) ?: 2;
    $gap = get_term_meta($term_id, 'wprg_gap', true) ?: 20;
    
    // Récupérer les valeurs des checkboxes avec conversion explicite en int
    $autoplay_meta = get_term_meta($term_id, 'wprg_autoplay', true);
    $autoplay = $autoplay_meta !== '' ? intval($autoplay_meta) : 0;
    
    $autoplay_speed = get_term_meta($term_id, 'wprg_autoplay_speed', true) ?: 3000;
    
    $pause_hover_meta = get_term_meta($term_id, 'wprg_pause_hover', true);
    $pause_hover = $pause_hover_meta !== '' ? intval($pause_hover_meta) : 1;
    
    $loop_meta = get_term_meta($term_id, 'wprg_loop', true);
    $loop = $loop_meta !== '' ? intval($loop_meta) : 1;
    
    $show_arrows_meta = get_term_meta($term_id, 'wprg_show_arrows', true);
    $show_arrows = $show_arrows_meta !== '' ? intval($show_arrows_meta) : 1;
    
    $show_dots_meta = get_term_meta($term_id, 'wprg_show_dots', true);
    $show_dots = $show_dots_meta !== '' ? intval($show_dots_meta) : 1;
    
    $animation_speed = get_term_meta($term_id, 'wprg_animation_speed', true) ?: 300;
    
    $drag_scroll_meta = get_term_meta($term_id, 'wprg_drag_scroll', true);
    $drag_scroll = $drag_scroll_meta !== '' ? intval($drag_scroll_meta) : 1;
    
    // On ignore wprg_infinite et on utilise loop à la place
    $infinite = $loop; // Pour la compatibilité avec le JS, on utilise la valeur de loop
    
    // Récupérer les reels de la galerie
    $args = array(
        'post_type' => 'wprg_reel',
        'posts_per_page' => $carousel_limit,
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'DESC',
        'tax_query' => array(
            array(
                'taxonomy' => 'wprg_gallery',
                'field' => 'term_id',
                'terms' => $term_id
            )
        )
    );
    
    $reels_query = new WP_Query($args);
    
    if (!$reels_query->have_posts()) {
        return '<p style="padding: 20px; background: #fff3cd; color: #856404; border-radius: 5px;">📭 Aucun reel trouvé dans cette galerie.</p>';
    }
    
    $total_posts = $reels_query->post_count;
    
    ob_start();
    ?>
    <div class="wprg-carousel-container" 
         data-desktop="<?php echo esc_attr($desktop_items); ?>"
         data-tablet="<?php echo esc_attr($tablet_items); ?>"
         data-mobile="<?php echo esc_attr($mobile_items); ?>"
         data-gap="<?php echo esc_attr($gap); ?>"
         data-autoplay="<?php echo esc_attr($autoplay); ?>"
         data-autoplay-speed="<?php echo esc_attr($autoplay_speed); ?>"
         data-pause-hover="<?php echo esc_attr($pause_hover); ?>"
         data-loop="<?php echo esc_attr($loop); ?>"
         data-show-arrows="<?php echo esc_attr($show_arrows); ?>"
         data-show-dots="<?php echo esc_attr($show_dots); ?>"
         data-animation-speed="<?php echo esc_attr($animation_speed); ?>"
         data-drag-scroll="<?php echo esc_attr($drag_scroll); ?>"
         data-infinite="<?php echo esc_attr($infinite); ?>"
         data-total="<?php echo esc_attr($total_posts); ?>">
        
        <div class="wprg-carousel">
            <?php 
            $counter = 0;
            while ($reels_query->have_posts()) : $reels_query->the_post(); 
                $counter++;
                $post_id = get_the_ID();
                $video_type = get_post_meta($post_id, '_wprg_video_type', true);
                $video_url = get_post_meta($post_id, '_wprg_video_url', true);
                $video_upload = get_post_meta($post_id, '_wprg_video_upload', true);
                
                // Récupérer l'image mise en avant
                $thumbnail_id = get_post_thumbnail_id($post_id);
                
                if ($thumbnail_id) {
                    $thumbnail = wp_get_attachment_image_url($thumbnail_id, 'large');
                    if (!$thumbnail) {
                        $thumbnail = wp_get_attachment_image_url($thumbnail_id, 'full');
                    }
                } else {
                    if ($video_type == 'youtube' && $video_url) {
                        $youtube_id = wprg_get_youtube_id($video_url);
                        $thumbnail = 'https://img.youtube.com/vi/' . $youtube_id . '/maxresdefault.jpg';
                    } else {
                        $thumbnail = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="400" height="700" viewBox="0 0 400 700"><rect width="400" height="700" fill="%23f0f0f0"/><text x="50%" y="50%" font-family="Arial" font-size="24" fill="%23999" text-anchor="middle" dy=".3em">Reel</text></svg>';
                    }
                }
                
                // Récupérer le nombre de likes
                $likes = get_post_meta($post_id, '_wprg_likes', true) ?: 0;
                $formatted_likes = wprg_get_formatted_likes($post_id);
                
                // Récupérer le nombre de vues
                $views = get_post_meta($post_id, '_wprg_views', true) ?: 0;
                $formatted_views = wprg_get_formatted_views($post_id);
            ?>
                <div class="wprg-carousel-item"
     data-post-id="<?php echo $post_id; ?>"
     data-index="<?php echo $counter; ?>"
     data-likes="<?php echo esc_attr($likes); ?>">
                    <div class="wprg-carousel-thumbnail">
                        <img src="<?php echo esc_url($thumbnail); ?>" alt="<?php the_title_attribute(); ?>" loading="lazy">
                        
                        <!-- Badge de likes sur la miniature - EN HAUT À DROITE -->
                        <div class="wprg-thumbnail-likes" data-post-id="<?php echo $post_id; ?>">
                            <span class="wprg-likes-icon">❤️</span>
                            <span class="wprg-likes-count"><?php echo esc_html($formatted_likes); ?></span>
                        </div>
                        
                        <!-- Badge de vues sur la miniature - EN HAUT À GAUCHE -->
                        <div class="wprg-thumbnail-views" data-post-id="<?php echo $post_id; ?>">
                            <span class="wprg-views-icon">👁️</span>
                            <span class="wprg-views-count"><?php echo esc_html($formatted_views); ?></span>
                        </div>
                        
                        <div class="wprg-carousel-play">
                            <svg viewBox="0 0 24 24" width="48" height="48">
                                <circle cx="12" cy="12" r="10" fill="rgba(0,0,0,0.6)"/>
                                <polygon points="10,8 16,12 10,16" fill="white"/>
                            </svg>
                        </div>
                        
                        <!-- Titre de la vidéo - EN BAS -->
                        <div class="wprg-carousel-title"><?php the_title(); ?></div>
                    </div>
                    
                    <!-- Données cachées pour le popup -->
                    <div class="wprg-reel-data" style="display: none;">
                        <div class="wprg-video-title"><?php the_title(); ?></div>
                        <div class="wprg-video-type"><?php echo esc_attr($video_type); ?></div>
                        <div class="wprg-video-source">
                            <?php 
                            if ($video_type == 'youtube' && $video_url) {
                                $youtube_id = wprg_get_youtube_id($video_url);
                                echo esc_url('https://www.youtube.com/embed/' . $youtube_id . '?autoplay=1&mute=1&rel=0&showinfo=0');
                            } else if ($video_type == 'upload' && $video_upload) {
                                echo wp_get_attachment_url($video_upload);
                            }
                            ?>
                        </div>
                        <div class="wprg-video-likes"><?php echo esc_attr($likes); ?></div>
                        <div class="wprg-video-likes-formatted"><?php echo esc_attr($formatted_likes); ?></div>
                        <div class="wprg-video-views"><?php echo esc_attr($views); ?></div>
                        <div class="wprg-video-views-formatted"><?php echo esc_attr($formatted_views); ?></div>
                    </div>
                </div>
            <?php endwhile; wp_reset_postdata(); ?>
        </div>
        
        <!-- Boutons de navigation -->
        <?php if ($show_arrows): ?>
        <button class="wprg-carousel-prev" aria-label="Précédent">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="15 18 9 12 15 6"></polyline>
            </svg>
        </button>
        <button class="wprg-carousel-next" aria-label="Suivant">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="9 18 15 12 9 6"></polyline>
            </svg>
        </button>
        <?php endif; ?>
        
        <!-- Indicateurs -->
        <?php if ($show_dots): ?>
        <div class="wprg-carousel-dots"></div>
        <?php endif; ?>
    </div>

    <!-- Popup avec bouton de likes -->
    <div id="wprg-popup" class="wprg-popup">
        <div class="wprg-popup-overlay"></div>
        <div class="wprg-popup-content">
            <div class="wprg-popup-player-container">
                <div class="wprg-popup-video-container">
                    <button class="wprg-popup-close">&times;</button>
                    <div class="wprg-popup-video"></div>
                </div>
                
                <!-- Barre de likes sous le lecteur -->
                <div class="wprg-popup-likes-bar">
                    <button class="wprg-like-button" id="wprg-like-btn">
                        <span class="wprg-like-icon">❤️</span>
                        <span class="wprg-like-text">J'aime</span>
                        <span class="wprg-like-count">0</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <?php
    return ob_get_clean();
}

// Ajouter colonne shortcode dans l'admin
add_filter('manage_edit-wprg_gallery_columns', 'wprg_gallery_columns');
function wprg_gallery_columns($columns) {
    $columns['shortcode'] = 'Shortcode';
    $columns['reels_count'] = 'Nombre de reels';
    $columns['carousel_settings'] = '⚙️ Paramètres';
    return $columns;
}

add_action('manage_wprg_gallery_custom_column', 'wprg_gallery_column_content', 10, 3);
function wprg_gallery_column_content($content, $column_name, $term_id) {
    if ($column_name == 'shortcode') {
        $shortcode = '[reels_gallery gallery_id="' . $term_id . '"]';
        echo '<input type="text" value="' . esc_attr($shortcode) . '" readonly onclick="this.select()" style="width:100%; padding: 3px; background: #f0f0f1; border: 1px solid #ccc;">';
    }
    
    if ($column_name == 'reels_count') {
        $reels = get_posts(array(
            'post_type' => 'wprg_reel',
            'numberposts' => -1,
            'fields' => 'ids',
            'tax_query' => array(
                array(
                    'taxonomy' => 'wprg_gallery',
                    'field' => 'term_id',
                    'terms' => $term_id
                )
            )
        ));
        echo count($reels);
    }
    
    if ($column_name == 'carousel_settings') {
        $desktop = get_term_meta($term_id, 'wprg_desktop_items', true) ?: 6;
        $autoplay = get_term_meta($term_id, 'wprg_autoplay', true);
        $autoplay = $autoplay !== '' ? intval($autoplay) : 0;
        $loop = get_term_meta($term_id, 'wprg_loop', true);
        $loop = $loop !== '' ? intval($loop) : 1;
        $show_arrows = get_term_meta($term_id, 'wprg_show_arrows', true);
        $show_arrows = $show_arrows !== '' ? intval($show_arrows) : 1;
        $show_dots = get_term_meta($term_id, 'wprg_show_dots', true);
        $show_dots = $show_dots !== '' ? intval($show_dots) : 1;
        
        echo '<span style="display:inline-block; padding:3px 8px; background:#e3f2fd; border-radius:12px; font-size:11px;">📱 ' . $desktop . ' items</span> ';
        echo $autoplay ? '<span style="display:inline-block; padding:3px 8px; background:#e8f5e8; border-radius:12px; font-size:11px;">▶️ Auto</span> ' : '';
        echo $loop ? '<span style="display:inline-block; padding:3px 8px; background:#fff3e0; border-radius:12px; font-size:11px;">🔄 Loop</span>' : '';
        
        if (!$show_arrows) {
            echo ' <span style="display:inline-block; padding:3px 8px; background:#ffebee; border-radius:12px; font-size:11px;">🚫 Flèches</span>';
        }
        
        if (!$show_dots) {
            echo ' <span style="display:inline-block; padding:3px 8px; background:#ffebee; border-radius:12px; font-size:11px;">🚫 Dots</span>';
        }
    }
}