<?php


$is_archive   = is_post_type_archive();
$is_guide_tax = function_exists('is_tax') ? is_tax(LP_TAX_GUIDE_CATEGORY) : false;
if ($is_guide_tax) {
    $is_archive = false;
}
$current_term = $is_guide_tax ? get_queried_object() : null;
$paged        = max(1, get_query_var('paged') ? (int) get_query_var('paged') : (get_query_var('page') ? (int) get_query_var('page') : 1));

// Sécuriser l'accès à $args['post_type'] : $args peut être null ou un entier selon l'appel
if (isset($args) && is_array($args) && !empty($args['post_type'])) {
    $post_type = $args['post_type'];
} else {
    $post_type = 'guide';
}
$cover_image = null;

if ($is_archive) {
    $surtitre =  get_field('guide_surtitre', 'option');
    $titre = get_field('guide_titre', 'option');
    $cover_image = get_field('guide_cover', 'option');
    $description = get_field('guide_description', 'option');
} else if ($is_guide_tax && $current_term && !is_wp_error($current_term)) {
    $titre = $current_term->name;
    $cover_image = get_field('guide_category_image', 'term_' . (int) $current_term->term_id);

    $parent_term = $current_term->parent ? get_term((int) $current_term->parent, LP_TAX_GUIDE_CATEGORY) : null;
    $surtitre    = (!is_wp_error($parent_term) && $parent_term) ? $parent_term->name : get_field('guide_titre', 'option');
    $description = $current_term->description;
}






$query_args = array(
    'post_type'      => $post_type,
    'posts_per_page' => get_option('posts_per_page'),
    'post_status'    => array('publish', 'private'),
    'paged'          => $paged,
);

$categories_args = array(
    'taxonomy'   => LP_TAX_GUIDE_CATEGORY,
    'hide_empty' => false,
    'parent'     => 0,
);
// Filter by current taxonomy if on a guide_category archive and if the current term has a parent get the parent term id
if ($is_guide_tax && $current_term && !is_wp_error($current_term)) {
    $query_args['tax_query'] = array(
        array(
            'taxonomy' => LP_TAX_GUIDE_CATEGORY,
            'field'    => 'slug',
            'terms'     => $current_term->slug,
        ),
    );

    $categories_args['parent'] = $current_term->term_id;
}

$the_query = new WP_Query($query_args);
?>


<?php
// if (function_exists('yoast_breadcrumb') && $is_archive) {
//     yoast_breadcrumb('<div class="breadcrumbs"><div class="container">', '</div></div>');
// }
// echo 'is_archive', $is_archive;
// echo 'is_guide_tax', $is_guide_tax;
// echo 'is_category', is_category();


if ($is_archive) {
?>
    <div class="breadcrumbs">
        <nav class="container breadcrumb" aria-label="breadcrumb">
            <ol class="breadcrumb-list">
                <li class="breadcrumb-item"><a href="<?php echo esc_url(home_url('/')); ?>"><?php echo __('Home', 'laurentperrier'); ?></a><span class="separator">&gt;</span></li>
                <li class="breadcrumb-item"><span><?php echo __('Guides &amp; Tips', 'laurentperrier'); ?></span></li>
            </ol>
        </nav>
    </div>
<?php

} else if ($is_guide_tax) {
    if ($is_guide_tax && $current_term && !is_wp_error($current_term)) {
        lp_display_guide_category_breadcrumb($current_term, array('show_current' => true));
    } else {
        lp_display_guide_breadcrumb(null, array('show_current' => true));
    }
}
?>


<div class="relative flex items-center justify-center min-h-[549px]">
    <div class="layer">
        <?php
        // $cover_image peut être soit un tableau ACF (avec ['ID']), soit un ID entier.
        if (is_array($cover_image) && !empty($cover_image['ID'])):
            echo wp_get_attachment_image($cover_image['ID'], 'full', false, array('class' => 'z-0 w-full h-full object-cover top-0 left-0 absolute'));
        elseif (!empty($cover_image)):
            echo wp_get_attachment_image($cover_image, 'full', false, array('class' => 'z-0 w-full h-full object-cover top-0 left-0 absolute'));
        endif; ?>
        <div class="absolute inset-0 bg-black opacity-50"></div>
    </div>
    <div class="relative">
        <h1 class="font-heading text-[1.75rem] md:text-[2.5rem] font-normal uppercase leading-snug text-white text-center">
            <small class="text-xs md:text-sm block ">
                <?php echo esc_html($surtitre); ?>
            </small>
            <?php echo $titre; ?>
            <?php if ($paged > 1): ?>
                <span class="text-xs  opacity-50">
                    <?php echo __('Page', 'laurentperrier'); ?> <?php echo $paged; ?>
                </span>
            <?php endif; ?>
        </h1>
    </div>
