<?php
/**
 * SEO AI Pro read-only Rank Math bridge.
 * Add this code (without the opening PHP tag) to an existing child theme's
 * functions.php or your existing site snippets facility. Do not install another
 * SEO plugin. This registers only an authenticated GET route, and changes no
 * content, settings, metadata, or public REST responses.
 */
add_action('rest_api_init', function () {
    register_rest_route('seo-ai-pro/v1', '/metadata/(?P<id>\d+)', array(
        'methods' => WP_REST_Server::READABLE,
        'permission_callback' => function (WP_REST_Request $request) {
            $id = (int) $request['id'];
            return is_user_logged_in() && current_user_can('edit_post', $id);
        },
        'callback' => function (WP_REST_Request $request) {
            $id = (int) $request['id'];
            $post = get_post($id);
            if (!$post || !in_array($post->post_type, array('post', 'page'), true)) {
                return new WP_Error('invalid_target', 'Only posts and pages are supported.', array('status' => 404));
            }
            $response = new WP_REST_Response(array(
                'id' => $id,
                'fields' => array(
                    'rank_math_title' => (string) get_post_meta($id, 'rank_math_title', true),
                    'rank_math_description' => (string) get_post_meta($id, 'rank_math_description', true),
                ),
            ));
            $response->header('Cache-Control', 'private, no-store');
            return $response;
        },
        'args' => array('id' => array('required' => true, 'validate_callback' => function ($value) {
            return ctype_digit((string) $value) && (int) $value > 0;
        })),
    ));
});