<?php

/**
 * Guides Custom Post Type
 * Laurent-Perrier Theme
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Register Guides Custom Post Type
 */
function lp_register_guides_post_type()
{
    // Obtenir le slug de base des guides via WPML (traduction par langue)
    $guides_base_slug = 'laurent-perrier-guides';
    if (function_exists('icl_t')) {
        $guides_base_slug = icl_t('laurentperrier', 'Guide URL Slug', $guides_base_slug);
    }

    $labels = array(
        'name'                  => _x('Guides', 'CPT general name', 'laurentperrier'),
        'singular_name'         => _x('Guide', 'Post type singular name', 'laurentperrier'),
        'menu_name'             => _x('Guides', 'Admin Menu text', 'laurentperrier'),
        'name_admin_bar'        => _x('Guide', 'Add New on Toolbar', 'laurentperrier'),
        'add_new'               => __('Ajouter', 'laurentperrier'),
        'add_new_item'          => __('Ajouter un Guide', 'laurentperrier'),
        'new_item'              => __('Nouveau Guide', 'laurentperrier'),
        'edit_item'             => __('Éditer le Guide', 'laurentperrier'),
        'view_item'             => __('Voir le Guide', 'laurentperrier'),
        'view_items'            => __('Voir les Guides', 'laurentperrier'),
        'all_items'             => __('Tous les Guides', 'laurentperrier'),
        'search_items'          => __('Rechercher un Guide', 'laurentperrier'),
        'parent_item_colon'     => __('Guide parent:', 'laurentperrier'),
        'not_found'             => __('Aucun guide trouvé', 'laurentperrier'),
        'not_found_in_trash'    => __('Aucun guide trouvé dans la corbeille', 'laurentperrier'),
        'featured_image'        => _x('Image du Guide', 'Overrides the "Featured Image" phrase', 'laurentperrier'),
        'set_featured_image'    => _x('Définir l\'image du guide', 'Overrides the "Set featured image" phrase', 'laurentperrier'),
        'remove_featured_image' => _x('Supprimer l\'image du guide', 'Overrides the "Remove featured image" phrase', 'laurentperrier'),
        'use_featured_image'    => _x('Utiliser comme image du guide', 'Overrides the "Use as featured image" phrase', 'laurentperrier'),
        'archives'              => _x('Archives des Guides', 'The post type archive label', 'laurentperrier'),
        'insert_into_item'      => _x('Insérer dans le guide', 'Overrides the "Insert into post" phrase', 'laurentperrier'),
        'uploaded_to_this_item' => _x('Téléchargé vers ce guide', 'Overrides the "Uploaded to this post" phrase', 'laurentperrier'),
        'filter_items_list'     => _x('Filtrer la liste des guides', 'Screen reader text for the filter links', 'laurentperrier'),
        'items_list_navigation' => _x('Navigation de la liste des guides', 'Screen reader text for the pagination', 'laurentperrier'),
        'items_list'            => _x('Liste des guides', 'Screen reader text for the items list', 'laurentperrier'),
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'show_in_nav_menus'  => true,
        'show_in_admin_bar'  => true,
        'show_in_rest'       => true, // Enable Gutenberg editor
        'query_var'          => true,
        'rewrite'            => array(
            // Utiliser le slug traduit pour la langue courante
            'slug' => $guides_base_slug,
            'with_front' => false,
            'pages' => true,
            'feeds' => true,
        ),
        // Activer l'archive en utilisant le slug traduit
        'has_archive'        => $guides_base_slug,
        'hierarchical'       => false,
        'menu_position'      => 9, // Position in admin menu (after Posts)
        'menu_icon'          => 'dashicons-universal-access
', // Admin menu icon
        'supports'           => array(
            'title',
            'editor',
            'excerpt',
            'thumbnail',
            'custom-fields',
            'page-attributes', // For menu order
            'revisions',
            'author'
        ),
        'taxonomies'         => array(), // Add taxonomies if needed later
        'can_export'         => true,
        'delete_with_user'   => false,
    );

    register_post_type('guide', $args);
}

// Hook into the 'init' action
add_action('init', 'lp_register_guides_post_type');

