<?php
if (!defined('ABSPATH')) exit;

class SS_FAQ_Frontend {

    public static function init() {
        add_filter('the_content', [self::class, 'render_archive'], 999);
        add_filter('request', [self::class, 'rewrite']);
        add_filter('template_include', [self::class, 'template']);
    }

    public static function render_archive($content) {

        if (!is_post_type_archive('ss_qa') || !in_the_loop()) {
            return $content;
        }

        $query = new WP_Query([
            'post_type' => 'ss_qa',
            'posts_per_page' => -1,
        ]);

        ob_start(); ?>

        <div class="ss-faq-archive" style="max-width:900px;margin:60px auto;padding:20px;">

            <h1 style="font-size:32px;margin-bottom:30px;">FAQs</h1>

            <?php if ($query->have_posts()): ?>
                <?php while ($query->have_posts()): $query->the_post(); ?>

                    <?php
                    $answer = get_post_meta(get_the_ID(), '_ss_qa_answer', true);
                    ?>

                    <div style="margin-bottom:30px;padding-bottom:20px;border-bottom:1px solid #ddd;">

                        <h2 style="font-size:22px;">
                            <a href="<?php the_permalink(); ?>" style="text-decoration:none;">
                                <?php the_title(); ?>
                            </a>
                        </h2>

                        <?php if ($answer): ?>
                            <p style="margin-top:10px;color:#555;">
                                <?php echo esc_html(wp_trim_words($answer, 25)); ?>
                            </p>
                        <?php endif; ?>

                    </div>

                <?php endwhile; ?>
                <?php wp_reset_postdata(); ?>
            <?php else: ?>
                <p>No FAQs found.</p>
            <?php endif; ?>

        </div>

        <?php
        return ob_get_clean();
    }

    public static function rewrite($query_vars) {

        if (isset($query_vars['pagename']) && strpos($query_vars['pagename'], 'faq/') === 0) {

            $slug = str_replace('faq/', '', $query_vars['pagename']);

            return [
                'post_type' => 'ss_qa',
                'name' => $slug
            ];
        }

        return $query_vars;
    }

    public static function template($template) {

        if (is_singular('ss_qa')) {

            $custom = SEARCHSHIFTER_PLUGIN_DIR . 'includes/single-ss_qa.php';

            if (file_exists($custom)) {
                return $custom;
            }
        }

        return $template;
    }
}