<?php
// File: modules/knowledge-graph-check.php

defined('ABSPATH') || exit;

// Shared key validation used across ALL modules
require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/check-knowledge-graph', [
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'myaio_sac_check_knowledge_graph',
        'permission_callback' => 'myaio_sac_rest_permission_check',
    ]);
});

/**
 * Safely extract JSON-LD blocks using DOM parsing (no regex, no script execution).
 * Returns an array of decoded JSON objects.
 */
if (!function_exists('myaio_sac_extract_json_ld_blocks')) {
    function myaio_sac_extract_json_ld_blocks($html) {
        $schemas = [];

        if (empty($html) || !is_string($html)) {
            return $schemas;
        }

        // DOMDocument can emit warnings on malformed HTML
        libxml_use_internal_errors(true);

        $dom = new DOMDocument();

        // Prefix encoding to support UTF-8 consistently
        $loaded = $dom->loadHTML('<?xml encoding="utf-8" ?>' . $html, LIBXML_NOWARNING | LIBXML_NOERROR);
        if (!$loaded) {
            libxml_clear_errors();
            return $schemas;
        }

        $scripts = $dom->getElementsByTagName('script');

        foreach ($scripts as $script) {
            $type = strtolower(trim((string) $script->getAttribute('type')));
            if ($type !== 'application/ld+json') {
                continue;
            }

            $json = trim((string) $script->textContent);
            if ($json === '') {
                continue;
            }

            $data = json_decode($json, true);
            if (json_last_error() === JSON_ERROR_NONE && !empty($data)) {
                $schemas[] = $data;
            }
        }

        libxml_clear_errors();

        return $schemas;
    }
}

/**
 * Checks if Knowledge Graph structured data is present on the homepage.
 * Output MUST remain same.
 */
if (!function_exists('myaio_sac_check_knowledge_graph')) {
    function myaio_sac_check_knowledge_graph(WP_REST_Request $request) {
        $homepage = home_url('/');

        $res = wp_safe_remote_get($homepage, [
            'timeout'     => 10,
            'redirection' => 3,
            'headers'     => [
                'User-Agent' => 'MyAIO-SEO-KGCheck/1.0; ' . home_url(),
            ],
        ]);

        if (is_wp_error($res)) {
            return new WP_REST_Response([
                'available' => false,
                'error'     => 'Failed to fetch homepage: ' . $res->get_error_message(),
            ], 500);
        }

        $html = (string) wp_remote_retrieve_body($res);
        if ($html === '') {
            return new WP_REST_Response([
                'available' => false,
                'error'     => 'Empty homepage response.',
            ], 500);
        }

        // Extract JSON-LD structured data (DOM-based; no regex; no script output/execution)
        $json_ld_blocks = myaio_sac_extract_json_ld_blocks($html);

        $found   = false;
        $details = [];

        foreach ((array) $json_ld_blocks as $data) {

            // Case 1: single object with @type
            if (is_array($data) && isset($data['@type'])) {
                $types = is_array($data['@type']) ? $data['@type'] : [$data['@type']];
                foreach ($types as $type) {
                    if (in_array($type, ['Organization', 'LocalBusiness', 'Person'], true)) {
                        $found = true;
                        $details[] = $data;
                        break 2;
                    }
                }
            }

            // Case 2: array of items
            if (is_array($data) && isset($data[0]) && is_array($data[0])) {
                foreach ($data as $item) {
                    if (is_array($item) && isset($item['@type']) && in_array($item['@type'], ['Organization', 'LocalBusiness', 'Person'], true)) {
                        $found = true;
                        $details[] = $item;
                        break 2;
                    }
                }
            }
        }

        return new WP_REST_Response([
            'homepage'        => $homepage,
            'knowledge_graph' => $found ? 'Present' : 'Not Found',
            'details'         => $found ? $details : [],
        ], 200);
    }
}