/**
 * Charger les traductions du thème
 */
function lp_load_theme_textdomain()
{
    load_theme_textdomain('laurentperrier', get_template_directory() . '/languages');
}
add_action('after_setup_theme', 'lp_load_theme_textdomain');

/**
 * Enregistrer les strings pour WPML String Translation
 */
function lp_register_wpml_strings()
{
    if (function_exists('icl_register_string')) {
        // Enregistrer le slug des guides pour traduction
        icl_register_string('laurentperrier', 'Guide URL Slug', 'laurent-perrier-guides');
        // Enregistrer le slug des catégories de guides pour traduction (même que les guides)
        icl_register_string('laurentperrier', 'Guide Category URL Slug', 'laurent-perrier-guides');
    }
}
add_action('init', 'lp_register_wpml_strings');

/**
 * Obtenir le slug traduit selon la langue courante
 */
function lp_get_translated_guides_slug($lang_code = null)
{
    // Si aucune langue spécifiée, utiliser la langue courante
    if (!$lang_code) {
        $lang_code = function_exists('icl_get_current_language') ? icl_get_current_language() : 'en';
    }

    $default = 'laurent-perrier-guides';

    // 1) Base de données (plus fiable que le filtre selon configuration WPML)
    global $wpdb;
    if ($wpdb) {
        $string_id = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}icl_strings WHERE context = %s AND name = %s",
            'laurentperrier',
            'Guide Category URL Slug'
        ));
        if ($string_id) {
            $translation = $wpdb->get_var($wpdb->prepare(
                "SELECT value FROM {$wpdb->prefix}icl_string_translations WHERE string_id = %d AND language = %s ORDER BY status DESC LIMIT 1",
                (int)$string_id,
                $lang_code
            ));
            if (!empty($translation)) {
                return $translation;
            }
        }
    }

    // 2) Filtre WPML
    if (function_exists('apply_filters')) {
        $filtered = apply_filters('wpml_translate_single_string', $default, 'laurentperrier', 'Guide Category URL Slug', $lang_code);
        if (!empty($filtered)) {
            return $filtered;
        }
    }

    // 3) Fallback icl_t
    if (function_exists('icl_t')) {
        $translated = icl_t('laurentperrier', 'Guide Category URL Slug', $default);
        if (!empty($translated)) {
            return $translated;
        }
    }

    // 4) Fallback final
    return $default;
}

/**
 * Add custom columns to Guides admin list
 */
function lp_guides_custom_columns($columns)
{
    // Remove date column and add it back at the end
    $date = isset($columns['date']) ? $columns['date'] : '';
    if (isset($columns['date'])) {
        unset($columns['date']);
    }

    // Add custom columns
    $columns['featured_image'] = __('Image', 'laurentperrier');
    if (!empty($date)) {
        $columns['date'] = $date;
    }

    return $columns;
}
add_filter('manage_guides_posts_columns', 'lp_guides_custom_columns');

/**
 * Display custom column content
 */
function lp_guides_custom_column_content($column, $post_id)
{
    switch ($column) {
        case 'featured_image':
            $thumbnail = get_the_post_thumbnail($post_id, array(50, 50));
            if ($thumbnail) {
                echo $thumbnail;
            } else {
                echo '<span class="dashicons dashicons-format-image" style="color: #ccc; font-size: 30px;"></span>';
            }
            break;
    }
}
add_action('manage_guides_posts_custom_column', 'lp_guides_custom_column_content', 10, 2);

/**
 * Make custom columns sortable (optional)
 */
function lp_guides_sortable_columns($columns)
{
    $columns['featured_image'] = 'featured_image';
    return $columns;
}
add_filter('manage_edit-guides_sortable_columns', 'lp_guides_sortable_columns');

/**
 * Register Custom Taxonomies for Guides
 */
