<?php
/**
 * MYAIO Schema Markup API.
 *
 * 1. GET all pages/posts schema markup.
 * 2. GET single URL schema markup.
 * 3. INSERT/REPLACE schema markup.
 * 4. REMOVE duplicate schema markup.
 */

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

require_once plugin_dir_path( __FILE__ ) . '../includes/sac-utils.php';

add_action(
    'rest_api_init',
    function () {

        /**
         * GET SCHEMA MARKUP
         *
         * Optional:
         * ?url=https://example.com/about
         */
        register_rest_route(
            'myaio/v1',
            '/schema-markup',
            array(
                'methods'             => 'GET',
                'callback'            => 'myaio_get_schema_markup',
                'permission_callback' => 'myaio_sac_rest_permission_check',
            )
        );

        /**
         * INSERT / UPDATE SCHEMA
         */
        register_rest_route(
            'myaio/v1',
            '/schema-markup',
            array(
                'methods'             => 'POST',
                'callback'            => 'myaio_insert_schema_markup',
                'permission_callback' => 'myaio_sac_rest_permission_check',
                'args'                => array(
                    'url' => array(
                        'required'          => true,
                        'sanitize_callback' => 'esc_url_raw',
                    ),
                    'schema' => array(
                        'required' => true,
                    ),
                ),
            )
        );
    }
);

/**
 * =========================================================
 * GET SCHEMA MARKUP
 * =========================================================
 */
function myaio_get_schema_markup( WP_REST_Request $request ) {

    $url = esc_url_raw( $request->get_param( 'url' ) );

    // SINGLE URL.
    if ( ! empty( $url ) ) {

        $record = myaio_extract_schema_from_url( $url );

        return rest_ensure_response(
            array(
                'success' => true,
                'count'   => 1,
                'data'    => array( $record ),
            )
        );
    }

    // ALL POSTS + PAGES.
    $posts = get_posts(
        array(
            'post_type'      => array( 'post', 'page' ),
            'post_status'    => 'publish',
            'posts_per_page' => -1,
        )
    );

    $results = array();

    foreach ( $posts as $post ) {

        $results[] = myaio_extract_schema_from_url( get_permalink( $post->ID ) );
    }

    return rest_ensure_response(
        array(
            'success' => true,
            'count'   => count( $results ),
            'data'    => $results,
        )
    );
}

/**
 * =========================================================
 * EXTRACT SCHEMA FROM URL
 * =========================================================
 */
function myaio_extract_schema_from_url( $url ) {

    $response = wp_remote_get(
        $url,
        array(
            'timeout' => 20,
        )
    );

    if ( is_wp_error( $response ) ) {

        return array(
            'url'     => $url,
            'success' => false,
            'error'   => $response->get_error_message(),
        );
    }

    $html = wp_remote_retrieve_body( $response );

    preg_match_all(
        '/<script[^>]*type=["\']application\/ld\+json["\'][^>]*>(.*?)<\/script>/is',
        $html,
        $matches
    );

    $schemas = array();

    if ( ! empty( $matches[1] ) ) {

        foreach ( $matches[1] as $schema ) {

            $decoded = json_decode( trim( $schema ), true );

            $schemas[] = array(
                'raw'     => trim( $schema ),
                'decoded' => $decoded,
            );
        }
    }

    $post_id = url_to_postid( $url );

    return array(
        'success'       => true,
        'post_id'       => $post_id,
        'url'           => $url,
        'title'         => get_the_title( $post_id ),
        'type'          => get_post_type( $post_id ),
        'schemas'       => $schemas,
        'schema_count'  => count( $schemas ),
        
    );
}



/**
 * =========================================================
 * INSERT / REPLACE SCHEMA MARKUP
 * =========================================================
 */
function myaio_insert_schema_markup( WP_REST_Request $request ) {

    $url    = esc_url_raw( $request->get_param( 'url' ) );
    $schema = $request->get_param( 'schema' );

    if ( empty( $url ) ) {

        return new WP_REST_Response(
            array(
                'success' => false,
                'message' => 'URL is required.',
            ),
            400
        );
    }

    $post_id = url_to_postid( $url );

    if ( ! $post_id ) {

        return new WP_REST_Response(
            array(
                'success' => false,
                'message' => 'Post/Page not found.',
            ),
            404
        );
    }

    // REMOVE OLD SCHEMA.
    delete_post_meta( $post_id, '_myaio_custom_schema' );

    // REMOVE RANK MATH SCHEMA.
    delete_post_meta( $post_id, 'rank_math_rich_snippet' );
    delete_post_meta( $post_id, 'rank_math_schema_Service' );

    // REMOVE YOAST SCHEMA.
    delete_post_meta( $post_id, '_yoast_wpseo_schema_page_type' );

    // SAVE NEW SCHEMA.
    update_post_meta(
        $post_id,
        '_myaio_custom_schema',
        wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT )
    );

    return rest_ensure_response(
        array(
            'success' => true,
            'message' => 'Schema markup inserted successfully.',
            'post_id' => $post_id,
            'url'     => $url,
        )
    );
}

/**
 * =========================================================
 * PRINT CUSTOM SCHEMA IN FRONTEND
 * =========================================================
 */
add_action(
    'wp_head',
    function () {

        if ( is_admin() ) {
            return;
        }

        global $post;

        if ( empty( $post ) ) {
            return;
        }

        $schema = get_post_meta( $post->ID, '_myaio_custom_schema', true );

        if ( empty( $schema ) ) {
            return;
        }

        // DISABLE YOAST SCHEMA.
        add_filter( 'wpseo_json_ld_output', '__return_false' );

        // DISABLE RANK MATH SCHEMA.
        add_filter( 'rank_math/json_ld', '__return_empty_array', 99 );

        echo '<script type="application/ld+json">';
        echo wp_kses_post( $schema );
        echo '</script>';
    },
    1
);