</div>

<div class="container py-10 md:py-20 max-w-7xl flex flex-col gap-20  ">
    <?php if ($description): ?>
        <div class="max-w-4xl mx-auto">
            <?php echo $description; ?>
        </div>
    <?php endif; ?>
    <!-- Liste des catégories (only on page 1) -->
    <?php if ((int)$paged === 1): ?>
        <?php $categories = get_terms($categories_args); ?>
        <?php if (!empty($categories) && !is_wp_error($categories)) : ?>
            <section class="">
                <!-- <h2 class="font-italic text-center text-3xl md:text-[3rem]  mb-8 md:mb-10 italic normal-case"><?php //_e('Catégories', 'laurentperrier');
                                                                                                                    ?></h2> -->
                <div class="divide-y divide-gold/50">
                    <?php foreach ($categories as $term) :
                        $img_id = get_field('guide_category_thumb', 'term_' . $term->term_id);
                        $img_html = $img_id ? wp_get_attachment_image($img_id, 'large', false, array('class' => 'absolute top-0 left-0 w-full h-full object-cover object-center')) : '';
                        $term_link = get_term_link($term);
                    ?>
                        <article class="py-8">
                            <div class="grid grid-cols-1 md:grid-cols-12 gap-6 md:gap-20 items-center">
                                <div class="md:col-span-5">
                                    <div class="block  overflow-hidden aspect-4/3 relative">
                                        <?php echo $img_html; ?>
                                    </div>
                                </div>
                                <div class="md:col-span-7 flex flex-col gap-5 items-start">
                                    <h3 class="font-heading text-xl md:text-2xl uppercase">
                                        <?php echo esc_html($term->name); ?>
                                    </h3>
                                    <?php if (!empty($term->description)) : ?>
                                        <div class="link-gold link-underline link-strong">
                                            <?php echo wp_kses_post($term->description); ?>
                                        </div>
                                    <?php endif; ?>
                                    <?php
                                    get_template_part(
                                        'template-parts/components/read-more',
                                        null,
                                        array(
                                            'href'       => $term_link
                                        )
                                    );
                                    ?>
                                </div>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
            </section>
        <?php endif; ?>
    <?php endif; ?>



    <!-- Liste des Guides -->
    <?php if ($the_query->have_posts()): ?>
        <section class="">
            <div class="flex flex-col gap-20">
                <div>
                    <h2 class="font-cursive text-center text-3xl md:md:text-[3rem] italic normal-case !leading-none">
                        <small class="block text-lg md:text-2xl !leading-none">
                            <?php echo
                            __('Tous les articles dans ', 'laurentperrier') ?></small>
                        <span class="!leading-none">"<?php echo $titre; ?>"</span>
                    </h2>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-8 md:gap-10 lg:gap-24">
                    <?php while ($the_query->have_posts()): $the_query->the_post(); ?>
                        <?php get_template_part('template-parts/guide/card'); ?>
                    <?php endwhile; ?>
                </div>
            </div>
            <!-- Pagination -->
            <section class="wrapper blog-pagination">
                <?php
                $big = 999999999; // need an unlikely integer
                $base = str_replace($big, '%#%', esc_url(get_pagenum_link($big)));
                // Default: pretty permalinks use /page/2/ on archives; plain uses ?paged=2
                $format = get_option('permalink_structure') ? 'page/%#%/' : '?paged=%#%';

                // On taxonomy archives, anchor the base to the term link to avoid language/slug mismatches
                if ($is_guide_tax && $current_term && !is_wp_error($current_term)) {
                    $term_url = get_term_link($current_term);
                    if (!is_wp_error($term_url)) {
                        $base = trailingslashit($term_url) . user_trailingslashit('page/%#%/', 'paged');
                        $format = ''; // format embedded in base
                    }
                }

                $pagination_links = paginate_links(array(
                    'base'      => $base,
                    'format'    => $format,
                    'total'     => max(1, (int) $the_query->max_num_pages),
                    'current'   => max(1, (int) $paged),
                    'type'      => 'array',
                    'end_size'  => 3,
                    'mid_size'  => 1,
                    'prev_next' => true,
                    'prev_text' => __('Précédent', 'laurentperrier'),
                    'next_text' => __('Suivant', 'laurentperrier'),
                ));

                if ($pagination_links): ?>
                    <div class="flex justify-center items-center space-x-2 mt-12">
                        <?php foreach ($pagination_links as $link): ?>
                            <div class="pagination-item"><?php echo $link; ?></div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>
            <?php wp_reset_postdata(); ?>


        <?php endif; ?>
</div>