function lp_register_guide_taxonomies()
{
    // Guide Categories
    $category_labels = array(
        'name'                       => _x('Guide Categories', 'Taxonomy General Name', 'laurentperrier'),
        'singular_name'              => _x('Guide Category', 'Taxonomy Singular Name', 'laurentperrier'),
        'menu_name'                  => __('Categories', 'laurentperrier'),
        'all_items'                  => __('All Categories', 'laurentperrier'),
        'parent_item'                => __('Parent Category', 'laurentperrier'),
        'parent_item_colon'          => __('Parent Category:', 'laurentperrier'),
        'new_item_name'              => __('New Category Name', 'laurentperrier'),
        'add_new_item'               => __('Add New Category', 'laurentperrier'),
        'edit_item'                  => __('Edit Category', 'laurentperrier'),
        'update_item'                => __('Update Category', 'laurentperrier'),
        'view_item'                  => __('View Category', 'laurentperrier'),
        'separate_items_with_commas' => __('Separate categories with commas', 'laurentperrier'),
        'add_or_remove_items'        => __('Add or remove categories', 'laurentperrier'),
        'choose_from_most_used'      => __('Choose from the most used', 'laurentperrier'),
        'popular_items'              => __('Popular Categories', 'laurentperrier'),
        'search_items'               => __('Search Categories', 'laurentperrier'),
        'not_found'                  => __('Not Found', 'laurentperrier'),
        'no_terms'                   => __('No categories', 'laurentperrier'),
        'items_list'                 => __('Categories list', 'laurentperrier'),
        'items_list_navigation'      => __('Categories list navigation', 'laurentperrier'),
    );

    $category_args = array(
        'labels'                     => $category_labels,
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => true,
        'show_tagcloud'              => true,
        'show_in_rest'               => true,
        'rewrite'                    => array(
            'slug' => function_exists('icl_t') ? icl_t('laurentperrier', 'Guide Category URL Slug', 'laurent-perrier-guides') : 'laurent-perrier-guides',
            'with_front' => false,
        ),
    );

    register_taxonomy('guide_category', array('guide'), $category_args);
}

// Hook into the 'init' action
add_action('init', 'lp_register_guide_taxonomies', 0);

/**
 * Add taxonomy columns to admin list
 */
function lp_add_guide_taxonomy_columns($columns)
{
    // Add category and tag columns after title
    $new_columns = array();
    foreach ($columns as $key => $value) {
        $new_columns[$key] = $value;
        if ($key === 'title') {
            $new_columns['guide_category'] = __('Categories', 'laurentperrier');
        }
    }
    return $new_columns;
}
add_filter('manage_guide_posts_columns', 'lp_add_guide_taxonomy_columns');

/**
 * Display taxonomy content in admin columns
 */
function lp_display_guide_taxonomy_columns($column, $post_id)
{
    switch ($column) {
        case 'guide_category':
            $categories = get_the_terms($post_id, 'guide_category');
            if ($categories && !is_wp_error($categories)) {
                $category_names = array();
                foreach ($categories as $category) {
                    $category_names[] = '<a href="' . admin_url('edit.php?post_type=guide&guide_category=' . $category->slug) . '">' . $category->name . '</a>';
                }
                echo implode(', ', $category_names);
            } else {
                echo '—';
            }
            break;
    }
}
add_action('manage_guide_posts_custom_column', 'lp_display_guide_taxonomy_columns', 10, 2);

/**
 * Make taxonomy columns sortable
 */
function lp_make_guide_taxonomy_columns_sortable($columns)
{
    $columns['guide_category'] = 'guide_category';
    return $columns;
}
add_filter('manage_edit-guide_sortable_columns', 'lp_make_guide_taxonomy_columns_sortable');

/**
 * Add taxonomy filters to admin list
 */
function lp_add_guide_taxonomy_filters()
{
    global $typenow;

    if ($typenow == 'guide') {
        // Category filter
        $selected_category = isset($_GET['guide_category']) ? $_GET['guide_category'] : '';
        $categories = get_terms('guide_category');
        if ($categories) {
            echo '<select name="guide_category" id="guide_category" class="postform">';
            echo '<option value="">' . __('All Categories', 'laurentperrier') . '</option>';
            foreach ($categories as $category) {
                printf(
                    '<option value="%s"%s>%s (%s)</option>',
                    $category->slug,
                    selected($selected_category, $category->slug, false),
                    $category->name,
                    $category->count
                );
            }
            echo '</select>';
        }
    }
}
add_action('restrict_manage_posts', 'lp_add_guide_taxonomy_filters');

