<?php
/**
 * SearchShifter Shortcodes
 * Handles public shortcode rendering for glossary, FAQ, light checker, and more.
 */

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

class SS_Shortcodes {

    /**
     * Initialize all shortcodes
     */
    public static function init() {
        // Register shortcodes
        add_shortcode('ss_light_checker', [__CLASS__, 'render_light_checker']);
        add_shortcode('searchshifter_glossary', [__CLASS__, 'render_glossary']);
        add_shortcode('searchshifter_faq', [__CLASS__, 'render_faq']);

        // Enqueue assets for light checker
        add_action('wp_enqueue_scripts', [__CLASS__, 'enqueue_light_checker_assets']);
    }

    /**
     * Light Checker Shortcode
     * Usage: [ss_light_checker]
     */
    public static function render_light_checker() {
        ob_start(); ?>
        <div class="ss-light-checker">
            <form id="ss-light-form" style="max-width:480px;margin:auto;text-align:center;">
                <input type="url" id="ss-light-url" placeholder="https://example.com" required
                    style="width:100%;padding:10px;border:1px solid #ccc;border-radius:6px;">
                <button type="submit"
                    style="margin-top:10px;padding:10px 16px;background:#111;color:#fff;border:0;border-radius:6px;cursor:pointer;">
                    Check My Site
                </button>
            </form>
            <div id="ss-light-result" style="margin-top:20px;text-align:left;"></div>
        </div>
        <?php
        return ob_get_clean();

    }

    /**
     * Enqueue JS for the light checker
     */
    public static function enqueue_light_checker_assets() {
        $handle = 'ss-light-checker';
        wp_enqueue_script(
            $handle,
            plugins_url('../../public/js/light-checker.js', __FILE__),
            ['jquery'],
            SEARCHSHIFTER_VERSION,
            true
        );
        wp_localize_script($handle, 'SS_LIGHT', [
            'endpoint' => rest_url('searchshifter/v1/light-check'),
        ]);
    }

    /**
     * Glossary Shortcode
     * Usage: [searchshifter_glossary]
     */
public static function render_glossary() {

    $plan = ss_get_current_plan(); // free, pro, authority, elite

    // Fetch all glossary CPT terms
    $terms = get_posts([
        'post_type'      => 'ss_glossary',
        'posts_per_page' => -1,
        'orderby'        => 'title',
        'order'          => 'ASC'
    ]);

    if (empty($terms)) {
        return "<p>No glossary terms found.</p>";
    }

    // Active letters
    $active_letters = [];
    foreach ($terms as $t) {
        $active_letters[] = strtoupper(substr($t->post_title, 0, 1));
    }
    $active_letters = array_unique($active_letters);

    // Group A–Z
    $groups = [];
    foreach ($terms as $t) {
        $letter = strtoupper(substr($t->post_title, 0, 1));
        if (!isset($groups[$letter])) $groups[$letter] = [];
        $groups[$letter][] = $t;
    }

    ob_start();
    ?>

<h1 class="ss-glossary-main-title">SearchShifter™ Glossary</h1>

<div class="ss-glossary-page">

    <!-- Search Bar -->
    <div class="ss-glossary-search-wrapper">
        <input type="text" id="ss-glossary-search" placeholder="Search glossary terms...">
    </div>

    <!-- A–Z Navigation -->
    <div class="ss-glossary-nav">
        <?php foreach (range('A','Z') as $l): ?>
            <a href="<?php echo in_array($l, $active_letters) ? '#ss-'.$l : 'javascript:void(0)'; ?>" 
               class="<?php echo in_array($l, $active_letters) ? '' : 'inactive'; ?>">
                <?php echo $l; ?>
            </a>
        <?php endforeach; ?>
    </div>

    <!-- A–Z Sections -->
    <div id="ss-glossary-container">
    <?php foreach ($groups as $letter => $items): ?>
        <div class="ss-letter-section" data-letter="<?php echo $letter; ?>">
            <h2 id="ss-<?php echo $letter; ?>"><?php echo $letter; ?></h2>

            <ul class="ss-term-list">
                <?php foreach ($items as $t): 
                    $def = get_post_meta($t->ID, 'ss_definition', true);
                    $vid = get_post_meta($t->ID, 'ss_video_url', true);

                    // First 22 words preview
                    $preview = wp_trim_words(strip_tags($def), 22);

                    // Determine if lock icon should show
                    $show_lock = false;

                    // FREE → lock everything beyond Definition
                    if ($plan === 'free' && $vid) {
                        $show_lock = true;
                    }

                    // PRO → lock only Authority-level features
                    if ($plan === 'pro' && $vid) {
                        $show_lock = true;
                    }

                ?>
                <li class="ss-term-item" data-term="<?php echo strtolower($t->post_title); ?>">

                    <a class="ss-term-title" href="<?php echo get_permalink($t->ID); ?>">
                        <?php echo esc_html($t->post_title); ?>
                    </a>

                    <!-- Authority Only Video Badge -->
                    <?php if ($vid && $plan === 'authority'): ?>
                        <span class="ss-video-badge">🎥</span>
                    <?php endif; ?>

                    <!-- Lock Badge -->
                    <?php if ($show_lock): ?>
                        <span class="ss-lock-badge">🔒</span>
                    <?php endif; ?>

                    <p class="ss-term-preview"><?php echo esc_html($preview); ?></p>
                </li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endforeach; ?>
    </div>

</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const input = document.getElementById("ss-glossary-search");
    const items = document.querySelectorAll(".ss-term-item");
    const sections = document.querySelectorAll(".ss-letter-section");

    input.addEventListener("keyup", function() {
        let q = this.value.toLowerCase();

        items.forEach(item => {
            let text = item.dataset.term;
            item.style.display = text.includes(q) ? "block" : "none";
        });

        // Hide empty letter sections
        sections.forEach(section => {
            const visible = section.querySelectorAll(".ss-term-item[style*='block']").length > 0;
            section.style.display = visible ? "block" : "none";
        });
    });
});
</script>

<style>
.ss-glossary-main-title {
    text-align:center;
    font-size:32px;
    margin-bottom:25px;
}

.ss-video-badge {
    margin-left:6px;
    color:#0073aa;
    font-size:15px;
}

.ss-lock-badge {
    margin-left:6px;
    color:#999;
    font-size:15px;
}
</style>

    <?php
    return ob_get_clean();
}



    /**
     * FAQ Shortcode
     * Usage: [searchshifter_faq]
     */
    public static function render_faq() {
        ob_start();
        $template_path = SEARCHSHIFTER_PLUGIN_DIR . 'includes/faq-display.php';
        if (file_exists($template_path)) {
            include $template_path;
        } else {
            echo '<p style="color:red;">⚠️ FAQ template not found at: ' . esc_html($template_path) . '</p>';
        }
        return ob_get_clean();
    }
}

// ✅ Initialize the shortcodes after WordPress loads
add_action('init', ['SS_Shortcodes', 'init']);
