<?php
// File: modules/slow-images.php

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', '/slow-images', [
        'methods'             => 'GET',
        'callback'            => 'myaio_sac_slow_images',
        'permission_callback' => 'myaio_sac_slow_images_permission',
    ]);
});

/**
 * Permission callback for slow-images endpoint
 * Uses the shared myaio_sac_validate_api_key() from includes/sac-utils.php
 */
if ( ! function_exists('myaio_sac_slow_images_permission') ) {
    function myaio_sac_slow_images_permission( 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_slow_images(WP_REST_Request $request) {
    $threshold_ms = 500; // Flag if load time > 500ms
    $urls = myaio_sac_get_all_crawlable_urls();
    $results = [];
    $slow_images_total = 0;

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

        if (is_wp_error($response)) continue;

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

        libxml_use_internal_errors(true);
        $dom = new DOMDocument();
        @$dom->loadHTML($html);
        $images = $dom->getElementsByTagName('img');

        $slow_images = [];

        foreach ($images as $img) {
            $src = $img->getAttribute('src');
            if (empty($src)) continue;

            // Make sure it's absolute URL
            if (strpos($src, 'http') !== 0) {
                $src = home_url($src);
            }

            // Measure loading time
            $start = microtime(true);
            $img_response = wp_remote_get($src, ['timeout' => 5]);
            $end = microtime(true);
            $duration_ms = round(($end - $start) * 1000, 2);

            if (!is_wp_error($img_response) && $duration_ms > $threshold_ms) {
                $slow_images[] = [
                    'src' => $src,
                    'load_time_ms' => $duration_ms,
                ];
            }
        }

        if (!empty($slow_images)) {
            $results[] = [
                'page' => $page_url,
                'slow_images' => $slow_images,
            ];
            $slow_images_total += count($slow_images);
        }
    }

    return rest_ensure_response([
        'total_pages_checked' => count($urls),
        'total_slow_images_found' => $slow_images_total,
        'slow_images' => $results
    ]);
}
