<?php

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

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

// Constants to avoid typos and keep slugs centralized
if (!defined('LP_GUIDES_TD')) {
    define('LP_GUIDES_TD', 'laurentperrier');
}
if (!defined('LP_GUIDES_CPT')) {
    define('LP_GUIDES_CPT', 'guide');
}
if (!defined('LP_GUIDES_DEFAULT_SLUG')) {
    define('LP_GUIDES_DEFAULT_SLUG', 'laurent-perrier-guides');
}
// Note: Historically taxonomy base used same default; can be changed per language in WPML
if (!defined('LP_GUIDES_CATEGORY_DEFAULT_SLUG')) {
    define('LP_GUIDES_CATEGORY_DEFAULT_SLUG', 'laurent-perrier-guides');
}
if (!defined('LP_GUIDES_URL_SLUG_KEY')) {
    define('LP_GUIDES_URL_SLUG_KEY', 'Guide URL Slug');
}
if (!defined('LP_GUIDES_CATEGORY_URL_SLUG_KEY')) {
    define('LP_GUIDES_CATEGORY_URL_SLUG_KEY', 'Guide Category URL Slug');
}
// Centralized taxonomy slug for Guide Categories
if (!defined('LP_TAX_GUIDE_CATEGORY')) {
    define('LP_TAX_GUIDE_CATEGORY', 'guide_category');
}

/**
 * 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 = LP_GUIDES_DEFAULT_SLUG;
    if (function_exists('icl_t')) {
        $guides_base_slug = icl_t(LP_GUIDES_TD, LP_GUIDES_URL_SLUG_KEY, $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,
        'capability_type' => [LP_GUIDES_CPT, LP_GUIDES_CPT . 's'],
        'map_meta_cap' => true,
        'capabilities' => [
            'edit_post'           => 'edit_' . LP_GUIDES_CPT,
            'read_post'           => 'read_' . LP_GUIDES_CPT,
            'delete_post'         => 'delete_' . LP_GUIDES_CPT,
            'edit_posts'          => 'edit_' . LP_GUIDES_CPT . 's',
            'create_posts'        => 'edit_' . LP_GUIDES_CPT . 's',
            'edit_others_posts'   => 'edit_others_' . LP_GUIDES_CPT . 's',
            'publish_posts'       => 'publish_' . LP_GUIDES_CPT . 's',
            'read_private_posts'  => 'read_private_' . LP_GUIDES_CPT . 's',
            'delete_posts'        => 'delete_' . LP_GUIDES_CPT . 's',
            'delete_private_posts' => 'delete_private_' . LP_GUIDES_CPT . 's',
            'delete_published_posts' => 'delete_published_' . LP_GUIDES_CPT . 's',
            'delete_others_posts' => 'delete_others_' . LP_GUIDES_CPT . 's',
            'edit_private_posts'  => 'edit_private_' . LP_GUIDES_CPT . 's',
            'edit_published_posts' => 'edit_published_' . LP_GUIDES_CPT . 's',
        ],
        '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(LP_GUIDES_CPT, $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(LP_GUIDES_TD, 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(LP_GUIDES_TD, LP_GUIDES_URL_SLUG_KEY, LP_GUIDES_DEFAULT_SLUG);
        // Enregistrer le slug des catégories de guides pour traduction (peut être différent si souhaité)
        icl_register_string(LP_GUIDES_TD, LP_GUIDES_CATEGORY_URL_SLUG_KEY, LP_GUIDES_CATEGORY_DEFAULT_SLUG);
    }
}
add_action('init', 'lp_register_wpml_strings');

/**
 * 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('lp_get_translated_guides_slug') ? lp_get_translated_guides_slug() : (function_exists('icl_t') ? icl_t('laurentperrier', 'Guide Category URL Slug', 'laurent-perrier-guides') : 'laurent-perrier-guides'),
            'slug' => _x(LP_GUIDES_CATEGORY_DEFAULT_SLUG,  'Guide Category URL Slug', 'laurentperrier'),
            'with_front' => false,
            'hierarchical' => true,
        ),
        'capabilities' => [
            'manage_terms' => 'manage_' . LP_TAX_GUIDE_CATEGORY,
            'edit_terms'   => 'edit_' . LP_TAX_GUIDE_CATEGORY,
            'delete_terms' => 'delete_' . LP_TAX_GUIDE_CATEGORY,
            'assign_terms' => 'assign_' . LP_TAX_GUIDE_CATEGORY,
        ]
    );

    register_taxonomy(LP_TAX_GUIDE_CATEGORY, array(LP_GUIDES_CPT), $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[LP_TAX_GUIDE_CATEGORY]) ? $_GET[LP_TAX_GUIDE_CATEGORY] : '';
        $categories = get_terms(LP_TAX_GUIDE_CATEGORY);
        if ($categories) {
            echo '<select name="' . esc_attr(LP_TAX_GUIDE_CATEGORY) . '" id="' . esc_attr(LP_TAX_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[LP_TAX_GUIDE_CATEGORY]) && $_GET[LP_TAX_GUIDE_CATEGORY] != '') {
            $query->set('tax_query', array(
                array(
                    'taxonomy' => LP_TAX_GUIDE_CATEGORY,
                    'field'    => 'slug',
                    'terms'    => $_GET[LP_TAX_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);


/**
 * Ajouter les règles de réécriture pour les URLs hiérarchiques
 */
