<?php
// File: modules/amp-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', '/is-amp-active', [
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'myaio_sac_check_amp_status',
        'permission_callback' => 'myaio_sac_rest_permission_check',
    ]);
});

/**
 * Check if AMP is active on the homepage
 * Output MUST remain same.
 */
if (!function_exists('myaio_sac_check_amp_status')) {
    function myaio_sac_check_amp_status(WP_REST_Request $request) {
        $homepage_url = home_url('/');

        // Safer request with timeout/redirection; does not change output
        $res = wp_safe_remote_get($homepage_url, [
            'timeout'     => 12,
            'redirection' => 3,
            'headers'     => [
                'User-Agent' => 'MyAIO-SEO-AMPCheck/1.0; ' . home_url(),
            ],
        ]);

        if (is_wp_error($res)) {
            return new WP_REST_Response([
                'status'  => 'error',
                'message' => 'Failed to fetch homepage',
                'details' => $res->get_error_message()
            ], 500);
        }

        $html = (string) wp_remote_retrieve_body($res);
        if ($html === '') {
            // Keep same error shape/meaning
            return new WP_REST_Response([
                'status'  => 'error',
                'message' => 'Failed to fetch homepage',
                'details' => 'Empty response body'
            ], 500);
        }

        $is_amp = false;
        $debug  = [];

        if (preg_match('/<html[^>]+(amp|⚡)/i', $html)) {
            $is_amp = true;
            $debug[] = 'HTML tag contains amp or ⚡';
        }

        if (strpos($html, 'https://cdn.ampproject.org/v0.js') !== false) {
            $is_amp = true;
            $debug[] = 'AMP runtime script detected';
        }

        return new WP_REST_Response([
            'homepage_url' => $homepage_url,
            'amp_status'   => $is_amp ? 'active' : 'not active',
            'debug_info'   => $debug
        ], 200);
    }
}
