<?php

if (!defined('ABSPATH')) {
    exit;
}

class AIEO_FAQ {

    const POST_TYPE = 'faq';
    const TAXONOMY  = 'faq_group';

    private static $instance = null;

    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action('init', array($this, 'register_content'));
        add_action('init', array($this, 'register_shortcodes'));
        add_action('wp_enqueue_scripts', array($this, 'maybe_enqueue_assets'));
    }

    
    public function register_content() {
        register_taxonomy(self::TAXONOMY, array(self::POST_TYPE), array(
            'labels' => array(
                'name'          => __('FAQ Groups', 'ai-eshop-optimizer'),
                'singular_name' => __('FAQ Group', 'ai-eshop-optimizer'),
                'menu_name'     => __('FAQ Groups', 'ai-eshop-optimizer'),
                'all_items'     => __('All FAQ Groups', 'ai-eshop-optimizer'),
                'edit_item'     => __('Edit FAQ Group', 'ai-eshop-optimizer'),
                'add_new_item'  => __('Add FAQ Group', 'ai-eshop-optimizer'),
                'new_item_name' => __('New FAQ Group name', 'ai-eshop-optimizer'),
                'search_items'  => __('Search FAQ Groups', 'ai-eshop-optimizer'),
            ),
            'public'             => false,
            'publicly_queryable' => false,
            'hierarchical'       => true,  
            'show_ui'            => true,
            'show_in_menu'       => false, 
            'show_in_rest'       => true,  
            'show_admin_column'  => true,
            'rewrite'            => false,
        ));

        register_post_type(self::POST_TYPE, array(
            'labels' => array(
                'name'          => __('FAQs', 'ai-eshop-optimizer'),
                'singular_name' => __('FAQ', 'ai-eshop-optimizer'),
                'menu_name'     => __('FAQ', 'ai-eshop-optimizer'),
                'all_items'     => __('All FAQs', 'ai-eshop-optimizer'),
                'add_new_item'  => __('Add FAQ', 'ai-eshop-optimizer'),
                'edit_item'     => __('Edit FAQ', 'ai-eshop-optimizer'),
                'new_item'      => __('New FAQ', 'ai-eshop-optimizer'),
                'search_items'  => __('Search FAQs', 'ai-eshop-optimizer'),
                'not_found'     => __('No FAQs found', 'ai-eshop-optimizer'),
            ),
            'public'              => false,
            'publicly_queryable'  => false,
            'show_ui'             => true,
            
            
            'show_in_menu'        => false,
            'show_in_nav_menus'   => false,
            'show_in_rest'        => true, 
            'exclude_from_search' => true,
            'menu_icon'           => 'dashicons-editor-help',
            'supports'            => array('title', 'editor', 'page-attributes'),
            'has_archive'         => false,
            'rewrite'             => false,
            'hierarchical'        => false,
            'taxonomies'          => array(self::TAXONOMY),
        ));
    }

    public function register_shortcodes() {
        add_shortcode('aieo_faq', array($this, 'render_shortcode'));
        
        if (!shortcode_exists('faq')) {
            add_shortcode('faq', array($this, 'render_shortcode'));
        }
    }

    
    public function maybe_enqueue_assets() {
        if (is_admin()) {
            return;
        }
        $rel = 'assets/css/aieo-faq-accordion.css';
        $dir = defined('AIEO_DIR') ? AIEO_DIR : plugin_dir_path(dirname(__FILE__)) . '';
        $uri = defined('AIEO_URI') ? AIEO_URI : plugins_url('/', dirname(__FILE__));
        $abs = $dir . $rel;
        $ver = file_exists($abs) ? (string) filemtime($abs) : (defined('AIEO_VERSION') ? AIEO_VERSION : '1.0');
        wp_register_style('aieo-faq-accordion', $uri . $rel, array(), $ver);

        if (is_singular()) {
            $post = get_post();
            if ($post && (has_shortcode($post->post_content, 'faq') || has_shortcode($post->post_content, 'aieo_faq'))) {
                wp_enqueue_style('aieo-faq-accordion');
            }
        }
    }

    

    public function render_shortcode($atts) {
        $atts = shortcode_atts(array(
            'group'    => '',
            'title'    => '',
            'sections' => '',
            'ids'      => '',
            'limit'    => '-1',
            'orderby'  => 'menu_order',
            'order'    => 'ASC',
        ), $atts, 'faq');

        
        
        if (wp_style_is('aieo-faq-accordion', 'registered') && !wp_style_is('aieo-faq-accordion', 'enqueued')) {
            wp_enqueue_style('aieo-faq-accordion');
        }

        $sections = in_array(strtolower((string) $atts['sections']), array('1', 'yes', 'true', 'on'), true);
        if ($sections && '' === $atts['group'] && '' === $atts['ids']) {
            return $this->render_sectioned($atts);
        }

        $q = new WP_Query($this->build_query_args($atts));
        if (!$q->have_posts()) {
            wp_reset_postdata();
            return '';
        }
        $html = $this->accordion_from_query($q);
        wp_reset_postdata();
        return $this->wrap($html, $atts['title']);
    }

    private function build_query_args($atts) {
        $args = array(
            'post_type'           => self::POST_TYPE,
            'post_status'         => 'publish',
            'posts_per_page'      => (int) $atts['limit'],
            'orderby'             => array('menu_order' => 'ASC', 'date' => 'ASC'),
            'no_found_rows'       => true,
            'ignore_sticky_posts' => true,
        );

        $ob = sanitize_key((string) $atts['orderby']);
        if ($ob && 'menu_order' !== $ob) {
            $args['orderby'] = $ob;
            $args['order']   = ('DESC' === strtoupper((string) $atts['order'])) ? 'DESC' : 'ASC';
        }

        if ('' !== $atts['group']) {
            $slugs = array_filter(array_map('sanitize_title', array_map('trim', explode(',', (string) $atts['group']))));
            if ($slugs) {
                $args['tax_query'] = array(array(
                    'taxonomy' => self::TAXONOMY,
                    'field'    => 'slug',
                    'terms'    => $slugs,
                ));
            }
        }

        if ('' !== $atts['ids']) {
            $ids = array_filter(array_map('absint', explode(',', (string) $atts['ids'])));
            if ($ids) {
                $args['post__in'] = $ids;
                $args['orderby']  = 'post__in';
            }
        }

        return $args;
    }

    private function accordion_from_query($q) {
        $out = '<div class="aieo-faq-accordion">';
        while ($q->have_posts()) {
            $q->the_post();
            $raw    = get_the_content();
            $answer = has_blocks($raw) ? do_blocks($raw) : wpautop($raw);
            $out   .= '<details class="aieo-faq-accordion__item">'
                . '<summary class="aieo-faq-accordion__q">' . esc_html(get_the_title()) . '</summary>'
                . '<div class="aieo-faq-accordion__a">' . $answer . '</div>'
                . '</details>';
        }
        $out .= '</div>';
        return $out;
    }

    
    private function render_sectioned($atts) {
        $terms = get_terms(array(
            'taxonomy'   => self::TAXONOMY,
            'hide_empty' => true,
            'orderby'    => 'name',
        ));
        if (is_wp_error($terms)) {
            $terms = array();
        }

        $out = '';
        foreach ($terms as $term) {
            $q = new WP_Query(array(
                'post_type'           => self::POST_TYPE,
                'post_status'         => 'publish',
                'posts_per_page'      => -1,
                'orderby'             => array('menu_order' => 'ASC', 'date' => 'ASC'),
                'no_found_rows'       => true,
                'ignore_sticky_posts' => true,
                'tax_query'           => array(array(
                    'taxonomy' => self::TAXONOMY,
                    'field'    => 'term_id',
                    'terms'    => $term->term_id,
                )),
            ));
            if (!$q->have_posts()) {
                wp_reset_postdata();
                continue;
            }
            $out .= '<h3 class="aieo-faq__section-title">' . esc_html($term->name) . '</h3>';
            $out .= $this->accordion_from_query($q);
            wp_reset_postdata();
        }

        
        $ung = new WP_Query(array(
            'post_type'           => self::POST_TYPE,
            'post_status'         => 'publish',
            'posts_per_page'      => -1,
            'orderby'             => array('menu_order' => 'ASC', 'date' => 'ASC'),
            'no_found_rows'       => true,
            'ignore_sticky_posts' => true,
            'tax_query'           => array(array(
                'taxonomy' => self::TAXONOMY,
                'operator' => 'NOT EXISTS',
            )),
        ));
        if ($ung->have_posts()) {
            $out .= $this->accordion_from_query($ung);
        }
        wp_reset_postdata();

        if ('' === $out) {
            return '';
        }
        return $this->wrap($out, $atts['title']);
    }

    private function wrap($html, $title = '') {
        $title = trim((string) $title);
        $pre   = ('' !== $title)
            ? '<h2 class="aieo-faq__title">' . esc_html($title) . '</h2>'
            : '';
        return '<div class="aieo-faq">' . $pre . $html . '</div>';
    }
}

AIEO_FAQ::instance();
