<?php
// File: modules/breadcrumb-schema.php
// Breadcrumb Schema Checker and Generator

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

// Use the 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', '/breadcrumb-check', [
        'methods'             => 'GET',
        'callback'            => 'myaio_sac_check_breadcrumb_across_site',
        'permission_callback' => 'myaio_sac_breadcrumb_permission_callback',
    ]);

    register_rest_route('myaio/v1', '/breadcrumb-generate', [
        'methods'             => 'POST',
        'callback'            => 'myaio_sac_generate_breadcrumb_for_url',
        'permission_callback' => 'myaio_sac_breadcrumb_permission_callback',
    ]);
});

/**
 * Permission callback for breadcrumb endpoints
 * Uses the shared myaio_sac_validate_api_key() from includes/sac-utils.php
 */
if ( ! function_exists('myaio_sac_breadcrumb_permission_callback') ) {
    function myaio_sac_breadcrumb_permission_callback( WP_REST_Request $request ) {
        if ( function_exists('myaio_sac_validate_api_key') && myaio_sac_validate_api_key($request) ) {
            return true;
        }
        return new WP_Error('unauthorized', 'Invalid or unverified API key', ['status' => 401]);
    }
}

function myaio_sac_check_breadcrumb_across_site( WP_REST_Request $request ) {
    $urls = myaio_sac_get_all_site_urls();
    $missing = [];

    foreach ($urls as $entry) {
        $url = $entry['url'];
        $response = wp_remote_get($url);

        if (is_wp_error($response)) {
            continue;
        }

        $html = wp_remote_retrieve_body($response);
        if (empty($html)) {
            continue;
        }

        if (
            strpos($html, '"@type":"BreadcrumbList"') === false &&
            strpos($html, 'schema.org/BreadcrumbList') === false
        ) {
            $missing[] = esc_url_raw($url);
        }
    }

    return rest_ensure_response([
        'missing_schema_pages' => $missing,
        'checked'              => count($urls),
        'missing_count'        => count($missing),
    ]);
}

function myaio_sac_generate_breadcrumb_for_url( WP_REST_Request $request ) {
    $raw_url = $request->get_param('url');
    $url = is_string($raw_url) ? esc_url_raw(wp_unslash($raw_url)) : '';

    if (empty($url)) {
        return new WP_REST_Response(['error' => 'Missing URL'], 400);
    }

    $parsed_url = wp_parse_url($url);
    $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
    $parts = array_filter(explode('/', $path));
    $breadcrumbs = [];

    $base = home_url();
    $breadcrumbs[] = [
        '@type'    => 'ListItem',
        'position' => 1,
        'name'     => 'Home',
        'item'     => $base,
    ];

    $current = $base;
    $pos = 2;

    foreach ($parts as $part) {
        $current .= '/' . $part;
        $breadcrumbs[] = [
            '@type'    => 'ListItem',
            'position' => $pos++,
            'name'     => ucwords(str_replace(['-', '_'], ' ', $part)),
            'item'     => esc_url_raw($current),
        ];
    }

    $schema = [
        '@context'        => 'https://schema.org',
        '@type'           => 'BreadcrumbList',
        'itemListElement' => $breadcrumbs,
    ];

    return rest_ensure_response([
        'generated_schema' => $schema,
    ]);
}
