<?php
class SS_Validation {

    public static function run() {
        return [
            self::plugin_status(),
            self::glossary_page(),
            self::faq_page(),
            self::glossary_render(),
            self::faq_render(),
            self::schema_check(),
            self::ai_files_check(),
        ];
    }

    /* ---------------------------
     * SAFE FETCH HELPER (NEW)
     * --------------------------- */
    private static function fetch($url) {

        $res = wp_remote_get(trailingslashit($url), [
            'timeout'   => 15,
            'sslverify' => false,
            'headers'   => ['Cache-Control' => 'no-cache']
        ]);

        if (is_wp_error($res)) return false;

        $code = wp_remote_retrieve_response_code($res);
        if ($code !== 200) return false;

        return wp_remote_retrieve_body($res);
    }

    private static function get_page_url($type = 'glossary') {

        $id = ($type === 'faq')
            ? get_option('ss_faq_page_id')
            : get_option('ss_glossary_page_id');

        if ($id && get_post_status($id) === 'publish') {
            return get_permalink($id);
        }

        // fallback (just in case)
        return home_url('/' . ($type === 'faq' ? 'faq' : 'glossary'));
    }

    /* ---------------------------
     * PLUGIN STATUS (UNCHANGED)
     * --------------------------- */
    private static function plugin_status() {

        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $plugin = plugin_basename(SEARCHSHIFTER_PLUGIN_FILE);

        if (!is_plugin_active($plugin)) {
            return [
                'title' => 'Plugin Status',
                'status' => 'red',
                'message' => 'Plugin is not active.',
                'details' => [
                    'problem' => 'SearchShifter plugin is inactive.',
                    'why' => 'The system cannot function if the plugin is not active.',
                    'fix' => 'Activate the plugin from Plugins page.',
                    'action' => admin_url('plugins.php')
                ]
            ];
        }

        return [
            'title' => 'Plugin Status',
            'status' => 'green',
            'message' => 'Plugin is installed and active.'
        ];
    }

    /* ---------------------------
     * GLOSSARY PAGE (UNCHANGED)
     * --------------------------- */
    private static function glossary_page() {

        $page_id = get_option('ss_glossary_page_id');
        $page = $page_id ? get_post($page_id) : null;

        if (!$page) {
            return [
                'title' => 'Glossary Page',
                'status' => 'red',
                'message' => 'Glossary page not found.',
                'details' => [
                    'problem' => 'Glossary page does not exist.',
                    'why' => 'Users and AI cannot access glossary content.',
                    'fix' => 'Create a Glossary page.',
                    'action' => admin_url('post-new.php?post_type=page')
                ]
            ];
        }

        if (has_shortcode($page->post_content, 'searchshifter_glossary')) {
            return [
                'title' => 'Glossary Page',
                'status' => 'green',
                'message' => 'Connected to plugin output.'
            ];
        }

        return [
            'title' => 'Glossary Page',
            'status' => 'yellow',
            'message' => 'Page exists but connection not confirmed.',
            'details' => [
                'problem' => 'Shortcode not detected.',
                'why' => 'Content may not render correctly.',
                'fix' => 'Ensure [searchshifter_glossary] is added.',
                'action' => admin_url('post.php?post=' . $page->ID . '&action=edit')
            ]
        ];
    }

    /* ---------------------------
     * FAQ PAGE (UNCHANGED)
     * --------------------------- */
    private static function faq_page() {

        $page_id = get_option('ss_faq_page_id');
        $page = $page_id ? get_post($page_id) : null;

        if (!$page) {
            return [
                'title' => 'FAQ Page',
                'status' => 'red',
                'message' => 'FAQ page not found.',
                'details' => [
                    'problem' => 'FAQ page does not exist.',
                    'why' => 'Users cannot access FAQs.',
                    'fix' => 'Create FAQ page.',
                    'action' => admin_url('post-new.php?post_type=page')
                ]
            ];
        }

        if (has_shortcode($page->post_content, 'searchshifter_faq')) {
            return [
                'title' => 'FAQ Page',
                'status' => 'green',
                'message' => 'Connected to plugin output.'
            ];
        }

        return [
            'title' => 'FAQ Page',
            'status' => 'yellow',
            'message' => 'Page exists but connection not confirmed.',
            'details' => [
                'problem' => 'Shortcode not detected.',
                'why' => 'FAQ may not render.',
                'fix' => 'Ensure [searchshifter_faq] is added.',
                'action' => admin_url('post.php?post=' . $page->ID . '&action=edit')
            ]
        ];
    }

    /* ---------------------------
     * GLOSSARY RENDER (FIXED)
     * --------------------------- */
    private static function glossary_render() {

        $body = self::fetch(self::get_page_url('glossary'));
        $count = wp_count_posts('ss_glossary')->publish ?? 0;

        if (!$body) {
            return [
                'title' => 'Glossary Content',
                'status' => 'yellow',
                'message' => 'Unable to verify page automatically.'
            ];
        }

        if ($count == 0) {
            return [
                'title' => 'Glossary Content',
                'status' => 'yellow',
                'message' => 'No glossary terms added.'
            ];
        }

        if (
            strpos($body, 'ss-glossary') !== false ||
            strpos($body, 'SearchShifter') !== false
        ) {
            return [
                'title' => 'Glossary Content',
                'status' => 'green',
                'message' => 'Glossary content is rendering correctly.'
            ];
        }

        return [
            'title' => 'Glossary Content',
            'status' => 'red',
            'message' => 'Content not rendering.'
        ];
    }