/**
 * Filter posts by taxonomy in admin
 */
function lp_filter_guides_by_taxonomy($query)
{
    global $pagenow;

    if ($pagenow == 'edit.php' && isset($_GET['post_type']) && $_GET['post_type'] == 'guide' && $query->is_admin && $query->is_main_query()) {
        if (isset($_GET['guide_category']) && $_GET['guide_category'] != '') {
            $query->set('tax_query', array(
                array(
                    'taxonomy' => 'guide_category',
                    'field'    => 'slug',
                    'terms'    => $_GET['guide_category']
                )
            ));
        }
    }
}
add_action('pre_get_posts', 'lp_filter_guides_by_taxonomy');


add_filter('wpseo_schema_article_type', function ($type, $context) {
    if ($context->post && $context->post->post_type === 'guide') {
        return 'NewsArticle'; // ✅ Forcer le type schema
    }
    return $type;
}, 10, 2);

/**
 * Gestion des permaliens hiérarchiques pour les guides
 */
function lp_guide_permalink_structure($post_link, $post)
{
    if ($post->post_type !== 'guide') {
        return $post_link;
    }

    // Récupérer les catégories du guide
    $terms = wp_get_object_terms($post->ID, 'guide_category');

    // Déterminer la langue du post
    $post_lang_details = function_exists('apply_filters') ? apply_filters('wpml_post_language_details', null, $post->ID) : null;
    $post_lang_code = (is_array($post_lang_details) && !empty($post_lang_details['language_code'])) ? $post_lang_details['language_code'] : (function_exists('icl_get_current_language') ? icl_get_current_language() : null);

    if (empty($terms) || is_wp_error($terms)) {
        // Si pas de catégorie, utiliser la structure simple
        $guides_slug = lp_get_translated_guides_slug($post_lang_code ?: 'en');
        $url = home_url('/' . $guides_slug . '/' . $post->post_name . '/');
        if (function_exists('apply_filters')) {
            $url = apply_filters('wpml_permalink', $url, $post_lang_code);
        }
        return $url;
    }

    // Construire la hiérarchie des catégories
    $category_hierarchy = array();

    foreach ($terms as $term) {
        $ancestors = get_ancestors($term->term_id, 'guide_category');
        $ancestors = array_reverse($ancestors);
        $ancestors[] = $term->term_id;

        $category_path = array();
        foreach ($ancestors as $ancestor_id) {
            $ancestor_term = get_term($ancestor_id, 'guide_category');
            if ($ancestor_term && !is_wp_error($ancestor_term)) {
                $category_path[] = $ancestor_term->slug;
            }
        }

        if (!empty($category_path)) {
            $category_hierarchy = $category_path;
            break; // Utiliser la première catégorie trouvée
        }
    }

    if (empty($category_hierarchy)) {
        $guides_slug = lp_get_translated_guides_slug($post_lang_code ?: 'en');
        $url = home_url('/' . $guides_slug . '/' . $post->post_name . '/');
        if (function_exists('apply_filters')) {
            $url = apply_filters('wpml_permalink', $url, $post_lang_code);
        }
        return $url;
    }

    // Construire le chemin complet des catégories
    $category_path = implode('/', $category_hierarchy);
    $guides_slug = lp_get_translated_guides_slug($post_lang_code ?: 'en');

    $url = home_url('/' . $guides_slug . '/' . $category_path . '/' . $post->post_name . '/');
    if (function_exists('apply_filters')) {
        $url = apply_filters('wpml_permalink', $url, $post_lang_code);
    }
    return $url;
}
add_filter('post_type_link', 'lp_guide_permalink_structure', 10, 2);

/**
 * Corriger les liens des catégories de guides pour respecter la hiérarchie
 */
