<?php
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped,WordPress.Security.EscapeOutput.ExceptionNotEscaped,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQLPlaceholders.LikeWildcardsInQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_fclose,WordPress.WP.AlternativeFunctions.file_system_operations_is_writable,WordPress.WP.AlternativeFunctions.file_system_operations_chmod,WordPress.WP.AlternativeFunctions.file_system_operations_rmdir,WordPress.DateTime.RestrictedFunctions.date_date,WordPress.WP.I18n.NonSingularStringLiteralDomain,WordPress.WP.I18n.MissingTranslatorsComment,WordPress.WP.I18n.MissingArgDomain,WordPressVIPMinimum.Performance.WPQueryParams.SuppressFilters_suppress_filters,WordPress.WP.EnqueuedResources.NonEnqueuedScript,WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- WordPress.org PCP audit pass: legacy controlled-beta surfaces require targeted follow-up hardening.
if (!defined('ABSPATH')) {
    exit;
}


class Aysa_Public {
    private $plugin_name;
    private $version;
    private $seo_appendix_rendered = array();
    private $seo_appendix_jsonld_rendered = array();

    public function __construct($plugin_name, $version) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }

    public function enqueue_styles() {
        wp_enqueue_style(
            $this->plugin_name,
            AYSA_PLUGIN_URL . 'assets/css/aysa.css',
            array(),
            $this->version,
            'all'
        );
    }

    public function enqueue_scripts() {
        wp_enqueue_script(
            $this->plugin_name,
            AYSA_PLUGIN_URL . 'assets/js/aysa.js',
            array('jquery'),
            $this->version,
            false
        );

        // Localize the script with new data
        wp_localize_script(
            $this->plugin_name,
            'aysa_ajax',
            array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('aysa_ajax_nonce'),
                'home_url' => home_url()
            )
        );
    }

    /**
     * Handle front-end 301 redirects based on API records
     */
    public function handle_frontend_redirect() {
        if (is_admin()) {
            return;
        }
        
        // Enable this for extensive debugging
        $debug = defined('WP_DEBUG') && WP_DEBUG;
        
        // Normalize requested path to match stored SourceUrl
        $req = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
        if ($debug) aysa_debug_log("[AYSA] Original requested URI: $req");
        
        // Strip WordPress base path
        $base = wp_parse_url(home_url(), PHP_URL_PATH) ?: '';
        if (strpos($req, $base) === 0) {
            $req = substr($req, strlen($base));
        }
        
        // Remove /index.php if present
        $path = preg_replace('#^/index\.php#', '', $req);
        
        if ($debug) aysa_debug_log("[AYSA] Normalized path for redirect check: $path");
        
        // Demo 410 for on-page testing without DB entries
        if ($path === '/fake-410-page') {
            if ($debug) aysa_debug_log("[AYSA] Demo 410 for $path");
            status_header(410);
            nocache_headers();
            exit;
        }
        
        // Fetch redirects from API using centralized config
        $api_url = Aysa_API_Config::get_endpoint_url('redirects');
        
        // Fallback to old method if config not available
        if (!$api_url) {
            $api_url = rtrim(AYSA_API_BASE_URL, '/') . '/api/Redirect';
        }
        
        if ($debug) aysa_debug_log("[AYSA] Fetching redirects from: $api_url");
        
        $response = wp_remote_get($api_url);
        if (is_wp_error($response)) {
            if ($debug) aysa_debug_log('[AYSA] wp_remote_get error: ' . $response->get_error_message());
            return;
        }
        
        $body = wp_remote_retrieve_body($response);
        $items = json_decode($body, true);
        
        if (!is_array($items)) {
            if ($debug) aysa_debug_log('[AYSA] Invalid redirects response: ' . substr($body, 0, 255));
            return;
        }
        
        if ($debug) aysa_debug_log('[AYSA] Found ' . count($items) . ' redirects to process');
        
        // Look for a matching SourceUrl
        foreach ($items as $r) {
            if (isset($r['SourceUrl']) && $r['SourceUrl'] === $path) {
                $dest = isset($r['DestinationUrl']) ? $r['DestinationUrl'] : '';
                if (!empty($dest)) {
                    if ($debug) {
                        aysa_debug_log("[AYSA] Matched redirect: $path → $dest");
                        aysa_debug_log("[AYSA] Redirect details: " . json_encode($r));
                    }
                    
                    // Add home_url to relative paths if needed
                    if (strpos($dest, 'http') !== 0) {
                        $dest = home_url($dest);
                        if ($debug) aysa_debug_log("[AYSA] Expanded destination URL: $dest");
                    }
                    
                    $dest_host = wp_parse_url($dest, PHP_URL_HOST);
                    if ($dest_host) {
                        add_filter('allowed_redirect_hosts', static function($hosts) use ($dest_host) {
                            $hosts[] = $dest_host;
                            return array_unique($hosts);
                        });
                    }
                    wp_safe_redirect($dest, 301);
                    exit;
                }
            }
        }
        
        if ($debug) aysa_debug_log("[AYSA] No matching redirect found for: $path");
        
        // Get gone URLs from API using centralized config
        $gone_api = Aysa_API_Config::get_endpoint_url('gone_urls');
        
        // Fallback to old method if config not available
        if (!$gone_api) {
            $gone_api = rtrim(AYSA_API_BASE_URL, '/') . '/api/GoneUrl';
        }
        
        $gone_resp = wp_remote_get($gone_api);
        if (!is_wp_error($gone_resp)) {
            $gone_body = wp_remote_retrieve_body($gone_resp);
            $gone_items = json_decode($gone_body, true);
            
            if (is_array($gone_items)) {
                if ($debug) aysa_debug_log('[AYSA] Found ' . count($gone_items) . ' gone URLs');
                
                foreach ($gone_items as $g) {
                    if (isset($g['Url']) && $g['Url'] === $path) {
                        if ($debug) aysa_debug_log("[AYSA] Returning 410 for $path");
                        status_header(410);
                        nocache_headers();
                        exit;
                    }
                }
            }
        }
    }

    /**
     * Disable WordPress canonical redirects to allow plugin redirects to run
     */
    public function disable_canonical_redirect($redirect_url) {
        return false;
    }

    public function append_seo_appendix_to_content($content) {
        if (!in_the_loop() || !is_main_query()) {
            return $content;
        }

        $appendix = $this->render_seo_appendix_for_current_post();
        if ($appendix === '') {
            return $content;
        }

        return $content . $appendix;
    }

    public function render_seo_appendix_footer() {
        $appendix = $this->render_seo_appendix_for_current_post();
        if ($appendix !== '') {
            echo $appendix;
        }
        $jsonld = $this->render_seo_appendix_jsonld_for_current_post();
        if ($jsonld !== '') {
            echo $jsonld;
        }
    }

    public function print_seo_appendix_styles() {
        if (!$this->should_render_seo_appendix()) {
            return;
        }
        $post_id = (int) get_queried_object_id();
        if ($post_id <= 0 || trim((string) get_post_meta($post_id, '_aysa_seo_appendix_html', true)) === '') {
            return;
        }
        ?>
        <style>
            .aysa-seo-appendix{max-width:var(--wp--style--global--content-size,1100px);margin:32px auto;padding:0 20px}
            .aysa-seo-appendix h2,.aysa-seo-appendix h3{margin-top:1.2em}
            .aysa-seo-appendix p,.aysa-seo-appendix li{line-height:1.65}
        </style>
        <?php
    }

    private function render_seo_appendix_for_current_post() {
        if (!$this->should_render_seo_appendix()) {
            return '';
        }

        $post_id = (int) get_queried_object_id();
        if ($post_id <= 0 || !empty($this->seo_appendix_rendered[$post_id])) {
            return '';
        }

        $html = trim((string) get_post_meta($post_id, '_aysa_seo_appendix_html', true));
        if ($html === '') {
            return '';
        }

        $this->seo_appendix_rendered[$post_id] = true;
        return '<section class="aysa-seo-appendix" data-aysa-seo-appendix="1">' . wp_kses_post($html) . '</section>';
    }

    private function render_seo_appendix_jsonld_for_current_post() {
        if (!$this->should_render_seo_appendix()) {
            return '';
        }

        $post_id = (int) get_queried_object_id();
        if ($post_id <= 0 || !empty($this->seo_appendix_jsonld_rendered[$post_id])) {
            return '';
        }

        $html = trim((string) get_post_meta($post_id, '_aysa_seo_appendix_html', true));
        if ($html === '' || stripos($html, '<dt') === false && stripos($html, '<h3') === false && stripos($html, 'faq') === false) {
            return '';
        }

        $jsonld = trim((string) get_post_meta($post_id, '_aysa_seo_appendix_faq_schema_jsonld', true));
        $decoded = json_decode($jsonld, true);
        if (!is_array($decoded)) {
            return '';
        }
        $type = $decoded['@type'] ?? '';
        if (is_array($type)) {
            $type = implode(' ', array_map('strval', $type));
        }
        if (stripos((string) $type, 'FAQPage') === false || empty($decoded['mainEntity']) || !is_array($decoded['mainEntity'])) {
            return '';
        }

        $this->seo_appendix_jsonld_rendered[$post_id] = true;
        return "\n<script type=\"application/ld+json\">" . wp_json_encode($decoded, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "</script>\n";
    }

    private function should_render_seo_appendix() {
        if (is_admin() || wp_doing_ajax() || is_feed() || is_preview() || !is_singular()) {
            return false;
        }
        if (function_exists('wp_is_json_request') && wp_is_json_request()) {
            return false;
        }
        if ((function_exists('is_cart') && is_cart()) || (function_exists('is_checkout') && is_checkout()) || (function_exists('is_account_page') && is_account_page())) {
            return false;
        }

        $post_id = (int) get_queried_object_id();
        if ($post_id <= 0) {
            return false;
        }

        return !$this->post_has_noindex($post_id);
    }

    private function post_has_noindex($post_id) {
        $yoast_noindex = get_post_meta($post_id, '_yoast_wpseo_meta-robots-noindex', true);
        if ((string) $yoast_noindex === '1') {
            return true;
        }

        $rank_math = get_post_meta($post_id, 'rank_math_robots', true);
        if (is_array($rank_math) && in_array('noindex', $rank_math, true)) {
            return true;
        }
        if (is_string($rank_math) && stripos($rank_math, 'noindex') !== false) {
            return true;
        }

        $aioseo_noindex = get_post_meta($post_id, '_aioseo_robots_noindex', true);
        return (string) $aioseo_noindex === '1';
    }
}