    /* ---------------------------
     * FAQ RENDER (FIXED)
     * --------------------------- */
    private static function faq_render() {

        $count = wp_count_posts('ss_qa')->publish ?? 0;

        if ($count == 0) {
            return [
                'title' => 'FAQ Content',
                'status' => 'yellow',
                'message' => 'No FAQ entries added.'
            ];
        }

        // ✅ METHOD 1 — INTERNAL RENDER (MOST RELIABLE)
        $page_id = get_option('ss_faq_page_id');

        if ($page_id) {
            $content = get_post_field('post_content', $page_id);
            $rendered = do_shortcode($content);

            if (strpos($rendered, 'ss-public-faq') !== false) {
                return [
                    'title' => 'FAQ Content',
                    'status' => 'green',
                    'message' => 'FAQ content is rendering correctly.'
                ];
            }
        }

        // ✅ METHOD 2 — REMOTE FETCH (FALLBACK)
        $body = self::fetch(self::get_page_url('faq'));

        if ($body && strpos($body, 'ss-public-faq') !== false) {
            return [
                'title' => 'FAQ Content',
                'status' => 'green',
                'message' => 'FAQ content is rendering correctly.'
            ];
        }

        return [
            'title' => 'FAQ Content',
            'status' => 'red',
            'message' => 'Content not rendering.'
        ];
    }

    /* ---------------------------
     * SCHEMA CHECK (FIXED)
     * --------------------------- */
    private static function schema_check() {

        // -------- METHOD 1 (REMOTE GET - WORKS FOR IMPACTMINDZ) --------
        $glossary = wp_remote_get(self::get_page_url('glossary') . '?ss_check=' . time(), [
            'timeout' => 10,
            'headers' => ['Cache-Control' => 'no-cache']
        ]);

        $faq = wp_remote_get(self::get_page_url('faq') . '?ss_check=' . time(), [
            'timeout' => 10,
            'headers' => ['Cache-Control' => 'no-cache']
        ]);

        $g_ok = false;
        $f_ok = false;

        // -------- TRY METHOD 1 --------
        if (!is_wp_error($glossary)) {
            $body = wp_remote_retrieve_body($glossary);

            if (
                strpos($body, 'application/ld+json') !== false &&
                (
                    strpos($body, 'DefinedTermSet') !== false ||
                    strpos($body, '"@type":"DefinedTerm"') !== false ||
                    strpos($body, '"@type": "DefinedTerm"') !== false
                )
            ) {
                $g_ok = true;
            }
        }

        if (!is_wp_error($faq)) {
            $body = wp_remote_retrieve_body($faq);

            if (
                strpos($body, 'application/ld+json') !== false &&
                (
                    strpos($body, 'FAQPage') !== false ||
                    strpos($body, '"@type":"FAQPage"') !== false ||
                    strpos($body, '"@type": "FAQPage"') !== false
                )
            ) {
                $f_ok = true;
            }
        }

        // -------- FALLBACK METHOD 2 (FETCH - WORKS FOR LITEBITE) --------
        if (!$g_ok || !$f_ok) {

            $g_body = self::fetch(self::get_page_url('glossary'));
            $f_body = self::fetch(self::get_page_url('faq'));

            if (!$g_ok && $g_body) {
                if (
                    strpos($g_body, 'application/ld+json') !== false &&
                    (
                        strpos($g_body, 'DefinedTermSet') !== false ||
                        strpos($g_body, '"@type":"DefinedTerm"') !== false ||
                        strpos($g_body, '"@type": "DefinedTerm"') !== false
                    )
                ) {
                    $g_ok = true;
                }
            }

            if (!$f_ok && $f_body) {
                if (
                    strpos($f_body, 'application/ld+json') !== false &&
                    (
                        strpos($f_body, 'FAQPage') !== false ||
                        strpos($f_body, '"@type":"FAQPage"') !== false ||
                        strpos($f_body, '"@type": "FAQPage"') !== false
                    )
                ) {
                    $f_ok = true;
                }
            }
        }

        // -------- FINAL RESULT --------
        if ($g_ok && $f_ok) {
            return [
                'title' => 'Schema Presence',
                'status' => 'green',
                'message' => 'Schema detected on Glossary and FAQ pages.'
            ];
        }

        if ($g_ok || $f_ok) {
            return [
                'title' => 'Schema Presence',
                'status' => 'yellow',
                'message' => 'Schema partially detected.',
                'details' => [
                    'problem' => 'Schema missing on one page.',
                    'why' => 'AI understanding may be incomplete.',
                    'fix' => 'Ensure schema is output on both Glossary and FAQ pages.'
                ]
            ];
        }

        return [
            'title' => 'Schema Presence',
            'status' => 'red',
            'message' => 'Schema not detected.',
            'details' => [
                'problem' => 'No schema found.',
                'why' => 'AI cannot understand your content.',
                'fix' => 'Enable schema in SearchShifter settings.'
            ]
        ];
    }
    /* ---------------------------
     * AI FILES (FIXED)
     * --------------------------- */
    private static function ai_files_check() {

        $ai = wp_remote_get(site_url('/ai.txt'), ['sslverify' => false]);
        $llms = wp_remote_get(site_url('/llms.txt'), ['sslverify' => false]);

        $ai_ok = !is_wp_error($ai) && wp_remote_retrieve_response_code($ai) === 200;
        $llms_ok = !is_wp_error($llms) && wp_remote_retrieve_response_code($llms) === 200;

        if ($ai_ok && $llms_ok) {
            return [
                'title' => 'AI Crawler Files',
                'status' => 'green',
                'message' => 'Both files accessible.'
            ];
        }

        if ($ai_ok || $llms_ok) {
            return [
                'title' => 'AI Crawler Files',
                'status' => 'yellow',
                'message' => 'One file accessible.'
            ];
        }

        return [
            'title' => 'AI Crawler Files',
            'status' => 'red',
            'message' => 'Files missing.'
        ];
    }
}