function lp_guide_category_link($termlink, $term, $taxonomy)
{
    if ($taxonomy !== 'guide_category') {
        return $termlink;
    }

    // Obtenir le slug des catégories de guides (localisé)
    $guides_slug = lp_get_translated_guides_slug();

    // Construire le chemin hiérarchique
    $hierarchy = array();
    $current_term = $term;

    while ($current_term) {
        array_unshift($hierarchy, $current_term->slug);
        if ($current_term->parent) {
            $current_term = get_term($current_term->parent, 'guide_category');
        } else {
            break;
        }
    }

    $hierarchy_path = implode('/', $hierarchy);
    $url = home_url('/' . $guides_slug . '/' . $hierarchy_path . '/');
    if (function_exists('apply_filters')) {
        $lang_code = function_exists('icl_get_current_language') ? icl_get_current_language() : null;
        $url = apply_filters('wpml_permalink', $url, $lang_code);
    }
    return $url;
}
add_filter('term_link', 'lp_guide_category_link', 10, 3);

/**
 * Ajouter les règles de réécriture pour les URLs hiérarchiques
 */
function lp_guide_rewrite_rules()
{
    if (!function_exists('add_rewrite_rule')) {
        return;
    }

    // Récupérer tous les slugs traduits depuis WPML
    $all_slugs = array();
    $all_slugs[] = 'laurent-perrier-guides';

    $languages = apply_filters('wpml_active_languages', null, 'skip_missing=0');
    if (!empty($languages)) {
        foreach ($languages as $lang_code => $lang_info) {
            $translated_cat_base = lp_get_translated_guides_slug($lang_code);
            if (!empty($translated_cat_base) && !in_array($translated_cat_base, $all_slugs)) {
                $all_slugs[] = $translated_cat_base;
            }

            $translated_cpt_base = apply_filters('wpml_translate_single_string', 'laurent-perrier-guides', 'laurentperrier', 'Guide URL Slug', $lang_code);
            if (!empty($translated_cpt_base) && !in_array($translated_cpt_base, $all_slugs)) {
                $all_slugs[] = $translated_cpt_base;
            }
        }
    }

    $all_slugs = array_filter(array_unique($all_slugs));

    foreach ($all_slugs as $guides_slug) {
        add_rewrite_rule(
            '^' . $guides_slug . '/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$',
            'index.php?post_type=guide&name=$matches[5]',
            'top'
        );

        add_rewrite_rule(
            '^' . $guides_slug . '/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$',
            'index.php?post_type=guide&name=$matches[4]',
            'top'
        );

        add_rewrite_rule(
            '^' . $guides_slug . '/([^/]+)/([^/]+)/([^/]+)/?$',
            'index.php?guide_category=$matches[1]&guide_subcategory=$matches[2]&guide=$matches[3]',
            'top'
        );

        add_rewrite_rule(
            '^' . $guides_slug . '/([^/]+)/([^/]+)/?$',
            'index.php?guide_category=$matches[1]&guide_or_subcategory=$matches[2]',
            'top'
        );

        add_rewrite_rule(
            '^' . $guides_slug . '/([^/]+)/?$',
            'index.php?guide_or_category=$matches[1]',
            'top'
        );
    }
}

add_action('init', 'lp_guide_rewrite_rules', 20);

/**
 * Parser personnalisé pour déterminer si c'est un guide ou une catégorie
 */