function lp_guide_rewrite_rules()
{
    // Base multilingue pour les guides
    $guide_bases = '(guide-and-tips|guide-et-conseils|guide-and-tipps|guida-e-consigli|guia-y-consejos)';

    // Archive des guides
    // ex: /fr/guide-et-conseils/ ou /en/guide-and-tips/
    add_rewrite_rule(
        $guide_bases . '/?$',
        'index.php?post_type=' . LP_GUIDES_CPT . '&lp_guide_archive=1',
        'top'
    );

    // Taxonomie niveau 1
    // ex: /fr/guide-et-conseils/decouvrir-les-champagnes/
    add_rewrite_rule(
        $guide_bases . '/([^/]+)/?$',
        'index.php?post_type=' . LP_GUIDES_CPT . '&' . LP_TAX_GUIDE_CATEGORY . '=$matches[2]',
        'top'
    );

    // Taxonomie niveau 2
    // ex: /fr/guide-et-conseils/decouvrir-les-champagnes/les-cuvees-de-prestige/
    add_rewrite_rule(
        $guide_bases . '/([^/]+)/([^/]+)/?$',
        'index.php?post_type=' . LP_GUIDES_CPT . '&' . LP_TAX_GUIDE_CATEGORY . '=$matches[3]',
        'top'
    );

    // Single guide avec chemin hiérarchique complet
    // ex: /fr/guide-et-conseils/decouvrir-les-champagnes/les-cuvees-de-prestige/qu-est-ce-qu-une-cuvee-de-prestige/
    add_rewrite_rule(
        $guide_bases . '/([^/]+)/([^/]+)/([^/]+)/?$',
        'index.php?post_type=' . LP_GUIDES_CPT . '&name=$matches[4]',
        'top'
    );
}

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




function lp_guide_hierarchical_permalink($permalink, $post)
{
    if (!$post instanceof WP_Post) {
        return $permalink;
    }

    if ($post->post_type !== LP_GUIDES_CPT) {
        return $permalink;
    }

    $terms = get_the_terms($post, LP_TAX_GUIDE_CATEGORY);
    if (empty($terms) || is_wp_error($terms)) {
        return $permalink;
    }

    $term = array_shift($terms);

    $slugs = array();
    if ($term->parent) {
        $ancestors = get_ancestors($term->term_id, LP_TAX_GUIDE_CATEGORY);
        if (!empty($ancestors)) {
            $ancestors = array_reverse($ancestors);
            foreach ($ancestors as $ancestor_id) {
                $ancestor = get_term($ancestor_id, LP_TAX_GUIDE_CATEGORY);
                if ($ancestor && !is_wp_error($ancestor)) {
                    $slugs[] = $ancestor->slug;
                }
            }
        }
    }
    $slugs[] = $term->slug;

    $category_path = implode('/', $slugs);

    // Extraire la base multilingue déjà présente dans l'URL
    $pattern = '#/(guide-and-tips|guide-et-conseils|guide-and-tipps|guida-e-consigli|guia-y-consejos)(/|$)#';
    if (!preg_match($pattern, $permalink, $matches)) {
        return $permalink;
    }

    $base = $matches[1];

    $new_path = $base . '/' . $category_path . '/' . $post->post_name . '/';

    // Construire l'URL finale en respectant la langue courante (WPML)
    $home_url = home_url('/');

    // Si WPML est actif, utiliser son home_url par langue (important quand il
    // génère les permaliens pour chaque traduction, hreflang, etc.)
    if (function_exists('apply_filters') && function_exists('has_filter')) {
        if (has_filter('wpml_current_language') && has_filter('wpml_home_url')) {
            $current_lang = apply_filters('wpml_current_language', null);
            $home_url = apply_filters('wpml_home_url', $home_url, $current_lang);
        }
    }

    $home_url = trailingslashit($home_url);
    $permalink = $home_url . ltrim($new_path, '/');

    return $permalink;
}

add_filter('post_type_link', 'lp_guide_hierarchical_permalink', 10, 2);



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




/**
 * Ajouter les query vars personnalisées
 */
function lp_guide_query_vars($vars)
{
    $vars[] = LP_TAX_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');
