<?php

function register_accordion_post_type() {
    register_post_type('accordion', [
        'labels' => [
            'name' => __('Accordions'),
            'singular_name' => __('Accordion'),
        ],
        'public' => true,
        'has_archive' => true,
        'supports' => ['title', 'editor'],
        'hierarchical' => false,
        'show_in_rest' => true,
    ]);

    register_taxonomy('accordion_category', 'accordion', [
        'labels' => [
            'name' => __('Accordion Categories'),
            'singular_name' => __('Accordion Category'),
        ],
        'hierarchical' => true,
        'show_in_rest' => true,
    ]);
}
add_action('init', 'register_accordion_post_type');


//Shortcode
function accordion_shortcode($atts) {
    $atts = shortcode_atts(['category' => ''], $atts);

    // Fetch posts in the specified category
    $args = [
        'post_type' => 'accordion',
        'order' => 'ASC',
        'tax_query' => [
            [
                'taxonomy' => 'accordion_category',
                'field' => 'slug',
                'terms' => $atts['category'],
            ],
        ],
        'posts_per_page' => -1,
    ];
    $query = new WP_Query($args);

    if (!$query->have_posts()) {
        return '<p>No accordion items found.</p>';
    }

    // Build the accordion HTML
    $output = '<div class="accordion" id="accordionExample">';
    $count = 0;

    while ($query->have_posts()) {
        $query->the_post();
        $count++;
        $title = get_the_title();
        $excerpt = get_the_content();

        $output .= '
        <div class="accordion-item border-0">
            <h2 class="accordion-header" id="heading' . $count . '">
                <button class="accordion-button border-0 ' . ($count > 1 ? 'collapsed' : '') . '" type="button" data-bs-toggle="collapse" data-bs-target="#collapse' . $count . '" aria-expanded="' . ($count === 1 ? 'true' : 'false') . '" aria-controls="collapse' . $count . '">
                    <i class="bi bi-check-circle fs-4 fw-normal me-2"></i>' . esc_html($title) . '
                </button>
            </h2>
            <div id="collapse' . $count . '" class="accordion-collapse collapse ' . ($count === 1 ? 'show' : '') . '" aria-labelledby="heading' . $count . '" data-bs-parent="#accordionExample">
                <div class="accordion-body">
                    ' .$excerpt . '
                </div>
            </div>
        </div>';
    }

    wp_reset_postdata();
    $output .= '</div>';

    return $output;
}
add_shortcode('accordion', 'accordion_shortcode');