function lp_guide_request_parser($wp)
{
    // Cas 1
    if (isset($wp->query_vars['guide_category']) && isset($wp->query_vars['guide_subcategory']) && isset($wp->query_vars['guide'])) {
        $guide_slug = $wp->query_vars['guide'];
        $guide = get_page_by_path($guide_slug, OBJECT, 'guide');
        if ($guide && !is_wp_error($guide)) {
            $wp->query_vars['post_type'] = 'guide';
            $wp->query_vars['name'] = $guide_slug;
            unset($wp->query_vars['guide']);
            unset($wp->query_vars['guide_subcategory']);
            lp_guides_debug_log('Parser: Cas 1 → guide (' . $guide_slug . ')');
            return;
        } else {
            $term = get_term_by('slug', $guide_slug, 'guide_category');
            if ($term && !is_wp_error($term)) {
                $wp->query_vars['guide_category'] = $guide_slug;
                unset($wp->query_vars['guide']);
                unset($wp->query_vars['guide_subcategory']);
                lp_guides_debug_log('Parser: Cas 1 → catégorie (' . $guide_slug . ')');
                return;
            }
        }
    }

    // Cas 2
    if (isset($wp->query_vars['guide_category']) && isset($wp->query_vars['guide_or_subcategory'])) {
        $category_slug = $wp->query_vars['guide_category'];
        $item_slug = $wp->query_vars['guide_or_subcategory'];

        $term = get_term_by('slug', $item_slug, 'guide_category');
        if ($term && !is_wp_error($term)) {
            $parent_term = get_term_by('slug', $category_slug, 'guide_category');
            // Si c'est bien une sous-catégorie du parent attendu OU simplement une catégorie valide,
            // on traite l'URL comme une archive de cette catégorie.
            if (($parent_term && (int)$term->parent === (int)$parent_term->term_id) || $term) {
                $wp->query_vars['guide_category'] = $item_slug;
                unset($wp->query_vars['guide_or_subcategory']);
                lp_guides_debug_log('Parser: Cas 2 → sous-catégorie (' . $category_slug . ' / ' . $item_slug . ')');
                return;
            }
        }

        $guide = get_page_by_path($item_slug, OBJECT, 'guide');
        if ($guide && !is_wp_error($guide)) {
            $wp->query_vars['post_type'] = 'guide';
            $wp->query_vars['name'] = $item_slug;
            unset($wp->query_vars['guide_or_subcategory']);
            lp_guides_debug_log('Parser: Cas 2 → guide (' . $item_slug . ')');
            return;
        }
    }

    // Cas 2.5: un seul segment après la base (peut être un guide ou une catégorie de premier niveau)
    if (isset($wp->query_vars['guide_or_category'])) {
        $slug = $wp->query_vars['guide_or_category'];

        // Tenter d'abord comme un guide
        $guide = get_page_by_path($slug, OBJECT, 'guide');
        if ($guide && !is_wp_error($guide)) {
            $wp->query_vars['post_type'] = 'guide';
            $wp->query_vars['name'] = $slug;
            unset($wp->query_vars['guide_or_category']);
            lp_guides_debug_log('Parser: Cas 2.5 → guide (' . $slug . ')');
            return;
        }

        // Sinon, tenter comme une catégorie
        $term = get_term_by('slug', $slug, 'guide_category');
        if ($term && !is_wp_error($term)) {
            $wp->query_vars['guide_category'] = $slug;
            unset($wp->query_vars['guide_or_category']);
            lp_guides_debug_log('Parser: Cas 2.5 → catégorie (' . $slug . ')');
            return;
        }
    }

    // Cas 3
    if (isset($wp->query_vars['guide_category']) && !isset($wp->query_vars['guide_or_subcategory']) && !isset($wp->query_vars['guide']) && !isset($wp->query_vars['guide_subcategory'])) {
        $slug = $wp->query_vars['guide_category'];
        $term = get_term_by('slug', $slug, 'guide_category');
        if ($term && !is_wp_error($term)) {
            lp_guides_debug_log('Parser: Cas 3 → catégorie (' . $slug . ')');
            return;
        }
    }
}
add_action('parse_request', 'lp_guide_request_parser');

/**
 * Canonical redirects for Guides and Guide Categories
 * Ensures that any non-canonical URL pattern is redirected to the canonical one (WPML-aware).
 */
