<?php
/**
 * FajaedeSEO Frontend Schema.org (JSON-LD)
 */

defined('ABSPATH') or exit;

function fajaedeseo_render_schema() {
    if (get_option('fajaedeseo_disable_schema') === '1') {
        return;
    }

    $schema = [];

    // Ophalen van Social Media URLs voor Schema
    $social_profiles = [];
    $fb = get_option('fajaedeseo_facebook_handle');
    if ($fb) $social_profiles[] = filter_var($fb, FILTER_VALIDATE_URL) ? $fb : 'https://www.facebook.com/' . ltrim($fb, '@');
    
    $tw = get_option('fajaedeseo_twitter_handle');
    if ($tw) $social_profiles[] = filter_var($tw, FILTER_VALIDATE_URL) ? $tw : 'https://twitter.com/' . ltrim($tw, '@');

    // Organisatie Schema met Social Links
    $org_schema = [
        "@type" => "Organization",
        "@id"   => home_url('/#organization'),
        "name"  => get_bloginfo('name'),
        "url"   => home_url('/')
    ];
    if (!empty($social_profiles)) {
        $org_schema["sameAs"] = $social_profiles;
    }

    // 1. Basis WebSite Schema voor de homepage
    if (is_front_page() || is_home()) {
        $schema[] = $org_schema;
        $schema[] = [
            "@type"    => "WebSite",
            "@id"      => home_url('/#website'),
            "name"     => get_bloginfo('name'),
            "url"      => home_url('/'),
            "publisher"=> ["@id" => home_url('/#organization')],
            "potentialAction" => [
                "@type"       => "SearchAction",
                "target"      => home_url('/?s={search_term_string}'),
                "query-input" => "required name=search_term_string"
            ]
        ];
    } else {
        // Basis WebSite schema voor alle andere pagina's (nodig als referentie)
        $schema[] = $org_schema;
        $schema[] = [
            "@type"    => "WebSite",
            "@id"      => home_url('/#website'),
            "name"     => get_bloginfo('name'),
            "url"      => home_url('/'),
            "publisher"=> ["@id" => home_url('/#organization')]
        ];
    }

    // 2. Specifiek schema voor berichten/pagina's
    if (is_singular()) {
        $post_id = get_the_ID();
        $type    = get_post_meta($post_id, '_fajaedeseo_schema_type', true) ?: 'Article';
        $author_id = get_post_field('post_author', $post_id);
        $author_name = $author_id ? get_the_author_meta('display_name', $author_id) : get_bloginfo('name');
        
        // Degradatie: Als de licentie verlopen is (Free plan), vallen we terug op het standaard 'Article' schema.
        // Dit verwijdert de geavanceerde Rich Snippets in Google als stimulans om te verlengen.
        $plan = class_exists('\FajaedeSEO_Pro_License') ? \FajaedeSEO_Pro_License::get_plan_level() : 'free';
        
        $premium_schema_types = [
            'FAQPage', 'HowTo', 'Product', 'Service', 'Review',
            'LocalBusiness', 'Event', 'Recipe', 'SoftwareApplication',
            'VideoObject', 'Course', 'JobPosting', 'MedicalCondition',
            'Dataset', 'Book', 'Movie', 'MusicAlbum', 'NewsArticle',
            'PodcastEpisode', 'Quiz', 'Restaurant', 'QAPage', 'ProfilePage'
        ];

        if ( $plan === 'free' && in_array($type, $premium_schema_types) ) {
            $type = 'Article';
        }

        $post_schema = [
            "@type"    => $type,
            "@id"      => get_permalink() . '#' . strtolower($type),
            "isPartOf" => ["@id" => home_url('/#website')],
            "publisher"=> ["@id" => home_url('/#organization')],
            "headline" => get_the_title(),
            "url"      => get_permalink(),
            "datePublished" => get_the_date('c'),
            "dateModified"  => get_the_modified_date('c'),
            "author" => [
                "@type" => "Person",
                "name"  => $author_name
            ]
        ];

        // Automatisch genereren van geavanceerde FAQPage / HowTo Schema entiteiten
        if (in_array($type, ['FAQPage', 'HowTo'])) {
            $content = get_post_field('post_content', $post_id);
            
            $structured_parts = [];
            
            // 1. Native WordPress Block Parser (Voor Gutenberg & AI Blocks)
            if (function_exists('parse_blocks') && has_blocks($content)) {
                $blocks = parse_blocks($content);
                
                // Helper function to flatten nested blocks
                $flatten_blocks = function($blocks) use (&$flatten_blocks) {
                    $flat = [];
                    foreach ($blocks as $block) {
                        if (!empty($block['blockName'])) {
                            $flat[] = $block;
                        }
                        if (!empty($block['innerBlocks'])) {
                            $flat = array_merge($flat, $flatten_blocks($block['innerBlocks']));
                        }
                    }
                    return $flat;
                };
                
                $flat_blocks = $flatten_blocks($blocks);
                
                $current_q = '';
                $current_a = '';
                
                foreach ($flat_blocks as $block) {
                    if (empty(trim($block['innerHTML']))) continue;
                    
                    if (in_array($block['blockName'], ['core/heading', 'core/quote'])) {
                        if (!empty($current_q) && !empty($current_a)) {
                            $structured_parts[] = ['q' => trim($current_q), 'a' => trim(preg_replace('/\s+/', ' ', $current_a))];
                        }
                        $current_q = wp_strip_all_tags($block['innerHTML']);
                        $current_a = '';
                    } elseif (in_array($block['blockName'], ['core/paragraph', 'core/list'])) {
                        $inner = trim($block['innerHTML']);
                        
                        // 1. Check if the block is PURELY a question
                        if (preg_match('/^(?:<(?:p|ul|ol|li|div)[^>]*>)*\s*<(strong|b)[^>]*>(.*?)<\/\1>\s*(?:<\/(?:p|ul|ol|li|div)>)*$/is', $inner, $matches)) {
                            if (!empty($current_q) && !empty($current_a)) {
                                $structured_parts[] = ['q' => trim($current_q), 'a' => trim(preg_replace('/\s+/', ' ', $current_a))];
                            }
                            $current_q = wp_strip_all_tags($matches[2]);
                            $current_a = '';
                        } 
                        // 2. Check for inline Q&A within the block (e.g., <li><strong>Q:</strong> A</li>)
                        elseif (preg_match_all('/<(p|li|div)[^>]*>\s*<(strong|b)[^>]*>(.*?)<\/\2>(.+?)<\/\1>/is', $inner, $matches, PREG_SET_ORDER)) {
                            if (!empty($current_q) && !empty($current_a)) {
                                $structured_parts[] = ['q' => trim($current_q), 'a' => trim(preg_replace('/\s+/', ' ', $current_a))];
                                $current_q = '';
                                $current_a = '';
                            }
                            foreach ($matches as $match) {
                                $q_text = trim(wp_strip_all_tags($match[3]));
                                $a_text = trim(preg_replace('/\s+/', ' ', wp_strip_all_tags(str_replace(['<br', '<li'], [' <br', ' <li'], $match[4]))));
                                if (!empty($q_text) && !empty($a_text)) {
                                    $structured_parts[] = ['q' => $q_text, 'a' => $a_text];
                                }
                            }
                        } 
                        // 3. Otherwise, append to current answer
                        elseif (!empty($current_q)) {
                            $current_a .= ' ' . wp_strip_all_tags(str_replace(['<br', '<li'], [' <br', ' <li'], $inner));
                        }
                    }
                }
                if (!empty($current_q) && !empty($current_a)) {
                    $structured_parts[] = ['q' => trim($current_q), 'a' => trim(preg_replace('/\s+/', ' ', $current_a))];
                }
            }
            
            // 2. Regex Fallback (Voor Classic Editor, Elementor & Shortcodes)
            if (empty($structured_parts)) {
                $content_html = do_shortcode($content); 
                // Add wpautop to ensure raw text gets <p> tags for the regex to match
                $content_html = wpautop($content_html);
                
                $parts = preg_split('/(<(?:h[2-6]|summary)[^>]*>.*?<\/(?:h[2-6]|summary)>|<(?:p|li|div)[^>]*>\s*<(?:strong|b)[^>]*>.*?<\/(?:strong|b)>\s*<\/(?:p|li|div)>)/is', $content_html, -1, PREG_SPLIT_DELIM_CAPTURE);
                if (count($parts) > 1) {
                    for ($i = 1; $i < count($parts); $i += 2) {
                        $q = trim(wp_strip_all_tags($parts[$i]));
                        $a = trim(preg_replace('/\s+/', ' ', wp_strip_all_tags(str_replace(['<p', '<br', '<li', '<div'], [' <p', ' <br', ' <li', ' <div'], $parts[$i + 1] ?? ''))));
                        if (!empty($q) && !empty($a)) {
                            $structured_parts[] = ['q' => $q, 'a' => $a];
                        }
                    }
                }
                
                // Fallback for Q&A in the same paragraph, list item or div: <p><strong>Q:</strong> A</p>
                if (empty($structured_parts)) {
                    if (preg_match_all('/<(p|li|div)[^>]*>\s*<(strong|b)[^>]*>(.*?)<\/\2>(.+?)<\/\1>/is', $content_html, $matches, PREG_SET_ORDER)) {
                        foreach ($matches as $match) {
                            $q = trim(wp_strip_all_tags($match[3]));
                            $a = trim(preg_replace('/\s+/', ' ', wp_strip_all_tags(str_replace(['<br', '<li'], [' <br', ' <li'], $match[4]))));
                            if (!empty($q) && !empty($a)) {
                                $structured_parts[] = ['q' => $q, 'a' => $a];
                            }
                        }
                    }
                }
            }
            
            // 3. Bouw het Schema op
            if ($type === 'FAQPage' && !empty($structured_parts)) {
                $post_schema['mainEntity'] = [];
                foreach ($structured_parts as $part) {
                    $post_schema['mainEntity'][] = [
                        "@type" => "Question",
                        "name" => $part['q'],
                        "acceptedAnswer" => [
                            "@type" => "Answer",
                            "text" => $part['a']
                        ]
                    ];
                }
            } elseif ($type === 'HowTo' && !empty($structured_parts)) {
                $post_schema['step'] = [];
                foreach ($structured_parts as $part) {
                    $post_schema['step'][] = [
                        "@type" => "HowToStep",
                        "name" => $part['q'], // Gebruik 'q' als stapnaam
                        "text" => $part['a']  // Gebruik 'a' als staptekst
                    ];
                }
            }
        }
        
        // 4. AI Schema Extractor voor complexe types (Recepten, Evenementen, etc.)
        $complex_types = ['Recipe', 'Event', 'JobPosting', 'LocalBusiness', 'SoftwareApplication', 'Product', 'Course', 'Movie', 'Book', 'PodcastEpisode'];
        if (in_array($type, $complex_types) && class_exists('\FajaedeSEO_AI_Service_Manager')) {
            $content = get_post_field('post_content', $post_id);
            $ai_schema_attrs = \FajaedeSEO_AI_Service_Manager::generate_schema_attributes($type, $content);
            if (!empty($ai_schema_attrs) && is_array($ai_schema_attrs)) {
                $post_schema = array_merge($post_schema, $ai_schema_attrs);
            }
        }

        $schema[] = $post_schema;
    }

    if (!empty($schema)) {
        $output = [
            "@context" => "https://schema.org",
            "@graph"   => $schema
        ];
        $json_encoded = wp_json_encode($output, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        if ($json_encoded) {
            echo "\n<!-- FajaedeSEO Schema Start -->\n";
            echo '<script type="application/ld+json">' . $json_encoded . '</script>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo "\n<!-- FajaedeSEO Schema End -->\n";
        }
    }
}