function lp_guides_canonical_redirect()
{
    // Only apply on GET requests without POST data to avoid interfering with submissions
    if (strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'GET') {
        return;
    }

    // Build current full URL
    $scheme   = is_ssl() ? 'https' : 'http';
    $host     = $_SERVER['HTTP_HOST'] ?? '';
    $request  = $_SERVER['REQUEST_URI'] ?? '';
    if (!$host || !$request) {
        return;
    }
    $current_url = $scheme . '://' . $host . $request;

    // Normalize function
    $normalize = function ($url) {
        // Keep query string as-is; compare without trailing slashes quirks
        $parts = wp_parse_url($url);
        if (!$parts) return rtrim($url, "/");
        $path = isset($parts['path']) ? rtrim($parts['path'], '/') : '';
        $qs   = isset($parts['query']) ? '?' . $parts['query'] : '';
        $scheme = $parts['scheme'] ?? (is_ssl() ? 'https' : 'http');
        $host = $parts['host'] ?? '';
        $port = isset($parts['port']) ? ':' . $parts['port'] : '';
        return strtolower($scheme . '://' . $host . $port . $path . $qs);
    };

    // Single Guide canonical
    if (is_singular('guide')) {
        $canonical = get_permalink(); // already filtered by our permalink filters and WPML
        if ($canonical) {
            if ($normalize($current_url) !== $normalize($canonical)) {
                wp_safe_redirect($canonical, 301);
                exit;
            }
        }
        return;
    }

    // Taxonomy canonical for guide_category
    if (is_tax('guide_category')) {
        $term = get_queried_object();
        if ($term && !is_wp_error($term)) {
            $canonical = get_term_link($term);
            if (!is_wp_error($canonical) && $canonical) {
                if ($normalize($current_url) !== $normalize($canonical)) {
                    wp_safe_redirect($canonical, 301);
                    exit;
                }
            }
        }
        return;
    }
}
add_action('template_redirect', 'lp_guides_canonical_redirect', 1);

/**
 * Debug helpers (disabled by default)
 */
function lp_guides_debug_enabled()
{
    // Debug mode disabled globally
    return false;
}

function lp_guides_debug_log($message)
{
    static $log = null;
    if (!lp_guides_debug_enabled()) return;
    if ($log === null) {
        $log = array();
        // Store reference in global so other functions can read it in footer
        $GLOBALS['lp_guides_debug_log'] = &$log;
        // Ensure footer output is hooked once
        add_action('wp_footer', 'lp_guides_debug_render_panel', 1000);
    }
    $log[] = '[' . date_i18n('H:i:s') . '] ' . $message;
}

function lp_guides_debug_render_panel()
{
    if (!lp_guides_debug_enabled()) return;
    $log = isset($GLOBALS['lp_guides_debug_log']) && is_array($GLOBALS['lp_guides_debug_log']) ? $GLOBALS['lp_guides_debug_log'] : array();
    if (empty($log)) return;
    echo '<div style="position:fixed;z-index:999999;bottom:0;left:0;right:0;background:#111;color:#eee;font:12px/1.4 monospace;padding:12px 16px;opacity:0.95;box-shadow:0 -2px 8px rgba(0,0,0,.4)">';
    echo '<strong>Guides Debug</strong> (visible uniquement admin, param &lp_guides_debug=1)';
    echo '<ul style="margin:8px 0 0 16px;">';
    foreach ($log as $line) {
        echo '<li>' . esc_html($line) . '</li>';
    }
    echo '</ul></div>';
}

/**
 * Ajouter les query vars personnalisées
 */
function lp_add_guide_query_vars($vars)
{
    $vars[] = 'guide';
    $vars[] = 'guide_subcategory';
    $vars[] = 'guide_or_subcategory';
    $vars[] = 'guide_or_category';
    return $vars;
}
add_filter('query_vars', 'lp_add_guide_query_vars');

/**
 * Forcer le flush des règles de réécriture lors de l'activation du thème
 */
function lp_flush_rewrite_rules_on_theme_activation()
{
    lp_guide_rewrite_rules();
    flush_rewrite_rules();
}
add_action('after_switch_theme', 'lp_flush_rewrite_rules_on_theme_activation');

/**
 * Debug function pour les règles de réécriture (à supprimer en production)
 */
// Debug rewrite rules removed

/**
 * Ajouter les query vars personnalisées
 */
function lp_guide_query_vars($vars)
{
    $vars[] = 'guide_category';
    return $vars;
}
add_filter('query_vars', 'lp_guide_query_vars');

/**
 * Ajouter une classe body pour les pages single de guides (Gutenberg styling)
 */
function lp_guides_add_body_class($classes)
{
    if (is_singular('guide')) {
        $classes[] = 'page-gutenberg';
    }
    return $classes;
}
add_filter('body_class', 'lp_guides_add_body_class');
