<?php
/**
 * Plugin Name: WordPress Doctor
 * Description: A lightweight website health checker by DesignoPage.
 * Version: 2.0.25
 * Author: DesignoPage
 * License: GPL-2.0-or-later
 */

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

define( 'WPD_VERSION', '2.0.25' );

function wpd_register_shortcode() {
    add_shortcode( 'wordpress_doctor', 'wpd_render_shortcode' );
}
add_action( 'init', 'wpd_register_shortcode' );

/** Normalize and validate a submitted public website URL. */
function wpd_normalize_url( $input ) {
    $input = trim( (string) $input );
    if ( $input === '' || preg_match( '/[\s\x00-\x1F\x7F]/', $input ) || strlen( $input ) > 2048 ) {
        return new WP_Error( 'wpd_invalid_url', 'Please enter a valid website address.' );
    }
    if ( ! preg_match( '#^https?://#i', $input ) ) { $input = 'https://' . $input; }
    $url = esc_url_raw( $input, array( 'http', 'https' ) );
    $parts = wp_parse_url( $url );
    if ( ! $url || ! is_array( $parts ) || empty( $parts['scheme'] ) || empty( $parts['host'] ) ||
        ! in_array( strtolower( $parts['scheme'] ), array( 'http', 'https' ), true ) || isset( $parts['user'] ) || isset( $parts['pass'] ) ) {
        return new WP_Error( 'wpd_invalid_url', 'Please enter a valid website address.' );
    }
    $host = strtolower( rtrim( $parts['host'], '.' ) );
    if ( $host === 'localhost' || substr( $host, -10 ) === '.localhost' || substr( $host, -6 ) === '.local' ||
        substr( $host, -9 ) === '.internal' || filter_var( $host, FILTER_VALIDATE_IP ) ) {
        return new WP_Error( 'wpd_unsafe_url', 'Please enter a public website domain, not a local address or IP address.' );
    }
    if ( ! wp_http_validate_url( $url ) ) {
        return new WP_Error( 'wpd_unsafe_url', 'This address could not be validated as a safe public website.' );
    }
    return $url;
}

/** Read quoted or unquoted HTML attributes, independent of attribute order. */
function wpd_get_attribute( $tag, $attribute ) {
    $pattern = '/(?:^|\s)' . preg_quote( $attribute, '/' ) . '\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s>]+))/i';
    if ( preg_match( $pattern, $tag, $m ) ) {
        $value = isset( $m[1] ) && $m[1] !== '' ? $m[1] : ( ( isset( $m[2] ) && $m[2] !== '' ) ? $m[2] : ( $m[3] ?? '' ) );
        return html_entity_decode( $value, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
    }
    return '';
}

/** Return metadata lookup details so absent tags and empty content are distinct. */
function wpd_find_meta_content( $html, $name ) {
    $found = false;
    $empty_found = false;
    $values = array();
    if ( preg_match_all( '/<meta\b[^>]*>/i', $html, $matches ) ) {
        foreach ( $matches[0] as $tag ) {
            $tag_name = wpd_get_attribute( $tag, 'name' );
            $property = wpd_get_attribute( $tag, 'property' );
            if ( strcasecmp( $tag_name, $name ) === 0 || strcasecmp( $property, $name ) === 0 ) {
                $found = true;
                $content = trim( wpd_get_attribute( $tag, 'content' ) );
                if ( $content !== '' ) { $values[] = $content; } else { $empty_found = true; }
            }
        }
    }
    return array( 'found' => $found, 'empty' => $empty_found, 'values' => $values );
}

/** Backward-compatible helper used by viewport checks. */
function wpd_get_meta_content( $html, $name ) {
    $meta = wpd_find_meta_content( $html, $name );
    return ! empty( $meta['values'] ) ? $meta['values'][0] : '';
}

function wpd_result_item( $name, $status, $detail ) {
    return array( 'name' => $name, 'status' => $status, 'detail' => $detail );
}

/** Inspect a public HTTPS certificate when PHP OpenSSL and outbound TLS access are available. */
function wpd_inspect_ssl_certificate( $url ) {
    if ( ! function_exists( 'openssl_x509_parse' ) || ! function_exists( 'stream_socket_client' ) ) {
        return array( 'status' => 'Unable to verify', 'detail' => 'The server environment does not provide the PHP OpenSSL/socket functions needed for this certificate check.' );
    }
    $parts = wp_parse_url( $url );
    if ( ! is_array( $parts ) || strtolower( (string) ( $parts['scheme'] ?? '' ) ) !== 'https' || empty( $parts['host'] ) ) {
        return array( 'status' => 'Unable to verify', 'detail' => 'A certificate check requires an HTTPS website address.' );
    }
    $host = (string) $parts['host'];
    $port = ! empty( $parts['port'] ) ? (int) $parts['port'] : 443;
    // Resolve once and pin the socket to a public IPv4 address to reduce DNS-rebinding/SSRF risk.
    $resolved_ips = function_exists( 'gethostbynamel' ) ? @gethostbynamel( $host ) : false;
    $public_ip = '';
    foreach ( (array) $resolved_ips as $resolved_ip ) {
        if ( filter_var( $resolved_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) { $public_ip = $resolved_ip; break; }
    }
    if ( $public_ip === '' ) {
        return array( 'status' => 'Unable to verify', 'detail' => 'The scanner could not resolve a public IPv4 address for a safe, pinned certificate connection. The website may still support HTTPS; this certificate check was skipped.' );
    }
    $context = stream_context_create( array( 'ssl' => array(
        'capture_peer_cert' => true,
        'verify_peer' => true,
        'verify_peer_name' => true,
        'peer_name' => $host,
        'SNI_enabled' => true,
    ) ) );
    $errno = 0; $errstr = '';
    $socket = @stream_socket_client( 'ssl://' . $public_ip . ':' . $port, $errno, $errstr, 4, STREAM_CLIENT_CONNECT, $context );
    if ( ! $socket ) {
        return array( 'status' => 'Unable to verify', 'detail' => 'A verified TLS connection could not be established from the scanner server. This may be caused by outbound connection restrictions or a certificate/hostname problem; it is not enough on its own to diagnose the cause.' );
    }
    $params = stream_context_get_params( $socket );
    fclose( $socket );
    $certificate = $params['options']['ssl']['peer_certificate'] ?? null;
    if ( ! $certificate ) {
        return array( 'status' => 'Unable to verify', 'detail' => 'The TLS connection did not expose a certificate for inspection.' );
    }
    $parsed = @openssl_x509_parse( $certificate );
    if ( ! is_array( $parsed ) || empty( $parsed['validTo_time_t'] ) ) {
        return array( 'status' => 'Unable to verify', 'detail' => 'The certificate was connected to successfully but its expiry date could not be read.' );
    }
    $expiry = (int) $parsed['validTo_time_t'];
    $days = (int) floor( ( $expiry - time() ) / DAY_IN_SECONDS );
    $date = gmdate( 'Y-m-d H:i:s', $expiry ) . ' UTC';
    if ( $days < 0 ) {
        return array( 'status' => 'Issue found', 'detail' => 'The verified TLS certificate appears to have expired on ' . $date . '. Confirm the certificate from a browser or hosting control panel and renew it if necessary.' );
    }
    if ( $days <= 21 ) {
        return array( 'status' => 'Detected — Please verify', 'detail' => 'The verified TLS certificate expires on ' . $date . ' (about ' . $days . ' day(s) remaining). Arrange renewal if it is not already automated.' );
    }
    return array( 'status' => 'Pass', 'detail' => 'A verified TLS certificate was retrieved. Its parsed expiry date is ' . $date . ' (about ' . $days . ' day(s) remaining). This check reflects the scanner server’s TLS connection at scan time.' );
}

/** Determine whether a directive token appears in any supplied value. */
function wpd_has_directive_token( $values, $token ) {
    foreach ( (array) $values as $value ) {
        if ( preg_match( '/(?:^|[\s,;])' . preg_quote( $token, '/' ) . '(?:$|[\s,;])/i', (string) $value ) ) { return true; }
    }
    return false;
}


/** Create a normalized origin key, treating explicit default ports as implicit. */
function wpd_url_origin_key( $url ) {
    $parts = wp_parse_url( (string) $url );
    if ( ! is_array( $parts ) || empty( $parts['scheme'] ) || empty( $parts['host'] ) ) { return ''; }
    $scheme = strtolower( $parts['scheme'] );
    $host = strtolower( $parts['host'] );
    $port = isset( $parts['port'] ) ? (int) $parts['port'] : 0;
    if ( ( $scheme === 'http' && $port === 80 ) || ( $scheme === 'https' && $port === 443 ) ) { $port = 0; }
    return $scheme . '://' . $host . ( $port ? ':' . $port : '' );
}

/** Create a comparison key for URLs without changing the URL used for requests.
 * Treat host/scheme case, default ports, fragments, and a trailing slash as equivalent.
 * Preserve query strings because they may identify different content.
 */
function wpd_url_comparison_key( $url ) {
    $parts = wp_parse_url( (string) $url );
    if ( ! is_array( $parts ) || empty( $parts['scheme'] ) || empty( $parts['host'] ) ) { return ''; }
    $scheme = strtolower( $parts['scheme'] );
    $host = strtolower( $parts['host'] );
    $port = isset( $parts['port'] ) ? (int) $parts['port'] : 0;
    if ( ( $scheme === 'http' && $port === 80 ) || ( $scheme === 'https' && $port === 443 ) ) { $port = 0; }
    $path = isset( $parts['path'] ) && $parts['path'] !== '' ? $parts['path'] : '/';
    if ( $path !== '/' ) { $path = rtrim( $path, '/' ); if ( $path === '' ) { $path = '/'; } }
    $query = isset( $parts['query'] ) ? '?' . $parts['query'] : '';
    return $scheme . '://' . $host . ( $port ? ':' . $port : '' ) . $path . $query;
}

/** Resolve a relative HTTP(S) resource URL without permitting non-web schemes. */
function wpd_resolve_reference( $base, $reference ) {
    $reference = trim( html_entity_decode( (string) $reference, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) );
    if ( $reference === '' || $reference[0] === '#' || preg_match( '/^(?:data|javascript|mailto|tel):/i', $reference ) ) { return ''; }
    if ( preg_match( '#^https?://#i', $reference ) ) { $resolved = $reference; }
    elseif ( strpos( $reference, '//' ) === 0 ) {
        $parts = wp_parse_url( $base ); $resolved = ( isset( $parts['scheme'] ) ? $parts['scheme'] : 'https' ) . ':' . $reference;
    } else {
        $parts = wp_parse_url( $base );
        if ( ! is_array( $parts ) || empty( $parts['scheme'] ) || empty( $parts['host'] ) ) { return ''; }
        $origin = $parts['scheme'] . '://' . $parts['host'] . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' );
        if ( isset( $reference[0] ) && $reference[0] === '/' ) { $resolved = $origin . $reference; }
        elseif ( isset( $reference[0] ) && $reference[0] === '?' ) { $resolved = $origin . ( isset( $parts['path'] ) ? $parts['path'] : '/' ) . $reference; }
        else { $path = isset( $parts['path'] ) ? $parts['path'] : '/'; $dir = preg_replace( '#/[^/]*$#', '/', $path ); $resolved = $origin . $dir . $reference; }
    }
    $resolved = preg_replace( '/#.*$/', '', $resolved );
    $clean = esc_url_raw( $resolved, array( 'http', 'https' ) );
    return ( $clean && wp_http_validate_url( $clean ) ) ? $clean : '';
}

/** Trace a bounded HTTP redirect chain one hop at a time for accurate classification. */
function wpd_check_redirect_chain( $url, $max_redirects = 5 ) {
    $current = $url;
    $visited = array();
    $chain = array();
    $redirect_count = 0;
    $first_code = 0;
    $final_code = 0;

    for ( $step = 0; $step <= (int) $max_redirects; $step++ ) {
        if ( ! is_string( $current ) || ! wp_http_validate_url( $current ) ) {
            return array( 'status' => 'unverified', 'first_code' => $first_code, 'final_code' => $final_code, 'redirect_count' => $redirect_count, 'final_url' => $current, 'chain' => $chain, 'detail' => 'A redirect destination was not a valid public HTTP/HTTPS URL.' );
        }

        $parts = wp_parse_url( $current );
        $visit_key = strtolower( ( isset( $parts['scheme'] ) ? $parts['scheme'] : '' ) . '://' . ( isset( $parts['host'] ) ? $parts['host'] : '' ) ) . ( isset( $parts['port'] ) ? ':' . (int) $parts['port'] : '' ) . ( isset( $parts['path'] ) ? $parts['path'] : '/' ) . ( isset( $parts['query'] ) ? '?' . $parts['query'] : '' );
        if ( isset( $visited[ $visit_key ] ) ) {
            $chain[] = $current . ' (repeated URL)';
            return array( 'status' => 'redirect_loop', 'first_code' => $first_code, 'final_code' => $final_code, 'redirect_count' => $redirect_count, 'final_url' => $current, 'chain' => $chain, 'detail' => 'A redirect loop was detected because a URL repeated in the redirect chain.' );
        }
        $visited[ $visit_key ] = true;

        $response = wp_safe_remote_get( $current, array(
            'timeout' => 3,
            'redirection' => 0,
            'limit_response_size' => 1024,
            'user-agent' => 'WordPressDoctor/' . WPD_VERSION . '; ' . home_url( '/' ),
            'headers' => array( 'Accept' => '*/*' ),
        ) );
        if ( is_wp_error( $response ) ) {
            return array( 'status' => 'unverified', 'first_code' => $first_code, 'final_code' => $final_code, 'redirect_count' => $redirect_count, 'final_url' => $current, 'chain' => $chain, 'detail' => $response->get_error_message() );
        }

        $code = (int) wp_remote_retrieve_response_code( $response );
        if ( $first_code === 0 ) { $first_code = $code; }
        $final_code = $code;
        if ( $code === 206 ) {
            return array( 'status' => 'partial_content', 'first_code' => $first_code, 'final_code' => $final_code, 'redirect_count' => $redirect_count, 'final_url' => $current, 'chain' => $chain, 'detail' => 'The destination returned HTTP 206 Partial Content. The scanner did not request a byte range, so verify that the destination serves the expected complete response.' );
        }
        if ( $code === 304 ) {
            return array( 'status' => 'unverified', 'first_code' => $first_code, 'final_code' => $final_code, 'redirect_count' => $redirect_count, 'final_url' => $current, 'chain' => $chain, 'detail' => 'The destination returned HTTP 304 Not Modified even though the scanner did not make a conditional request. The destination content could not be verified.' );
        }

        if ( $code < 300 || $code >= 400 ) {
            $status = ( $redirect_count > 0 ) ? 'normal_redirect' : 'no_redirect';
            if ( $code >= 400 ) { $status = 'failed_destination'; }
            return array( 'status' => $status, 'first_code' => $first_code, 'final_code' => $final_code, 'redirect_count' => $redirect_count, 'final_url' => $current, 'chain' => $chain, 'detail' => '' );
        }

        $location = trim( (string) wp_remote_retrieve_header( $response, 'location' ) );
        if ( $location === '' ) {
            $chain[] = $current . ' (HTTP ' . $code . '; no Location header)';
            return array( 'status' => 'missing_location', 'first_code' => $first_code, 'final_code' => $code, 'redirect_count' => $redirect_count, 'final_url' => $current, 'chain' => $chain, 'detail' => 'The server returned a redirect status without a usable Location header.' );
        }

        $next = wpd_resolve_reference( $current, $location );
        if ( $next === '' || ! wp_http_validate_url( $next ) ) {
            $chain[] = $current . ' (HTTP ' . $code . '; invalid Location: ' . $location . ')';
            return array( 'status' => 'missing_location', 'first_code' => $first_code, 'final_code' => $code, 'redirect_count' => $redirect_count, 'final_url' => $current, 'chain' => $chain, 'detail' => 'The redirect Location could not be resolved to a valid public HTTP/HTTPS URL.' );
        }

        $chain[] = $current . ' (HTTP ' . $code . ') → ' . $next;
        $redirect_count++;
        $next_parts = wp_parse_url( $next );
        $next_key = strtolower( ( isset( $next_parts['scheme'] ) ? $next_parts['scheme'] : '' ) . '://' . ( isset( $next_parts['host'] ) ? $next_parts['host'] : '' ) ) . ( isset( $next_parts['port'] ) ? ':' . (int) $next_parts['port'] : '' ) . ( isset( $next_parts['path'] ) ? $next_parts['path'] : '/' ) . ( isset( $next_parts['query'] ) ? '?' . $next_parts['query'] : '' );
        if ( isset( $visited[ $next_key ] ) ) {
            return array( 'status' => 'redirect_loop', 'first_code' => $first_code, 'final_code' => $code, 'redirect_count' => $redirect_count, 'final_url' => $next, 'chain' => $chain, 'detail' => 'A redirect loop was detected because the next URL has already appeared in the chain.' );
        }
        if ( $redirect_count > (int) $max_redirects ) {
            return array( 'status' => 'excessive_chain', 'first_code' => $first_code, 'final_code' => $code, 'redirect_count' => $redirect_count, 'final_url' => $next, 'chain' => $chain, 'detail' => 'The redirect chain exceeded the configured limit of ' . (int) $max_redirects . ' redirect(s).' );
        }
        $current = $next;
    }

    return array( 'status' => 'excessive_chain', 'first_code' => $first_code, 'final_code' => $final_code, 'redirect_count' => $redirect_count, 'final_url' => $current, 'chain' => $chain, 'detail' => 'The redirect chain exceeded the configured limit.' );
}

/** Fetch a bounded public HTTP(S) resource using WordPress safe HTTP handling. */
function wpd_fetch_sample( $url, $accept = '*/*', $limit = 262144 ) {
    if ( ! is_string( $url ) || ! wp_http_validate_url( $url ) ) { return new WP_Error( 'wpd_invalid_resource', 'The resource URL is not a valid public HTTP/HTTPS URL.' ); }
    return wp_safe_remote_get( $url, array(
        'timeout' => 3, 'redirection' => 2, 'limit_response_size' => (int) $limit,
        'user-agent' => 'WordPressDoctor/' . WPD_VERSION . '; ' . home_url( '/' ),
        'headers' => array( 'Accept' => $accept ),
    ) );
}

function wpd_scan_website( $url ) {
    $started = microtime( true );
    $response = wp_safe_remote_get( $url, array(
        'timeout' => 12, 'redirection' => 3, 'limit_response_size' => 1048576,
        'user-agent' => 'WordPressDoctor/' . WPD_VERSION . '; ' . home_url( '/' ),
        'headers' => array( 'Accept' => 'text/html,application/xhtml+xml' ),
    ) );
    $elapsed = round( microtime( true ) - $started, 2 );
    if ( is_wp_error( $response ) ) {
        return array( 'error' => 'WordPress Doctor could not retrieve this website. ' . $response->get_error_message() );
    }
    $http_code = (int) wp_remote_retrieve_response_code( $response );
    $html = wp_remote_retrieve_body( $response );
    if ( $http_code < 200 || $http_code >= 300 || $html === '' ) {
        $message = ( $http_code === 206 )
            ? 'The website returned HTTP 206 Partial Content. Because the scanner did not request a byte range, page-content checks were stopped to avoid misleading results.'
            : ( ( $http_code >= 300 && $http_code < 400 )
                ? sprintf( 'The website still returned HTTP redirect status %1$d after the redirect limit. Page-content checks were stopped because this response may not contain the actual page.', $http_code )
                : sprintf( 'The website returned HTTP status %1$d or no readable HTML. The page checks could not be completed.', $http_code ) );
        return array( 'error' => $message );
    }
    $results = array();
    $homepage_response_status = ( $http_code === 206 ) ? 'Detected — Please verify' : ( ( $http_code >= 200 && $http_code < 300 ) ? 'Pass' : 'Detected — Please verify' );
    $homepage_response_detail = sprintf( 'The website returned HTTP %1$d in approximately %2$s seconds.', $http_code, number_format_i18n( $elapsed, 2 ) );
    if ( $http_code === 206 ) { $homepage_response_detail .= ' HTTP 206 means Partial Content; because WordPress Doctor did not request a byte range for the homepage, verify that the server is returning the expected full page response.'; }
    $results[] = wpd_result_item( 'Website response', $homepage_response_status, $homepage_response_detail );

    // 2. Page title.
    $title = '';
    if ( preg_match( '/<title\b[^>]*>(.*?)<\/title>/is', $html, $m ) ) {
        $title = trim( html_entity_decode( wp_strip_all_tags( $m[1] ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ) );
    }
    $results[] = wpd_result_item( 'Page title', $title !== '' ? 'Pass' : 'Issue found',
        $title !== '' ? 'Title detected: ' . $title : 'No page title was detected in the retrieved HTML. JavaScript-rendered titles may not be visible to this scanner.' );

    // 3. Meta description: inspect all matching tags and distinguish absent, empty, and unreadable cases.
    $description_meta = wpd_find_meta_content( $html, 'description' );
    $descriptions = array_values( array_unique( $description_meta['values'] ) );
    if ( ! empty( $descriptions ) ) {
        $description = implode( ' | ', $descriptions );
        $description_status = 'Pass';
        $description_detail = 'Meta description detected in the retrieved HTML: ' . $description;
        if ( count( $descriptions ) > 1 ) { $description_status = 'Detected — Please verify'; $description_detail = 'Multiple non-empty meta description values were detected in the retrieved HTML: ' . $description . '. Keep one intended description. JavaScript-rendered changes may not be visible to this scanner.'; }
    } elseif ( ! empty( $description_meta['found'] ) && ! empty( $description_meta['empty'] ) ) {
        $description_status = 'Issue found';
        $description_detail = 'A meta description tag was detected, but its content was empty. The scanner inspects retrieved HTML; JavaScript-rendered metadata may not be visible.';
    } else {
        $description_status = 'Detected — Please verify';
        $description_detail = 'No meta description tag was detected in the retrieved HTML. This may mean it is missing, or it may be added later by JavaScript and therefore not visible to this basic HTTP scanner.';
    }
    $results[] = wpd_result_item( 'Meta description', $description_status, $description_detail );

    // 4. H1 heading.
    $h1 = '';
    if ( preg_match( '/<h1\b[^>]*>(.*?)<\/h1>/is', $html, $m ) ) { $h1 = trim( wp_strip_all_tags( $m[1] ) ); }
    $results[] = wpd_result_item( 'H1 heading', $h1 !== '' ? 'Pass' : 'Issue found',
        $h1 !== '' ? 'H1 heading detected: ' . $h1 : 'No H1 heading was detected in the retrieved HTML. JavaScript-rendered headings may not be visible to this scanner.' );

    // 5. Mobile viewport.
    $viewport = wpd_get_meta_content( $html, 'viewport' );
    $results[] = wpd_result_item( 'Mobile viewport', $viewport !== '' ? 'Pass' : 'Issue found',
        $viewport !== '' ? 'A viewport meta tag was detected.' : 'No viewport meta tag was detected in the retrieved HTML.' );

    // 6. Canonical URL.
    $canonical = '';
    if ( preg_match_all( '/<link\b[^>]*>/i', $html, $link_matches ) ) {
        foreach ( $link_matches[0] as $tag ) {
            $rel = strtolower( wpd_get_attribute( $tag, 'rel' ) );
            if ( in_array( 'canonical', preg_split( '/\s+/', trim( $rel ) ), true ) ) { $canonical = wpd_get_attribute( $tag, 'href' ); break; }
        }
    }
    $results[] = wpd_result_item( 'Canonical URL', $canonical !== '' ? 'Pass' : 'Detected — Please verify',
        $canonical !== '' ? 'Canonical URL detected: ' . $canonical : 'No canonical link was detected. Confirm whether this page needs one.' );

    // 7. Indexing directives: all robots/googlebot meta tags and all X-Robots-Tag values.
    $robots_values = array();
    $googlebot_values = array();
    if ( preg_match_all( '/<meta\b[^>]*>/i', $html, $meta_tags ) ) {
        foreach ( $meta_tags[0] as $tag ) {
            $name = strtolower( trim( wpd_get_attribute( $tag, 'name' ) ) );
            if ( $name === 'robots' ) { $robots_values[] = wpd_get_attribute( $tag, 'content' ); }
            if ( $name === 'googlebot' ) { $googlebot_values[] = wpd_get_attribute( $tag, 'content' ); }
        }
    }
    $headers = wp_remote_retrieve_headers( $response );
    $xrobots_values = array();
    if ( is_object( $headers ) && method_exists( $headers, 'getAll' ) ) {
        $all_headers = $headers->getAll();
        foreach ( $all_headers as $header_name => $header_value ) {
            if ( strtolower( (string) $header_name ) === 'x-robots-tag' ) {
                foreach ( (array) $header_value as $value ) { $xrobots_values[] = (string) $value; }
            }
        }
    } elseif ( is_array( $headers ) ) {
        foreach ( $headers as $header_name => $header_value ) {
            if ( strtolower( (string) $header_name ) === 'x-robots-tag' ) {
                foreach ( (array) $header_value as $value ) { $xrobots_values[] = (string) $value; }
            }
        }
    }
    // WordPress header objects normally return a single combined header value; preserve arrays when provided.
    if ( empty( $xrobots_values ) ) {
        $single_header = wp_remote_retrieve_header( $response, 'x-robots-tag' );
        if ( is_array( $single_header ) ) { $xrobots_values = array_map( 'strval', $single_header ); }
        elseif ( is_string( $single_header ) && $single_header !== '' ) { $xrobots_values = array( $single_header ); }
    }
    $all_index_values = array_merge( $robots_values, $googlebot_values, $xrobots_values );
    $noindex = wpd_has_directive_token( $all_index_values, 'noindex' );
    $index_sources = array();
    if ( ! empty( $robots_values ) ) { $index_sources[] = 'robots meta tag(s)'; }
    if ( ! empty( $googlebot_values ) ) { $index_sources[] = 'googlebot meta tag(s)'; }
    if ( ! empty( $xrobots_values ) ) { $index_sources[] = 'X-Robots-Tag response header(s)'; }
    if ( $noindex ) {
        $index_status = 'Issue found';
        $index_detail = 'A noindex directive was detected in ' . implode( ', ', $index_sources ) . '. Search engines may be instructed not to index this page.';
    } elseif ( ! empty( $index_sources ) ) {
        $directive_samples = array();
        foreach ( array( 'robots' => $robots_values, 'googlebot' => $googlebot_values, 'X-Robots-Tag' => $xrobots_values ) as $source_label => $source_values ) {
            foreach ( array_unique( array_filter( array_map( 'trim', $source_values ) ) ) as $source_value ) {
                $directive_samples[] = $source_label . '=[' . $source_value . ']';
            }
        }
        $has_explicit_index = wpd_has_directive_token( $all_index_values, 'index' ) || wpd_has_directive_token( $all_index_values, 'all' );
        if ( $has_explicit_index ) {
            $index_status = 'Pass';
            $index_detail = 'An explicit index/all directive was detected and no noindex token was found. Directives read: ' . ( empty( $directive_samples ) ? 'values were empty or unreadable' : implode( '; ', $directive_samples ) ) . '. This only describes the retrieved HTML and response headers; robots.txt, authentication, canonicalization, server behavior, and search-engine rules may still affect indexing.';
        } else {
            $index_status = 'Detected — Please verify';
            $index_detail = 'No noindex token was detected, but no explicit index/all token was found either. Directives read: ' . ( empty( $directive_samples ) ? 'values were empty or unreadable' : implode( '; ', $directive_samples ) ) . '. The absence of noindex is not proof the page is indexable; robots.txt, authentication, canonicalization, server behavior, and search-engine-specific rules may still affect discovery or indexing.';
        }
    } else {
        $index_status = 'Detected — Please verify';
        $index_detail = 'No explicit robots/googlebot meta directive or X-Robots-Tag response header was detected in the retrieved page. That is not proof the page is indexable: robots.txt, authentication, canonicalization, server behavior, and search-engine-specific rules may still affect discovery or indexing.';
    }
    $results[] = wpd_result_item( 'Indexing directive', $index_status, $index_detail );

    // 8. HTTPS check. Use the submitted URL scheme; the HTTP API does not reliably expose the final URL.
    $is_https = strtolower( (string) wp_parse_url( $url, PHP_URL_SCHEME ) ) === 'https';
    $results[] = wpd_result_item( 'HTTPS connection', $is_https ? 'Pass' : 'Issue found',
        $is_https ? 'The submitted website address uses HTTPS. This does not independently verify every aspect of the SSL configuration.' : 'The submitted website address uses HTTP rather than HTTPS.' );

    // 8a. TLS certificate expiry and verified hostname connection.
    $certificate_check = wpd_inspect_ssl_certificate( $url );
    $results[] = wpd_result_item( 'SSL certificate expiry', $certificate_check['status'], $certificate_check['detail'] );

    // 8b. Check whether the HTTP homepage redirects to an HTTPS destination.
    $redirect_host = (string) wp_parse_url( $url, PHP_URL_HOST );
    $redirect_http_url = 'http://' . $redirect_host . '/';
    $http_redirect_response = wp_safe_remote_get( $redirect_http_url, array(
        'timeout' => 5, 'redirection' => 0, 'limit_response_size' => 32768,
        'user-agent' => 'WordPressDoctor/' . WPD_VERSION . '; ' . home_url( '/' ),
    ) );
    if ( is_wp_error( $http_redirect_response ) ) {
        $results[] = wpd_result_item( 'HTTP to HTTPS redirect', 'Unable to verify', 'The scanner could not test the HTTP homepage redirect from its server. Confirm this behavior in a browser or with a redirect-testing tool.' );
    } else {
        $redirect_code = (int) wp_remote_retrieve_response_code( $http_redirect_response );
        $redirect_location = (string) wp_remote_retrieve_header( $http_redirect_response, 'location' );
        if ( $redirect_code >= 300 && $redirect_code < 400 && stripos( $redirect_location, 'https://' ) === 0 ) {
            $results[] = wpd_result_item( 'HTTP to HTTPS redirect', 'Pass', 'The HTTP homepage returned a redirect to an HTTPS URL. Other paths and redirect chains were not tested by this check.' );
        } elseif ( $redirect_code >= 200 && $redirect_code < 300 ) {
            $results[] = wpd_result_item( 'HTTP to HTTPS redirect', 'Issue found', 'The HTTP homepage returned a successful response without an initial redirect. Consider redirecting HTTP visitors to the preferred HTTPS address if appropriate for this site.' );
        } elseif ( $redirect_code >= 300 && $redirect_code < 400 ) {
            $results[] = wpd_result_item( 'HTTP to HTTPS redirect', 'Detected — Please verify', 'The HTTP homepage returned redirect status ' . $redirect_code . ' to ' . ( $redirect_location !== '' ? $redirect_location : 'an unreadable or missing Location header' ) . '. Confirm that the final destination is the intended HTTPS URL.' );
        } else {
            $results[] = wpd_result_item( 'HTTP to HTTPS redirect', 'Unable to verify', 'The HTTP homepage returned status ' . $redirect_code . '. The scanner could not confirm a standard HTTP-to-HTTPS redirect.' );
        }
    }

    // 8c. Security headers visible in the initial homepage response.
    $security_headers = array();
    if ( is_object( $headers ) && method_exists( $headers, 'getAll' ) ) {
        $security_headers = array_change_key_case( $headers->getAll(), CASE_LOWER );
    } elseif ( is_array( $headers ) ) {
        $security_headers = array_change_key_case( $headers, CASE_LOWER );
    }
    $header_checks = array(
        'Strict-Transport-Security' => 'strict-transport-security',
        'Content-Security-Policy' => 'content-security-policy',
        'X-Content-Type-Options' => 'x-content-type-options',
        'Referrer-Policy' => 'referrer-policy',
        'X-Frame-Options' => 'x-frame-options',
    );
    $header_purposes = array(
        'Strict-Transport-Security' => 'asks browsers to use HTTPS for future visits',
        'Content-Security-Policy' => 'can restrict which sources may load scripts, styles, images, and other content',
        'X-Content-Type-Options' => 'helps prevent MIME-type sniffing when set to nosniff',
        'Referrer-Policy' => 'controls how much referrer information browsers send',
        'X-Frame-Options' => 'can restrict whether the page may be embedded in frames',
    );
    $missing_headers = array();
    $review_headers = array();
    $header_lines = array();
    foreach ( $header_checks as $label => $key ) {
        $value = $security_headers[ $key ] ?? '';
        if ( is_array( $value ) ) {
            $value = implode( ', ', array_filter( array_map( 'trim', array_map( 'strval', $value ) ), function( $v ) { return $v !== ''; } ) );
        } else {
            $value = trim( (string) $value );
        }
        if ( $value === '' ) {
            $missing_headers[] = $label;
            $header_lines[] = $label . ': not detected (' . $header_purposes[ $label ] . ')';
            continue;
        }

        $value_note = 'detected';
        $value_valid = true;
        if ( $label === 'Strict-Transport-Security' ) {
            if ( ! preg_match( '/(?:^|;)\s*max-age\s*=\s*\d+/i', $value ) ) {
                $value_valid = false;
                $value_note = 'detected, but no numeric max-age directive was recognized';
            } else {
                $value_note = 'detected with a max-age directive';
            }
        } elseif ( $label === 'X-Content-Type-Options' ) {
            if ( strtolower( trim( $value ) ) !== 'nosniff' ) {
                $value_valid = false;
                $value_note = 'detected, but the value is not the expected nosniff token';
            } else {
                $value_note = 'detected with nosniff';
            }
        } elseif ( $label === 'Referrer-Policy' ) {
            $known_policies = array( 'no-referrer', 'no-referrer-when-downgrade', 'origin', 'origin-when-cross-origin', 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin', 'unsafe-url' );
            $policy_tokens = array_map( 'trim', explode( ',', strtolower( $value ) ) );
            $last_policy = end( $policy_tokens );
            if ( ! in_array( $last_policy, $known_policies, true ) ) {
                $value_valid = false;
                $value_note = 'detected, but the policy value was not recognized by this basic check';
            } else {
                $value_note = 'detected with policy ' . $last_policy;
            }
        } elseif ( $label === 'X-Frame-Options' ) {
            $frame_value = strtoupper( trim( $value ) );
            if ( ! in_array( $frame_value, array( 'DENY', 'SAMEORIGIN' ), true ) ) {
                $value_valid = false;
                $value_note = 'detected, but its value is not DENY or SAMEORIGIN; CSP frame-ancestors may be an alternative';
            } else {
                $value_note = 'detected with ' . $frame_value;
            }
        } elseif ( $label === 'Content-Security-Policy' ) {
            $value_note = 'detected; directives and site compatibility were not fully evaluated';
        }
        if ( ! $value_valid ) { $review_headers[] = $label; }
        $header_lines[] = $label . ': ' . $value_note . ' (' . $header_purposes[ $label ] . ')';
    }
    $header_status = ( empty( $missing_headers ) && empty( $review_headers ) ) ? 'Pass' : 'Detected — Please verify';
    $header_detail = implode( '; ', $header_lines ) . '. This is a basic homepage-response check, not a complete security audit. Missing headers are not automatically proof of a vulnerability. HSTS should only be enabled when the site is intended to stay on HTTPS; start with a suitable max-age and expand carefully. CSP should be introduced in report-only mode or tested carefully to avoid breaking WordPress, themes, plugins, and embedded services. X-Frame-Options may be replaced or supplemented by the CSP frame-ancestors directive.';
    $results[] = wpd_result_item( 'Security response headers', $header_status, $header_detail );

    // 8d. Mixed-content references in retrieved HTML. This does not inspect CSS or JavaScript files.
    $mixed_content_count = 0;
    if ( $is_https && preg_match_all( '/(?:src|href|poster)\s*=\s*(["\'])(http:\/\/[^"\']+)\1/i', $html, $mixed_matches ) ) {
        $mixed_content_count = count( $mixed_matches[2] );
    }
    if ( ! $is_https ) {
        $results[] = wpd_result_item( 'Mixed content references', 'Unable to verify', 'The submitted URL uses HTTP, so the HTTPS mixed-content check was not applicable to this request.' );
    } else {
        $results[] = wpd_result_item( 'Mixed content references', $mixed_content_count > 0 ? 'Issue found' : 'Pass',
            $mixed_content_count > 0 ? sprintf( '%d HTTP resource reference(s) were found in the retrieved HTML of this HTTPS page. Check whether they load active or passive content insecurely.', $mixed_content_count ) : 'No direct HTTP src, href, or poster references were detected in the retrieved HTML. CSS, JavaScript-generated content, and other resources were not inspected by this check.' );
    }

    // 8e. Detect common Google measurement snippets in retrieved HTML only.
    $has_ga = (bool) preg_match( '/\b(?:gtag\s*\(|google-analytics\.com\/(?:g|analytics)\.js|G-[A-Z0-9]{6,}|UA-[0-9-]+)\b/i', $html );
    $has_gtm = (bool) preg_match( '/googletagmanager\.com\/gtm\.js|GTM-[A-Z0-9]+/i', $html );
    $has_gsc = (bool) preg_match( '/<meta\b[^>]*name\s*=\s*(["\'])google-site-verification\1/i', $html );
    $google_detected = array();
    if ( $has_ga ) { $google_detected[] = 'Google Analytics-related snippet'; }
    if ( $has_gtm ) { $google_detected[] = 'Google Tag Manager-related snippet'; }
    if ( $has_gsc ) { $google_detected[] = 'Google site verification meta tag'; }
    $results[] = wpd_result_item( 'Google service signals', empty( $google_detected ) ? 'Detected — Please verify' : 'Pass',
        empty( $google_detected ) ? 'No common Google Analytics, Tag Manager, or Search Console verification signal was detected in the retrieved HTML. This does not prove the services are absent; snippets may be injected later or verification may use another method.' : 'Public-page signals detected: ' . implode( ', ', $google_detected ) . '. This does not confirm account ownership, successful data collection, or Search Console access.' );

    // 8f. Heading structure, image attributes, link destinations and approximate HTML size.
    $heading_counts = array();
    for ( $level = 1; $level <= 6; $level++ ) {
        preg_match_all( '/<h' . $level . '\b[^>]*>/i', $html, $heading_matches );
        $heading_counts[ 'H' . $level ] = count( $heading_matches[0] );
    }
    $h1_count = $heading_counts['H1'];
    $heading_summary = array();
    foreach ( $heading_counts as $heading_name => $heading_count ) { if ( $heading_count > 0 ) { $heading_summary[] = $heading_name . ': ' . $heading_count; } }
    $results[] = wpd_result_item( 'Heading structure', $h1_count > 0 ? 'Pass' : 'Issue found',
        'Heading tags detected in the retrieved HTML: ' . ( empty( $heading_summary ) ? 'none' : implode( ', ', $heading_summary ) ) . '. The H1 count alone does not establish an SEO problem; review the actual heading text and order for a meaningful hierarchy. This check counts tags and does not assess writing quality or visual presentation.' );

    $image_total = 0; $images_missing_alt = 0; $images_missing_dimensions = 0; $images_lazy = 0;
    if ( preg_match_all( '/<img\b[^>]*>/i', $html, $image_matches ) ) {
        $image_total = count( $image_matches[0] );
        foreach ( $image_matches[0] as $image_tag ) {
            $alt = wpd_get_attribute( $image_tag, 'alt' );
            if ( $alt === '' && ! preg_match( '/(?:^|\s)alt\s*=\s*(["\'])\s*\1/i', $image_tag ) ) { $images_missing_alt++; }
            if ( wpd_get_attribute( $image_tag, 'width' ) === '' || wpd_get_attribute( $image_tag, 'height' ) === '' ) { $images_missing_dimensions++; }
            if ( strtolower( wpd_get_attribute( $image_tag, 'loading' ) ) === 'lazy' ) { $images_lazy++; }
        }
    }
    $image_status = ( $image_total === 0 || $images_missing_alt > 0 || $images_missing_dimensions > 0 ) ? 'Detected — Please verify' : 'Pass';
    $results[] = wpd_result_item( 'Image accessibility and loading attributes', $image_status,
        sprintf( 'Found %1$d image tag(s); %2$d appear to have no alt attribute, %3$d lack an explicit width or height attribute, and %4$d use loading="lazy". Empty alt text can be appropriate for decorative images; review image purpose and layout needs before changing attributes.', $image_total, $images_missing_alt, $images_missing_dimensions, $images_lazy ) );

    $internal_links = 0; $external_links = 0; $unusual_links = 0; $link_check_candidates = array(); $link_candidate_types = array();
    $site_host = strtolower( (string) wp_parse_url( $url, PHP_URL_HOST ) );
    $link_origin = strtolower( (string) wp_parse_url( $url, PHP_URL_SCHEME ) ) . '://' . (string) wp_parse_url( $url, PHP_URL_HOST );
    $link_port = wp_parse_url( $url, PHP_URL_PORT );
    if ( $link_port ) { $link_origin .= ':' . (int) $link_port; }
    if ( preg_match_all( '/<a\b[^>]*>/i', $html, $anchor_matches ) ) {
        foreach ( $anchor_matches[0] as $anchor_tag ) {
            $href = trim( wpd_get_attribute( $anchor_tag, 'href' ) );
            if ( $href === '' || $href[0] === '#' || preg_match( '/^(?:mailto:|tel:|javascript:|data:)/i', $href ) ) { continue; }
            $absolute = esc_url_raw( $href, array( 'http', 'https' ) );
            if ( ! preg_match( '#^https?://#i', $absolute ) ) {
                if ( class_exists( 'WP_Http' ) && method_exists( 'WP_Http', 'make_absolute_url' ) ) { $absolute = WP_Http::make_absolute_url( $href, $url ); }
                else { $absolute = $link_origin . '/' . ltrim( $href, '/' ); }
            }
            $link_host = strtolower( (string) wp_parse_url( $absolute, PHP_URL_HOST ) );
            if ( $link_host === '' ) { $unusual_links++; $link_type = 'uncategorized'; }
            elseif ( $link_host === $site_host || substr( $link_host, -strlen( '.' . $site_host ) ) === '.' . $site_host ) { $internal_links++; $link_type = 'internal'; }
            else { $external_links++; $link_type = 'external'; }
            if ( preg_match( '#^https?://#i', $absolute ) && wp_http_validate_url( $absolute ) ) {
                $link_check_candidates[] = $absolute;
                $link_candidate_types[ $absolute ] = $link_type;
            }
        }
    }
    $results[] = wpd_result_item( 'Links on the page', 'Pass',
        sprintf( 'The retrieved HTML contains approximately %1$d internal link(s), %2$d external link(s), and %3$d link(s) that could not be categorized. This is a link inventory only; it does not mean those links have been checked for broken destinations.', $internal_links, $external_links, $unusual_links ) );

    // Check a small, deduplicated sample of links and classify redirects instead of treating all redirects as issues.
    $link_check_candidates = array_values( array_unique( $link_check_candidates ) );
    $link_check_candidates = array_slice( $link_check_candidates, 0, 8 );
    $checked_links = 0; $broken_links = array(); $unverified_links = 0; $redirected_links = 0;
    $normal_redirects = 0; $redirect_issue_count = 0; $redirect_problem_examples = array();
    $link_error_examples = array(); $redirect_examples = array();
    $broken_internal_links = 0; $broken_external_links = 0; $broken_uncategorized_links = 0;

    foreach ( $link_check_candidates as $candidate_url ) {
        $trace = wpd_check_redirect_chain( $candidate_url, 5 );
        $trace_status = isset( $trace['status'] ) ? $trace['status'] : 'unverified';
        $final_code = isset( $trace['final_code'] ) ? (int) $trace['final_code'] : 0;
        $redirect_count = isset( $trace['redirect_count'] ) ? (int) $trace['redirect_count'] : 0;
        $final_url = isset( $trace['final_url'] ) ? (string) $trace['final_url'] : $candidate_url;
        $candidate_type = isset( $link_candidate_types[ $candidate_url ] ) ? $link_candidate_types[ $candidate_url ] : 'uncategorized';

        if ( $trace_status !== 'unverified' && $final_code > 0 ) { $checked_links++; }
        if ( $redirect_count > 0 ) {
            $redirected_links++;
            if ( $trace_status === 'normal_redirect' ) { $normal_redirects++; }
            if ( count( $redirect_examples ) < 5 ) {
                $redirect_examples[] = $candidate_url . ' → ' . $final_url . ' (' . $redirect_count . ' redirect(s), final HTTP ' . $final_code . ')';
            }
        }

        if ( in_array( $trace_status, array( 'redirect_loop', 'excessive_chain', 'missing_location' ), true ) ) {
            $redirect_issue_count++;
            if ( count( $redirect_problem_examples ) < 5 ) { $redirect_problem_examples[] = $candidate_url . ': ' . $trace['detail'] . ( empty( $trace['chain'] ) ? '' : ' Chain: ' . implode( ' → ', $trace['chain'] ) ); }
        }

        // An internal link ending on an unrelated host or downgrading HTTPS to HTTP is flagged for review.
        if ( $redirect_count > 0 && $trace_status === 'normal_redirect' ) {
            $original_scheme = strtolower( (string) wp_parse_url( $candidate_url, PHP_URL_SCHEME ) );
            $final_scheme = strtolower( (string) wp_parse_url( $final_url, PHP_URL_SCHEME ) );
            $final_host = strtolower( (string) wp_parse_url( $final_url, PHP_URL_HOST ) );
            $host_is_site = ( $final_host === $site_host || ( $site_host !== '' && substr( $final_host, -strlen( '.' . $site_host ) ) === '.' . $site_host ) );
            if ( ( $candidate_type === 'internal' && ! $host_is_site ) || ( $original_scheme === 'https' && $final_scheme === 'http' ) ) {
                $redirect_issue_count++;
                if ( count( $redirect_problem_examples ) < 5 ) {
                    $why = ( $candidate_type === 'internal' && ! $host_is_site ) ? 'an internal link redirects outside the scanned site host' : 'the redirect downgrades HTTPS to HTTP';
                    $redirect_problem_examples[] = $candidate_url . ' → ' . $final_url . ' (' . $why . ')';
                }
            }
        }

        if ( in_array( $final_code, array( 404, 410 ), true ) ) {
            $broken_links[] = $candidate_url . ' → ' . $final_url . ' (HTTP ' . $final_code . ')';
            if ( $candidate_type === 'internal' ) { $broken_internal_links++; }
            elseif ( $candidate_type === 'external' ) { $broken_external_links++; }
            else { $broken_uncategorized_links++; }
        } elseif ( $trace_status === 'unverified' || $trace_status === 'partial_content' || $trace_status === 'failed_destination' || $final_code >= 400 || $final_code === 0 ) {
            $unverified_links++;
            if ( count( $link_error_examples ) < 5 ) {
                $error_text = $candidate_url . ( $final_code > 0 ? ' (final HTTP ' . $final_code . ')' : '' );
                if ( ! empty( $trace['detail'] ) ) { $error_text .= ' — ' . $trace['detail']; }
                $link_error_examples[] = $error_text;
            }
        }
    }

    if ( empty( $link_check_candidates ) ) {
        $results[] = wpd_result_item( 'Sampled link destination checks', 'Unable to verify', 'No eligible HTTP/HTTPS links were available to test in the retrieved HTML. This check only samples links from the scanned homepage; it is not a full-site crawl.' );
    } elseif ( $checked_links === 0 ) {
        $results[] = wpd_result_item( 'Sampled link destination checks', 'Unable to verify', sprintf( 'The scanner could not verify any of the %d sampled links. Destinations may block automated requests or outbound checks may be restricted.', count( $link_check_candidates ) ) . ( empty( $link_error_examples ) ? '' : ' Examples: ' . implode( '; ', $link_error_examples ) . '.' ) );
    } else {
        if ( $redirect_issue_count > 0 ) { $link_status = 'Issue found'; }
        elseif ( ! empty( $broken_links ) || $unverified_links > 0 ) { $link_status = 'Detected — Please verify'; }
        else { $link_status = 'Pass'; }

        $detail = sprintf( 'Received an HTTP response for %1$d of up to %2$d sampled homepage link(s). %3$d returned HTTP 404 or 410 responses (likely missing; verify before treating them as broken; internal: %4$d, external: %5$d, uncategorized: %6$d). %7$d link(s) redirected; %8$d completed a redirect to a successful response and are treated as normal redirects, not automatically as issues. %9$d redirect behavior problem(s) were detected, and %10$d destination(s) could not be verified or returned other HTTP errors%11$s. Other HTTP errors are not automatically called broken because blocking, rate limits, or server restrictions may be responsible. This is a limited homepage sample, not a full-site broken-link scan.', $checked_links, count( $link_check_candidates ), count( $broken_links ), $broken_internal_links, $broken_external_links, $broken_uncategorized_links, $redirected_links, $normal_redirects, $redirect_issue_count, $unverified_links, empty( $link_error_examples ) ? '' : ' (examples: ' . implode( '; ', $link_error_examples ) . ')' );
        if ( ! empty( $broken_links ) ) { $detail .= ' Likely missing destinations to verify: ' . implode( '; ', array_slice( $broken_links, 0, 5 ) ) . '.'; }
        if ( ! empty( $redirect_examples ) ) { $detail .= ' Redirect examples (original → final destination): ' . implode( '; ', $redirect_examples ) . '.'; }
        if ( ! empty( $redirect_problem_examples ) ) { $detail .= ' Redirect behavior to review: ' . implode( '; ', $redirect_problem_examples ) . '.'; }
        $results[] = wpd_result_item( 'Sampled link destination checks', $link_status, $detail );
    }

    // Bounded resource inventory and status checks for homepage images and linked documents.
    // This is a homepage sample only; it does not crawl every page on the site.
    $resource_candidates = array();
    $resource_counts = array( 'images' => 0, 'PDF' => 0, 'Word documents' => 0, 'other files' => 0 );
    $resource_extension_type = function( $resource_url ) {
        $path = strtolower( (string) wp_parse_url( $resource_url, PHP_URL_PATH ) );
        if ( preg_match( '/\.(?:jpe?g|png|gif|webp|avif|svg|bmp|ico|tiff?)$/i', $path ) ) { return 'images'; }
        if ( preg_match( '/\.pdf$/i', $path ) ) { return 'PDF'; }
        if ( preg_match( '/\.(?:doc|docx|odt|rtf)$/i', $path ) ) { return 'Word documents'; }
        if ( preg_match( '/\.(?:xls|xlsx|csv|ppt|pptx|zip|txt|xml|mp3|mp4|webm|mov)$/i', $path ) ) { return 'other files'; }
        return '';
    };
    if ( preg_match_all( '/<img\b[^>]*>/i', $html, $resource_img_tags ) ) {
        foreach ( $resource_img_tags[0] as $resource_img_tag ) {
            $resource_src = trim( wpd_get_attribute( $resource_img_tag, 'src' ) );
            if ( $resource_src === '' ) { continue; }
            $resource_absolute = esc_url_raw( $resource_src, array( 'http', 'https' ) );
            if ( ! preg_match( '#^https?://#i', $resource_absolute ) ) {
                if ( class_exists( 'WP_Http' ) && method_exists( 'WP_Http', 'make_absolute_url' ) ) { $resource_absolute = WP_Http::make_absolute_url( $resource_src, $url ); }
                else { $resource_absolute = $link_origin . '/' . ltrim( $resource_src, '/' ); }
            }
            if ( preg_match( '#^https?://#i', $resource_absolute ) && wp_http_validate_url( $resource_absolute ) ) {
                $resource_type = $resource_extension_type( $resource_absolute );
                // An image tag indicates an image even when its URL has no file extension.
                if ( $resource_type === '' ) { $resource_type = 'images'; }
                $resource_counts[ $resource_type ]++;
                $resource_candidates[ $resource_absolute ] = $resource_type;
            }
        }
    }
    if ( preg_match_all( '/<a\b[^>]*>/i', $html, $resource_anchor_tags ) ) {
        foreach ( $resource_anchor_tags[0] as $resource_anchor_tag ) {
            $resource_href = trim( wpd_get_attribute( $resource_anchor_tag, 'href' ) );
            if ( $resource_href === '' || preg_match( '/^(?:#|mailto:|tel:|javascript:|data:)/i', $resource_href ) ) { continue; }
            $resource_absolute = esc_url_raw( $resource_href, array( 'http', 'https' ) );
            if ( ! preg_match( '#^https?://#i', $resource_absolute ) ) {
                if ( class_exists( 'WP_Http' ) && method_exists( 'WP_Http', 'make_absolute_url' ) ) { $resource_absolute = WP_Http::make_absolute_url( $resource_href, $url ); }
                else { $resource_absolute = $link_origin . '/' . ltrim( $resource_href, '/' ); }
            }
            if ( ! preg_match( '#^https?://#i', $resource_absolute ) || ! wp_http_validate_url( $resource_absolute ) ) { continue; }
            $resource_type = $resource_extension_type( $resource_absolute );
            if ( $resource_type !== '' && ! isset( $resource_candidates[ $resource_absolute ] ) ) {
                $resource_counts[ $resource_type ]++;
                $resource_candidates[ $resource_absolute ] = $resource_type;
            }
        }
    }
    $resource_unique_total = count( $resource_candidates );
    $resource_candidates = array_slice( $resource_candidates, 0, 12, true );
    $resource_sample_total = count( $resource_candidates );
    $resource_checked = 0; $resource_unverified = 0; $resource_broken_by_type = array(); $resource_broken_details = array();
    $resource_partial = 0; $resource_partial_examples = array();
    foreach ( $resource_candidates as $resource_url => $resource_type ) {
        $resource_range_requested = false;
        $resource_response = wp_safe_remote_head( $resource_url, array(
            'timeout' => 3, 'redirection' => 2, 'limit_response_size' => 1024,
            'user-agent' => 'WordPressDoctor/' . WPD_VERSION . '; ' . home_url( '/' ),
        ) );
        // Some legitimate hosts do not implement HEAD; try a tiny GET in that case.
        if ( ! is_wp_error( $resource_response ) && in_array( (int) wp_remote_retrieve_response_code( $resource_response ), array( 405, 501 ), true ) ) {
            $resource_range_requested = true;
            $resource_response = wp_safe_remote_get( $resource_url, array(
                'timeout' => 3, 'redirection' => 2, 'limit_response_size' => 1024,
                'user-agent' => 'WordPressDoctor/' . WPD_VERSION . '; ' . home_url( '/' ),
                'headers' => array( 'Range' => 'bytes=0-1023', 'Accept' => '*/*' ),
            ) );
        }
        if ( is_wp_error( $resource_response ) ) { $resource_unverified++; continue; }
        $resource_code = (int) wp_remote_retrieve_response_code( $resource_response );
        if ( $resource_code === 206 && ! $resource_range_requested ) {
            $resource_unverified++; $resource_partial++;
            if ( count( $resource_partial_examples ) < 3 ) { $resource_partial_examples[] = $resource_type . ': ' . $resource_url; }
        } elseif ( $resource_code >= 200 && $resource_code < 300 ) { $resource_checked++; }
        elseif ( in_array( $resource_code, array( 404, 410 ), true ) ) {
            $resource_checked++;
            if ( ! isset( $resource_broken_by_type[ $resource_type ] ) ) { $resource_broken_by_type[ $resource_type ] = 0; }
            $resource_broken_by_type[ $resource_type ]++;
            if ( count( $resource_broken_details ) < 5 ) { $resource_broken_details[] = $resource_type . ': ' . $resource_url . ' (HTTP ' . $resource_code . ')'; }
        } elseif ( $resource_code >= 400 ) { $resource_unverified++; }
        else { $resource_unverified++; }
    }
    $resource_inventory = array();
    foreach ( $resource_counts as $resource_label => $resource_count ) { if ( $resource_count > 0 ) { $resource_inventory[] = $resource_label . ': ' . $resource_count; } }
    $resource_detail = 'Homepage resource references detected (reference counts may include repeated uses of the same URL): ' . ( empty( $resource_inventory ) ? 'none with recognizable image/document URLs' : implode( ', ', $resource_inventory ) ) . '. Found ' . $resource_unique_total . ' unique eligible resource URL(s), sampled ' . $resource_sample_total . ' (maximum 12), checked successfully or received an HTTP response for ' . $resource_checked . ', and could not verify ' . $resource_unverified . '. Repeated image tags can make the image-reference count higher than the number of unique URLs tested.';
    if ( $resource_partial > 0 ) { $resource_detail .= ' HTTP 206 Partial Content was returned without the scanner requesting a byte range for ' . $resource_partial . ' resource(s); these were left unverified rather than counted as complete responses.' . ( empty( $resource_partial_examples ) ? '' : ' Examples: ' . implode( '; ', $resource_partial_examples ) . '.' ); }
    if ( ! empty( $resource_broken_by_type ) ) {
        $resource_type_summary = array();
        foreach ( $resource_broken_by_type as $resource_label => $resource_count ) { $resource_type_summary[] = $resource_label . ': ' . $resource_count; }
        $resource_detail .= ' HTTP 404/410 responses by type (likely missing resources): ' . implode( ', ', $resource_type_summary ) . '. Examples: ' . implode( '; ', $resource_broken_details ) . '. Verify manually because access restrictions can cause false positives.';
        $resource_status = 'Detected — Please verify';
    } elseif ( $resource_checked === 0 ) {
        $resource_status = 'Unable to verify';
        $resource_detail .= ' No resource status could be confirmed from this server.';
    } else {
        $resource_status = $resource_unverified > 0 ? 'Detected — Please verify' : 'Pass';
        $resource_detail .= ' Only HTTP 2xx responses are counted as successful resource checks. HTTP 404/410 responses are classified as likely missing resources; unresolved 3xx redirects and other HTTP errors remain unverified and may reflect access restrictions or server behavior. This is a bounded homepage sample, not a full-site resource crawl; URLs without recognizable file extensions may be missed.';
    }
    $results[] = wpd_result_item( 'Sampled image and document checks', $resource_status, $resource_detail );

    $html_bytes = strlen( $html );
    $results[] = wpd_result_item( 'HTML document size', $html_bytes > 250000 ? 'Detected — Please verify' : 'Pass',
        sprintf( 'The retrieved HTML body is approximately %s KB before any further browser processing. This scanner limits the response size to 1 MB; the result is not a full-page weight or Core Web Vitals measurement.', number_format_i18n( $html_bytes / 1024, 1 ) ) );

    // Public WordPress fingerprint signal; a detected version does not confirm whether it is vulnerable.
    $generator = '';
    if ( preg_match( '/<meta\b[^>]*name\s*=\s*(["\'])generator\1[^>]*>/i', $html, $generator_match ) ) { $generator = wpd_get_attribute( $generator_match[0], 'content' ); }
    $results[] = wpd_result_item( 'Public platform fingerprint', $generator !== '' && stripos( $generator, 'wordpress' ) !== false ? 'Detected — Please verify' : 'Unable to verify',
        $generator !== '' && stripos( $generator, 'wordpress' ) !== false ? 'A WordPress generator meta tag was detected (' . $generator . '). This is a public fingerprint signal, not proof of a security vulnerability.' : 'No WordPress generator meta tag was detected in the retrieved HTML. A WordPress site may hide or remove this tag, so the platform cannot be confirmed from this check alone.' );

    // Prepare origin for robots.txt and sitemap checks.
    $url_parts = wp_parse_url( $url );
    $origin = '';
    if ( is_array( $url_parts ) && ! empty( $url_parts['scheme'] ) && ! empty( $url_parts['host'] ) ) {
        $origin = $url_parts['scheme'] . '://' . $url_parts['host'];
        if ( ! empty( $url_parts['port'] ) ) { $origin .= ':' . (int) $url_parts['port']; }
    }

    // 9. robots.txt.
    $robots_body = false; $robots_status = 0;
    if ( $origin !== '' ) {
        $robots_response = wp_safe_remote_get( $origin . '/robots.txt', array(
            'timeout' => 8, 'redirection' => 3, 'limit_response_size' => 262144,
            'user-agent' => 'WordPressDoctor/' . WPD_VERSION . '; ' . home_url( '/' ),
        ) );
        if ( ! is_wp_error( $robots_response ) ) {
            $robots_status = (int) wp_remote_retrieve_response_code( $robots_response );
            // v2.0.10: HTTP 206 is a partial response, not a verified complete robots.txt file.
            if ( $robots_status >= 200 && $robots_status < 300 && $robots_status !== 206 ) { $robots_body = wp_remote_retrieve_body( $robots_response ); }
        }
    }
    if ( is_string( $robots_body ) && trim( $robots_body ) !== '' ) {
        $results[] = wpd_result_item( 'robots.txt', 'Pass', 'robots.txt was retrieved successfully. Its directives still need to be reviewed for your intended crawling rules.' );
    } elseif ( $robots_status === 404 ) {
        $results[] = wpd_result_item( 'robots.txt', 'Detected — Please verify', 'No robots.txt file was found at the standard location. This is not automatically an SEO problem.' );
    } else {
        $results[] = wpd_result_item( 'robots.txt', 'Unable to verify', 'WordPress Doctor could not confirm that robots.txt is readable. The file may be unavailable, blocked, or temporarily inaccessible.' );
    }

    // 10. Crawling directives. Keep Sitemap declarations separate from Disallow paths.
    if ( is_string( $robots_body ) && trim( $robots_body ) !== '' ) {
        $robots_directive_lines = preg_split( "/\\r\\n|\\n|\\r/", $robots_body );
        $valid_crawl_directives = array();
        foreach ( $robots_directive_lines as $robots_line ) {
            $robots_line = trim( preg_replace( '/\\s*#.*$/', '', $robots_line ) );
            if ( $robots_line === '' ) { continue; }
            if ( preg_match( '/^Disallow\\s*:\\s*(.*?)\\s*$/i', $robots_line, $disallow_match ) ) {
                $disallow_value = trim( $disallow_match[1] );
                // A malformed line such as "Disallow: Sitemap: https://example.com/sitemap.xml"
                // is not a valid path rule and must not be reported as one.
                if ( preg_match( '/^Sitemap\\s*:/i', $disallow_value ) ) { continue; }
                // An empty Disallow value does not block a path; do not count it as a selective rule.
                if ( $disallow_value === '' ) { continue; }
                $valid_crawl_directives[] = 'Disallow: ' . $disallow_value;
            } elseif ( preg_match( '/^User-agent\\s*:/i', $robots_line ) ) {
                $valid_crawl_directives[] = $robots_line;
            }
        }
        $crawl_directives_text = implode( "\n", $valid_crawl_directives );
        if ( preg_match( '/^Disallow\\s*:\\s*\\/(?:\\s*)$/im', $crawl_directives_text ) ) {
            $results[] = wpd_result_item( 'Crawling directives', 'Detected — Please verify', 'A broad Disallow: / rule was detected. It can block crawling for the user-agent group containing that rule. Review the group and confirm that blocking is intentional.' );
        } elseif ( preg_match( '/^Disallow\\s*:/im', $crawl_directives_text ) ) {
            $directive_lines = array();
            $current_user_agent = 'unspecified user-agent group';
            $directive_matches = array();
            if ( preg_match_all( '/^\\s*(User-agent|Disallow)\\s*:\\s*([^\\r\\n]*)/im', $crawl_directives_text, $directive_matches, PREG_SET_ORDER ) ) {
                foreach ( $directive_matches as $directive_match ) {
                    $directive_name = strtolower( trim( $directive_match[1] ) );
                    $directive_value = trim( $directive_match[2] );
                    if ( $directive_name === 'user-agent' ) {
                        $current_user_agent = $directive_value !== '' ? $directive_value : 'unspecified user-agent';
                    } elseif ( $directive_name === 'disallow' ) {
                        $directive_lines[] = 'User-agent ' . $current_user_agent . ': Disallow: ' . ( $directive_value !== '' ? $directive_value : '(empty path; normally does not block a path)' );
                    }
                    if ( count( $directive_lines ) >= 10 ) { break; }
                }
            }
            $directive_detail = 'One or more selective Disallow rules were detected. These may block particular paths rather than the entire website. Review each user-agent group and path to confirm the rules are intentional.';
            if ( ! empty( $directive_lines ) ) {
                $directive_detail .= ' Detected rules (up to 10): ' . implode( '; ', $directive_lines ) . ( count( $directive_lines ) >= 10 ? '; additional rules may exist' : '' ) . '.';
            }
            $results[] = wpd_result_item( 'Crawling directives', 'Detected — Please verify', $directive_detail );
        } else {
            $results[] = wpd_result_item( 'Crawling directives', 'Pass', 'No valid Disallow path rules were detected in the readable robots.txt file. Sitemap declarations are handled separately. This does not guarantee that every page is crawlable.' );
        }
    } else {
        $results[] = wpd_result_item( 'Crawling directives', 'Unable to verify', 'Crawling directives could not be inspected because a readable robots.txt file was not retrieved.' );
    }

    // 11 and 12. Sitemap discovery and robots.txt sitemap reference (preserved behaviour).
    $sitemap_candidates = array();
    if ( is_string( $robots_body ) && trim( $robots_body ) !== '' && preg_match_all( '/^\s*Sitemap\s*:\s*(\S+)/im', $robots_body, $sitemap_matches ) ) {
        foreach ( $sitemap_matches[1] as $sitemap_url ) {
            if ( preg_match( '#^https?://#i', $sitemap_url ) ) { $candidate = esc_url_raw( $sitemap_url, array( 'http', 'https' ) ); }
            else { $candidate = esc_url_raw( $origin . '/' . ltrim( $sitemap_url, '/' ), array( 'http', 'https' ) ); }
            if ( $candidate && wp_http_validate_url( $candidate ) ) { $sitemap_candidates[] = $candidate; }
        }
    }
    $robots_lists_sitemap = ! empty( $sitemap_candidates );
    if ( $origin !== '' ) {
        $sitemap_candidates[] = $origin . '/sitemap.xml';
        $sitemap_candidates[] = $origin . '/sitemap_index.xml';
        $sitemap_candidates[] = $origin . '/wp-sitemap.xml';
    }
    $sitemap_candidates = array_values( array_unique( $sitemap_candidates ) );
    $sitemap_found = false; $sitemap_unverified = false; $sitemap_found_url = ''; $sitemap_found_body = ''; $sitemap_root_type = '';
    foreach ( $sitemap_candidates as $sitemap_url ) {
        if ( ! wp_http_validate_url( $sitemap_url ) ) { continue; }
        $sitemap_response = wp_safe_remote_get( $sitemap_url, array(
            'timeout' => 8, 'redirection' => 3, 'limit_response_size' => 262144,
            'user-agent' => 'WordPressDoctor/' . WPD_VERSION . '; ' . home_url( '/' ),
            'headers' => array( 'Accept' => 'application/xml,text/xml,*/*' ),
        ) );
        if ( is_wp_error( $sitemap_response ) ) { $sitemap_unverified = true; continue; }
        $sitemap_code = (int) wp_remote_retrieve_response_code( $sitemap_response );
        $sitemap_body = wp_remote_retrieve_body( $sitemap_response );
        // v2.0.10: do not accept an unexpected HTTP 206 body as a complete sitemap.
        if ( $sitemap_code >= 200 && $sitemap_code < 300 && $sitemap_code !== 206 && is_string( $sitemap_body ) && preg_match( '/<(?:[a-z0-9_-]+:)?(urlset|sitemapindex)\b/i', $sitemap_body, $root_match ) ) { $sitemap_found = true; $sitemap_found_url = $sitemap_url; $sitemap_found_body = $sitemap_body; $sitemap_root_type = strtolower( $root_match[1] ); break; }
        if ( $sitemap_code !== 404 ) { $sitemap_unverified = true; }
    }
    if ( $sitemap_found ) {
        $results[] = wpd_result_item( 'Sitemap discovery', 'Pass', 'An accessible XML sitemap or sitemap index was detected at a common location or a URL advertised by robots.txt.' );
    } elseif ( $sitemap_unverified ) {
        $results[] = wpd_result_item( 'Sitemap discovery', 'Unable to verify', 'No accessible XML sitemap could be confirmed. A sitemap may exist at a custom location or access may be restricted.' );
    } else {
        $results[] = wpd_result_item( 'Sitemap discovery', 'Detected — Please verify', 'No XML sitemap was found at the checked locations. Confirm whether your website publishes a sitemap at another URL.' );
    }
    // Validate the retrieved sitemap as bounded XML. Network access and DTD/entity declarations are not allowed.
    if ( $sitemap_found ) {
        $expected_root = $sitemap_root_type;
        $xml_error = '';
        $xml_doc = false;
        $loc_count = 0;
        $invalid_loc_count = 0;
        $root_valid = false;
        $sitemap_too_large = strlen( $sitemap_found_body ) >= 262144;
        $xml_validation_status = 'Issue found';

        // A response-size limit, a deliberately rejected DTD/entity declaration, or a missing
        // XML parser prevents verification; none alone proves the website's sitemap is invalid.
        if ( $sitemap_too_large ) {
            $xml_error = 'The retrieved sitemap reached the scanner response-size limit, so the complete XML could not be verified.';
            $xml_validation_status = 'Unable to verify';
        } elseif ( preg_match( '/<!DOCTYPE|<!ENTITY/i', $sitemap_found_body ) ) {
            $xml_error = 'DTD or entity declarations are not accepted by this check, so the sitemap was not parsed.';
            $xml_validation_status = 'Unable to verify';
        } elseif ( class_exists( 'DOMDocument' ) ) {
            $previous_internal_errors = libxml_use_internal_errors( true );
            $xml_doc = new DOMDocument();
            $loaded = $xml_doc->loadXML( $sitemap_found_body, LIBXML_NONET | LIBXML_COMPACT );
            $xml_errors = libxml_get_errors();
            libxml_clear_errors();
            libxml_use_internal_errors( $previous_internal_errors );
            if ( ! $loaded ) {
                $xml_error = 'The retrieved response could not be parsed as well-formed XML.';
            } else {
                $root_node = $xml_doc->documentElement;
                $actual_root = $root_node ? strtolower( $root_node->localName ) : '';
                $root_valid = in_array( $actual_root, array( 'urlset', 'sitemapindex' ), true ) && $actual_root === $expected_root;
                if ( $root_valid ) {
                    $expected_child = $actual_root === 'sitemapindex' ? 'sitemap' : 'url';
                    foreach ( $root_node->childNodes as $entry_node ) {
                        if ( XML_ELEMENT_NODE !== $entry_node->nodeType || strtolower( $entry_node->localName ) !== $expected_child ) { continue; }
                        $entry_loc = '';
                        foreach ( $entry_node->childNodes as $entry_child ) {
                            if ( XML_ELEMENT_NODE === $entry_child->nodeType && strtolower( $entry_child->localName ) === 'loc' ) {
                                $entry_loc = trim( $entry_child->textContent );
                                break;
                            }
                        }
                        if ( $entry_loc === '' ) { $invalid_loc_count++; continue; }
                        $loc_count++;
                        $loc_url = esc_url_raw( $entry_loc, array( 'http', 'https' ) );
                        if ( ! $loc_url || ! wp_http_validate_url( $loc_url ) ) { $invalid_loc_count++; }
                    }
                }
            }
        } else {
            $xml_error = 'This server does not provide the XML parser required for strict sitemap validation.';
            $xml_validation_status = 'Unable to verify';
        }

        if ( $xml_error !== '' ) {
            $validation_intro = $xml_validation_status === 'Issue found' ? 'The sitemap at ' . $sitemap_found_url . ' could not pass XML validation. ' : 'The sitemap at ' . $sitemap_found_url . ' could not be fully verified by this check. ';
            $results[] = wpd_result_item( 'Sitemap XML structure', $xml_validation_status, $validation_intro . $xml_error . ' Review the sitemap directly if you need confirmation.' );
        } elseif ( ! $root_valid ) {
            $results[] = wpd_result_item( 'Sitemap XML structure', 'Issue found', 'The retrieved XML at ' . $sitemap_found_url . ' did not have the expected ' . $expected_root . ' root element. Confirm that the URL points to a sitemap or sitemap index.' );
        } elseif ( $loc_count < 1 ) {
            $results[] = wpd_result_item( 'Sitemap XML structure', 'Detected — Please verify', 'The retrieved ' . ( $expected_root === 'sitemapindex' ? 'sitemap index' : 'URL sitemap' ) . ' is well-formed XML with the expected root, but no usable direct loc entries were found. Review the sitemap contents.' );
        } elseif ( $invalid_loc_count > 0 ) {
            $results[] = wpd_result_item( 'Sitemap XML structure', 'Detected — Please verify', sprintf( 'The retrieved %1$s at %2$s contains %3$d direct loc entr(y/ies), but %4$d entry or entries were empty or could not be recognized as valid public HTTP/HTTPS URLs. The XML parsed successfully; this is not a complete sitemap schema or destination check.', $expected_root === 'sitemapindex' ? 'sitemap index' : 'URL sitemap', $sitemap_found_url, $loc_count, $invalid_loc_count ) );
        } else {
            $results[] = wpd_result_item( 'Sitemap XML structure', 'Pass', sprintf( 'The retrieved %1$s at %2$s parsed as well-formed XML, has the expected root element, and contains %3$d direct loc entr(y/ies) with valid public HTTP/HTTPS URL formats. This does not validate the full sitemap schema or check whether every listed destination works.', $expected_root === 'sitemapindex' ? 'sitemap index' : 'URL sitemap', $sitemap_found_url, $loc_count ) );
        }
    } else {
        $results[] = wpd_result_item( 'Sitemap XML structure', 'Unable to verify', 'A sitemap was not retrieved, so its XML structure and loc entries could not be checked.' );
    }

    if ( ! is_string( $robots_body ) || trim( $robots_body ) === '' ) {
        $results[] = wpd_result_item( 'Sitemap reference in robots.txt', 'Unable to verify', 'A sitemap reference could not be checked because robots.txt was not readable.' );
    } elseif ( $robots_lists_sitemap ) {
        $results[] = wpd_result_item( 'Sitemap reference in robots.txt', 'Pass', 'robots.txt contains at least one valid, publicly addressable sitemap URL.' );
    } else {
        $results[] = wpd_result_item( 'Sitemap reference in robots.txt', 'Detected — Please verify', 'No sitemap reference was detected in robots.txt. A sitemap can still exist without being listed there.' );
    }


    // v2.0.9: treat unexpected HTTP 206 Partial Content as unverified across sampled checks.
    // v2.0.4: corrected sample limits and diagnostic wording; bounded checks remain sample-based.
    $page_origin = wpd_url_origin_key( $url );

    // 1. Canonical consistency (presence is reported separately above).
    if ( $canonical !== '' ) {
        $canonical_url = wpd_resolve_reference( $url, $canonical );
        $input_url = preg_replace( '/#.*$/', '', $url );
        $canonical_norm = $canonical_url ? untrailingslashit( $canonical_url ) : '';
        $input_norm = untrailingslashit( $input_url );
        if ( $canonical_url === '' ) {
            $results[] = wpd_result_item( 'Canonical URL consistency', 'Detected — Please verify', 'A canonical value exists, but it could not be resolved as a valid public HTTP/HTTPS URL. Review the canonical tag manually.' );
        } elseif ( $canonical_norm === $input_norm ) {
            $results[] = wpd_result_item( 'Canonical URL consistency', 'Pass', 'The canonical URL matches the submitted URL after a basic trailing-slash comparison. This does not assess every redirect or duplicate-content scenario.' );
        } else {
            $results[] = wpd_result_item( 'Canonical URL consistency', 'Detected — Please verify', 'The canonical URL (' . $canonical_url . ') differs from the submitted address (' . $input_url . '). This can be intentional; confirm the preferred page and redirect behaviour.' );
        }
    } else {
        $results[] = wpd_result_item( 'Canonical URL consistency', 'Unable to verify', 'No canonical URL was available to compare with the submitted address.' );
    }

    // 2. Inspect a maximum of two sitemap loc destinations, without recursively crawling them.
    $sitemap_tested = 0; $sitemap_ok = 0; $sitemap_failed = 0; $sitemap_unchecked = 0;
    if ( $sitemap_found && preg_match_all( '/<(?:[a-z0-9_-]+:)?loc\b[^>]*>\s*(.*?)\s*<\/(?:[a-z0-9_-]+:)?loc\s*>/is', $sitemap_found_body, $sitemap_loc_matches ) ) {
        foreach ( array_slice( $sitemap_loc_matches[1], 0, 2 ) as $sitemap_loc ) {
            $destination = wpd_resolve_reference( $sitemap_found_url, wp_strip_all_tags( $sitemap_loc ) );
            if ( ! $destination ) { $sitemap_unchecked++; continue; }
            $check = wpd_fetch_sample( $destination, 'text/html,application/xml,text/xml,*/*', 65536 );
            $sitemap_tested++;
            if ( is_wp_error( $check ) ) { $sitemap_unchecked++; continue; }
            $code = (int) wp_remote_retrieve_response_code( $check );
            if ( $code >= 200 && $code < 300 && $code !== 206 ) { $sitemap_ok++; }
            elseif ( in_array( $code, array( 404, 410 ), true ) ) { $sitemap_failed++; }
            else { $sitemap_unchecked++; }
        }
    }
    if ( $sitemap_tested === 0 ) {
        $results[] = wpd_result_item( 'Sampled sitemap destinations', 'Unable to verify', 'No sitemap destinations were available for this limited sample, or the sitemap could not be parsed by this check.' );
    } elseif ( $sitemap_failed > 0 ) {
        $results[] = wpd_result_item( 'Sampled sitemap destinations', 'Detected — Please verify', sprintf( 'Among %1$d sampled destination(s), %2$d returned HTTP 404/410 responses (likely missing; verify before treating them as broken), %3$d returned an HTTP 2xx response, and %4$d could not be verified. Other HTTP errors may reflect access restrictions, rate limits, or server restrictions. Only up to two entries are sampled.', $sitemap_tested, $sitemap_failed, $sitemap_ok, $sitemap_unchecked ) );
    } else {
        $results[] = wpd_result_item( 'Sampled sitemap destinations', $sitemap_unchecked ? 'Detected — Please verify' : 'Pass', sprintf( 'Checked %1$d sitemap destination(s): %2$d returned HTTP 2xx responses and %3$d could not be verified, including unresolved redirects and other HTTP errors. Only up to two entries are sampled; this is not a full sitemap audit.', $sitemap_tested, $sitemap_ok, $sitemap_unchecked ) );
    }

    // Collect one additional same-origin HTML page, excluding duplicate forms of the submitted URL.
    $internal_candidates = array(); $internal_pages = array( array( 'url' => $url, 'html' => $html ) );
    $submitted_page_key = wpd_url_comparison_key( $url );
    if ( preg_match_all( '/<a\b[^>]*>/i', $html, $anchor_tags ) ) {
        foreach ( $anchor_tags[0] as $anchor_tag ) {
            $href = wpd_get_attribute( $anchor_tag, 'href' );
            $candidate = wpd_resolve_reference( $url, $href );
            if ( ! $candidate ) { continue; }
            $candidate_key = wpd_url_comparison_key( $candidate );
            if ( $candidate_key === '' || $candidate_key === $submitted_page_key || isset( $internal_candidates[ $candidate_key ] ) ) { continue; }
            $candidate_origin = wpd_url_origin_key( $candidate );
            if ( $candidate_origin !== $page_origin ) { continue; }
            $internal_candidates[ $candidate_key ] = $candidate;
            if ( count( $internal_candidates ) >= 1 ) { break; }
        }
    }
    $internal_page_attempted = count( $internal_candidates );
    $internal_page_failures = array();
    foreach ( array_values( $internal_candidates ) as $internal_url ) {
        $page_response = wpd_fetch_sample( $internal_url, 'text/html,application/xhtml+xml', 262144 );
        if ( is_wp_error( $page_response ) ) {
            $request_error = sanitize_text_field( $page_response->get_error_message() );
            if ( $request_error === '' ) { $request_error = 'request failed (no additional reason supplied)'; }
            if ( function_exists( 'mb_substr' ) ) { $request_error = mb_substr( $request_error, 0, 180 ); }
            else { $request_error = substr( $request_error, 0, 180 ); }
            $internal_page_failures[] = 'request failed: ' . $request_error;
            continue;
        }
        $page_code = (int) wp_remote_retrieve_response_code( $page_response );
        $page_body = wp_remote_retrieve_body( $page_response );
        $page_type = strtolower( (string) wp_remote_retrieve_header( $page_response, 'content-type' ) );
        $looks_like_html = ( strpos( $page_type, 'text/html' ) !== false || strpos( $page_type, 'application/xhtml+xml' ) !== false || preg_match( '/<html\b|<head\b/i', $page_body ) );
        if ( $page_code >= 200 && $page_code < 300 && $page_body !== '' && $looks_like_html ) {
            $internal_pages[] = array( 'url' => $internal_url, 'html' => $page_body );
        } else {
            if ( in_array( $page_code, array( 404, 410 ), true ) ) { $failure_reason = 'HTTP ' . $page_code . ' (likely missing)'; }
            elseif ( $page_code >= 400 || $page_code === 0 ) { $failure_reason = 'HTTP ' . ( $page_code > 0 ? $page_code : 'status unavailable' ); }
            elseif ( $page_code === 206 ) { $failure_reason = 'HTTP 206 Partial Content'; }
            elseif ( $page_code >= 300 && $page_code < 400 ) { $failure_reason = 'HTTP ' . $page_code . ' redirect was not resolved to a final HTML page'; }
            elseif ( $page_body === '' ) { $failure_reason = 'empty response body'; }
            else { $failure_reason = 'response did not appear to be HTML'; }
            $internal_page_failures[] = $failure_reason;
        }
    }
    if ( $internal_page_attempted === 0 ) {
        $internal_crawl_status = 'Unable to verify';
    } else {
        $internal_crawl_status = ( count( $internal_pages ) > 1 && empty( $internal_page_failures ) ) ? 'Pass' : 'Detected — Please verify';
    }
    $internal_crawl_detail = sprintf( 'Retrieved %1$d page(s), including the submitted page. Attempted %2$d additional same-origin page(s); %3$d could not be retrieved as HTML.', count( $internal_pages ), $internal_page_attempted, count( $internal_page_failures ) );
    if ( $internal_page_attempted === 0 ) {
        $internal_crawl_detail .= ' No eligible additional same-origin page was found in the retrieved homepage HTML, so the additional-page crawl could not be evaluated.';
    }
    if ( ! empty( $internal_page_failures ) ) {
        $internal_failure_counts = array_count_values( $internal_page_failures );
        $internal_failure_summary = array();
        foreach ( $internal_failure_counts as $failure_reason => $failure_count ) { $internal_failure_summary[] = $failure_reason . ': ' . $failure_count; }
        $internal_crawl_detail .= ' Reasons: ' . implode( '; ', $internal_failure_summary ) . '.';
    }
    $internal_crawl_detail .= ' This is a bounded sample, not a full-site crawl; pages linked only through JavaScript or not linked from the homepage may be missed.';
    $results[] = wpd_result_item( 'Internal-page sample crawl', $internal_crawl_status, $internal_crawl_detail );

    // 3. Sample link destination status across retrieved pages (maximum four distinct links).
    $link_sample = array();
    foreach ( $internal_pages as $page ) {
        if ( preg_match_all( '/<a\b[^>]*>/i', $page['html'], $page_anchors ) ) {
            foreach ( $page_anchors[0] as $page_anchor ) {
                $href = wpd_get_attribute( $page_anchor, 'href' );
                $link_url = wpd_resolve_reference( $page['url'], $href );
                if ( $link_url && ! isset( $link_sample[ $link_url ] ) ) { $link_sample[ $link_url ] = true; }
                if ( count( $link_sample ) >= 4 ) { break 2; }
            }
        }
    }
    $link_checked = 0; $link_bad = 0; $link_unknown = 0; $link_redirect = 0; $link_redirect_issues = 0;
    foreach ( array_keys( $link_sample ) as $link_url ) {
        // Use the same hop-by-hop redirect checker as the homepage sample so successful redirects
        // are treated as normal and unresolved chains are not confused with broken destinations.
        $link_trace = wpd_check_redirect_chain( $link_url, 5 );
        $link_trace_status = isset( $link_trace['status'] ) ? $link_trace['status'] : 'unverified';
        $link_code = isset( $link_trace['final_code'] ) ? (int) $link_trace['final_code'] : 0;
        $link_hops = isset( $link_trace['redirect_count'] ) ? (int) $link_trace['redirect_count'] : 0;
        if ( $link_trace_status !== 'unverified' && $link_code > 0 ) { $link_checked++; }
        if ( $link_hops > 0 && $link_trace_status === 'normal_redirect' ) { $link_redirect++; }
        if ( in_array( $link_trace_status, array( 'redirect_loop', 'excessive_chain', 'missing_location' ), true ) ) { $link_redirect_issues++; }
        if ( in_array( $link_code, array( 404, 410 ), true ) ) { $link_bad++; }
        elseif ( in_array( $link_trace_status, array( 'unverified', 'partial_content', 'failed_destination' ), true ) || $link_code >= 400 || $link_code === 0 ) { $link_unknown++; }
    }
    if ( empty( $link_sample ) ) { $link_status = 'Unable to verify'; }
    elseif ( $link_redirect_issues > 0 ) { $link_status = 'Issue found'; }
    elseif ( $link_bad > 0 || $link_unknown > 0 ) { $link_status = 'Detected — Please verify'; }
    else { $link_status = 'Pass'; }
    if ( empty( $link_sample ) ) {
        $link_detail = 'No eligible links were found across the retrieved pages, so no link destinations could be tested. This is not a pass; the check could not be evaluated. Maximum sample: four links across the retrieved pages.';
    } else {
        $link_detail = sprintf( 'Sampled %1$d distinct link(s): %2$d returned HTTP 404/410 responses (likely missing; verify before treating them as broken), %3$d completed a redirect chain to a successful response, %4$d could not be verified or returned other HTTP errors, and %5$d had redirect-chain problems (such as a loop, excessive redirects, or a missing/invalid Location). Other HTTP errors may reflect access restrictions, rate limits, or server restrictions. Successful redirects are treated as normal. Maximum sample: four links across the retrieved pages.', count( $link_sample ), $link_bad, $link_redirect, $link_unknown, $link_redirect_issues );
    }
    $results[] = wpd_result_item( 'Sampled link destinations', $link_status, $link_detail );

    // 4. Sample images and document resources from the retrieved pages (maximum four distinct URLs).
    $resource_sample = array(); $image_urls = array();
    foreach ( $internal_pages as $page ) {
        if ( preg_match_all( '/<(?:img|source)\b[^>]*>/i', $page['html'], $media_tags ) ) {
            foreach ( $media_tags[0] as $media_tag ) {
                $src = wpd_get_attribute( $media_tag, 'src' );
                if ( $src === '' ) { $src = wpd_get_attribute( $media_tag, 'data-src' ); }
                $resource_url = wpd_resolve_reference( $page['url'], $src );
                if ( $resource_url ) { $image_urls[ $resource_url ] = true; $resource_sample[ $resource_url ] = 'image'; }
                if ( count( $resource_sample ) >= 4 ) { break 2; }
            }
        }
        if ( preg_match_all( '/<a\b[^>]*>/i', $page['html'], $doc_anchors ) ) {
            foreach ( $doc_anchors[0] as $doc_anchor ) {
                $href = wpd_get_attribute( $doc_anchor, 'href' );
                if ( preg_match( '/\.(?:pdf|doc|docx)(?:[?#]|$)/i', $href ) ) {
                    $doc_url = wpd_resolve_reference( $page['url'], $href );
                    if ( $doc_url ) { $resource_sample[ $doc_url ] = 'document'; }
                }
                if ( count( $resource_sample ) >= 4 ) { break 2; }
            }
        }
    }
    $resource_checked = 0; $resource_missing = 0; $resource_unknown = 0; $resource_partial = 0;
    foreach ( $resource_sample as $resource_url => $resource_kind ) {
        $resource_response = wpd_fetch_sample( $resource_url, '*/*', 65536 );
        if ( is_wp_error( $resource_response ) ) { $resource_unknown++; continue; }
        $resource_code = (int) wp_remote_retrieve_response_code( $resource_response );
        if ( $resource_code === 206 ) { $resource_unknown++; $resource_partial++; }
        elseif ( $resource_code >= 200 && $resource_code < 300 ) { $resource_checked++; }
        elseif ( in_array( $resource_code, array( 404, 410 ), true ) ) { $resource_checked++; $resource_missing++; }
        else { $resource_unknown++; }
    }
    $resource_status = ( $resource_missing || $resource_partial ) ? 'Detected — Please verify' : ( $resource_checked > 0 ? ( $resource_unknown > 0 ? 'Detected — Please verify' : 'Pass' ) : 'Unable to verify' );
    $results[] = wpd_result_item( 'Sampled image and document resources', $resource_status, sprintf( 'Sampled %1$d image/document resource(s): %2$d returned HTTP 404/410 responses (likely missing; verify before treating them as broken), and %3$d could not be verified, including unresolved redirects and other HTTP errors. Other errors may reflect access restrictions, rate limits, or server restrictions. HTTP 404/410 results are marked for review as likely missing rather than treated as conclusively broken. The sample is limited to four distinct resources across the retrieved pages.', count( $resource_sample ), $resource_missing, $resource_unknown ) );

    // 5. Linked CSS mixed-content reference scan (only a few stylesheets, no CSS execution).
    $css_urls = array();
    if ( preg_match_all( '/<link\b[^>]*>/i', $html, $style_tags ) ) {
        foreach ( $style_tags[0] as $style_tag ) {
            if ( stripos( ' ' . wpd_get_attribute( $style_tag, 'rel' ) . ' ', 'stylesheet' ) === false ) { continue; }
            $css_url = wpd_resolve_reference( $url, wpd_get_attribute( $style_tag, 'href' ) );
            if ( $css_url ) { $css_urls[ $css_url ] = true; }
            if ( count( $css_urls ) >= 2 ) { break; }
        }
    }
    $css_checked = 0; $css_mixed = 0; $css_unknown = 0;
    foreach ( array_keys( $css_urls ) as $css_url ) {
        $css_response = wpd_fetch_sample( $css_url, 'text/css,*/*', 131072 );
        if ( is_wp_error( $css_response ) ) { $css_unknown++; continue; }
        $css_code = (int) wp_remote_retrieve_response_code( $css_response );
        if ( $css_code < 200 || $css_code >= 300 || $css_code === 206 ) { $css_unknown++; continue; }
        $css_body = wp_remote_retrieve_body( $css_response );
        if ( strlen( $css_body ) >= 131072 ) { $css_unknown++; continue; }
        $css_checked++;
        if ( preg_match( '#url\(\s*["\']?http://#i', $css_body ) || preg_match( '#@import\s+["\']http://#i', $css_body ) ) { $css_mixed++; }
    }
    $css_status = $css_mixed ? 'Detected — Please verify' : ( $css_unknown ? 'Detected — Please verify' : ( $css_checked ? 'Pass' : 'Unable to verify' ) );
    $results[] = wpd_result_item( 'Linked CSS mixed-content references', $css_status, sprintf( 'Fully sampled %1$d stylesheet(s) and found HTTP URL references in %2$d stylesheet(s); %3$d stylesheet(s) could not be fully checked or reached the 128 KB sample limit. Maximum sample: two stylesheets. Inline and dynamically generated CSS is not covered.', $css_checked, $css_mixed, $css_unknown ) );

    // 6. Linked JavaScript HTTP URL literal scan (text search only; scripts are never executed).
    $js_urls = array();
    if ( preg_match_all( '/<(?:script)\b[^>]*>/i', $html, $script_tags ) ) {
        foreach ( $script_tags[0] as $script_tag ) {
            $src = wpd_get_attribute( $script_tag, 'src' ); $js_url = wpd_resolve_reference( $url, $src );
            if ( $js_url ) { $js_urls[ $js_url ] = true; }
            if ( count( $js_urls ) >= 2 ) { break; }
        }
    }
    $js_checked = 0; $js_http_refs = 0; $js_unknown = 0;
    foreach ( array_keys( $js_urls ) as $js_url ) {
        $js_response = wpd_fetch_sample( $js_url, 'application/javascript,text/javascript,*/*', 131072 );
        if ( is_wp_error( $js_response ) ) { $js_unknown++; continue; }
        $js_code = (int) wp_remote_retrieve_response_code( $js_response );
        if ( $js_code < 200 || $js_code >= 300 || $js_code === 206 ) { $js_unknown++; continue; }
        $js_body = wp_remote_retrieve_body( $js_response );
        if ( strlen( $js_body ) >= 131072 ) { $js_unknown++; continue; }
        $js_checked++;
        if ( preg_match( '#https?://[^\s"\']+#i', $js_body ) ) { $js_http_refs++; }
    }
    $js_status = $js_http_refs ? 'Detected — Please verify' : ( $js_unknown ? 'Detected — Please verify' : ( $js_checked ? 'Pass' : 'Unable to verify' ) );
    $results[] = wpd_result_item( 'Linked JavaScript URL references', $js_status, sprintf( 'Fully sampled %1$d script file(s); %2$d contained literal HTTP/HTTPS URL strings and %3$d could not be fully checked or reached the 128 KB sample limit. Maximum sample: two scripts. Text matches may be unrelated to loaded resources and do not prove mixed content.', $js_checked, $js_http_refs, $js_unknown ) );

    // 7. Approximate transfer-size sampling for up to two image resources.
    $image_size_checked = 0; $image_size_large = 0; $image_size_unknown = 0; $image_size_total = 0;
    foreach ( array_slice( array_keys( $image_urls ), 0, 2 ) as $image_url ) {
        $image_response = wpd_fetch_sample( $image_url, 'image/*,*/*', 524288 );
        if ( is_wp_error( $image_response ) ) { $image_size_unknown++; continue; }
        $image_code = (int) wp_remote_retrieve_response_code( $image_response );
        if ( $image_code < 200 || $image_code >= 300 || $image_code === 206 ) { $image_size_unknown++; continue; }
        $image_size_checked++; $image_body = wp_remote_retrieve_body( $image_response ); $bytes = strlen( $image_body ); $image_size_total += $bytes;
        if ( $bytes >= 250000 ) { $image_size_large++; }
    }
    $image_size_status = $image_size_large ? 'Detected — Please verify' : ( ( $image_size_unknown > 0 && $image_size_checked > 0 ) ? 'Detected — Please verify' : ( $image_size_checked > 0 ? 'Pass' : 'Unable to verify' ) );
    $results[] = wpd_result_item( 'Sampled image transfer size', $image_size_status, sprintf( 'Measured response-body size for %1$d sampled image(s), with %2$d at or above 250 KB and %3$d not measurable. Sampled total: about %4$s KB. Responses are capped at 512 KB each, so larger files may be truncated and these are approximate sizes.', $image_size_checked, $image_size_large, $image_size_unknown, number_format_i18n( $image_size_total / 1024, 1 ) ) );

    // 8. Response compression headers.
    $content_encoding = (string) wp_remote_retrieve_header( $response, 'content-encoding' );
        $compression_seen = ( $content_encoding !== '' && strtolower( trim( $content_encoding ) ) !== 'identity' );
    $results[] = wpd_result_item( 'Response compression headers', $compression_seen ? 'Pass' : 'Detected — Please verify', $compression_seen ? 'The homepage response includes a non-identity Content-Encoding header. This does not measure compression savings or confirm all assets are compressed.' : 'No non-identity Content-Encoding header was visible in the homepage response. A proxy may alter headers, and this check does not measure actual compression savings.' );

    // 9. Browser caching response headers: inspect the homepage and up to two static assets.
    $cache_header_names = array( 'cache-control' => 'Cache-Control', 'expires' => 'Expires', 'etag' => 'ETag', 'last-modified' => 'Last-Modified', 'age' => 'Age' );
    $homepage_cache_names = array();
    foreach ( $cache_header_names as $header_key => $header_label ) {
        if ( (string) wp_remote_retrieve_header( $response, $header_key ) !== '' ) { $homepage_cache_names[] = $header_label; }
    }
    $static_cache_urls = array();
    if ( preg_match_all( '/<link\b[^>]*>/i', $html, $cache_link_tags ) ) {
        foreach ( $cache_link_tags[0] as $cache_link_tag ) {
            $rel = strtolower( wpd_get_attribute( $cache_link_tag, 'rel' ) );
            $href = wpd_get_attribute( $cache_link_tag, 'href' );
            if ( strpos( ' ' . $rel . ' ', ' stylesheet ' ) === false || $href === '' ) { continue; }
            $asset_url = wpd_resolve_reference( $url, $href );
            if ( $asset_url ) { $static_cache_urls[ $asset_url ] = true; }
            if ( count( $static_cache_urls ) >= 2 ) { break; }
        }
    }
    if ( count( $static_cache_urls ) < 2 && preg_match_all( '/<img\b[^>]*>/i', $html, $cache_image_tags ) ) {
        foreach ( $cache_image_tags[0] as $cache_image_tag ) {
            $src = wpd_get_attribute( $cache_image_tag, 'src' );
            if ( $src === '' ) { $src = wpd_get_attribute( $cache_image_tag, 'data-src' ); }
            $asset_url = wpd_resolve_reference( $url, $src );
            if ( $asset_url ) { $static_cache_urls[ $asset_url ] = true; }
            if ( count( $static_cache_urls ) >= 2 ) { break; }
        }
    }
    $asset_cache_checked = 0; $asset_cache_header_count = 0; $asset_cache_unchecked = 0; $asset_cache_names = array();
    foreach ( array_keys( $static_cache_urls ) as $cache_asset_url ) {
        $cache_asset_response = wpd_fetch_sample( $cache_asset_url, '*/*', 16384 );
        if ( is_wp_error( $cache_asset_response ) ) { $asset_cache_unchecked++; continue; }
        $asset_cache_code = (int) wp_remote_retrieve_response_code( $cache_asset_response );
        if ( $asset_cache_code < 200 || $asset_cache_code >= 300 || $asset_cache_code === 206 ) { $asset_cache_unchecked++; continue; }
        $asset_cache_checked++;
        foreach ( $cache_header_names as $header_key => $header_label ) {
            if ( (string) wp_remote_retrieve_header( $cache_asset_response, $header_key ) !== '' ) {
                $asset_cache_header_count++;
                $asset_cache_names[ $header_label ] = true;
            }
        }
    }
    $cache_seen = ! empty( $homepage_cache_names ) || $asset_cache_header_count > 0;
    $homepage_cache_text = ! empty( $homepage_cache_names ) ? 'Homepage: ' . implode( ', ', $homepage_cache_names ) . '.' : 'Homepage: no common cache-related headers detected.';
    $asset_cache_text = ' Static asset sample: checked ' . $asset_cache_checked . ' resource(s), with cache-related headers found on ' . ( $asset_cache_header_count > 0 ? 'one or more sampled response(s)' : 'none of the checked responses' ) . '; ' . $asset_cache_unchecked . ' could not be checked.';
    if ( ! empty( $asset_cache_names ) ) { $asset_cache_text .= ' Header names seen on assets: ' . implode( ', ', array_keys( $asset_cache_names ) ) . '.'; }
    $cache_detail = $homepage_cache_text . $asset_cache_text . ' Maximum sample: two CSS/image resources. Header presence alone does not establish a suitable cache duration; HTML and static assets may intentionally use different policies, and CDN/server rules can vary by URL.';
    $results[] = wpd_result_item( 'Browser caching response headers', $cache_seen ? 'Pass' : 'Detected — Please verify', $cache_detail );

    // 10. HTML language declaration.
    $html_lang = '';
    if ( preg_match( '/<html\b[^>]*>/i', $html, $html_tag_match ) ) { $html_lang = trim( wpd_get_attribute( $html_tag_match[0], 'lang' ) ); }
    $results[] = wpd_result_item( 'HTML language declaration', $html_lang !== '' ? 'Pass' : 'Detected — Please verify', $html_lang !== '' ? 'The HTML element declares lang="' . $html_lang . '". This check does not verify whether the language value accurately describes all page content.' : 'No lang attribute was detected on the retrieved HTML element. Declare the primary language to help assistive technology and other user agents.' );

    // 11. Social-sharing metadata.
    $social_keys = array();
    if ( preg_match_all( '/<meta\b[^>]*>/i', $html, $social_meta_tags ) ) {
        foreach ( $social_meta_tags[0] as $social_meta_tag ) {
            $property = strtolower( trim( wpd_get_attribute( $social_meta_tag, 'property' ) ) );
            $name = strtolower( trim( wpd_get_attribute( $social_meta_tag, 'name' ) ) );
            if ( strpos( $property, 'og:' ) === 0 || strpos( $name, 'twitter:' ) === 0 ) { $social_keys[ $property !== '' ? $property : $name ] = true; }
        }
    }
    $social_count = count( $social_keys );
    $results[] = wpd_result_item( 'Social-sharing metadata', $social_count >= 2 ? 'Pass' : 'Detected — Please verify', $social_count >= 2 ? sprintf( '%1$d Open Graph/Twitter metadata field name(s) were detected in the retrieved HTML. This does not validate values or guarantee how every social platform will render a preview.', $social_count ) : sprintf( 'Only %1$d Open Graph/Twitter metadata field name(s) were detected. Social previews may still work, but review title, description, and image metadata if sharing previews matter.', $social_count ) );

    return array( 'url' => $url, 'http_code' => $http_code, 'results' => $results );
}

function wpd_render_results( $scan ) {
    if ( isset( $scan['error'] ) ) { echo '<div class="wpd-error">' . esc_html( $scan['error'] ) . '</div>'; return; }
    echo '<div class="wpd-results"><h3>Website Health Report</h3><p class="wpd-scanned-url">Scanned address: ' . esc_html( $scan['url'] ) . '</p>';
    $status_counts = array( 'Pass' => 0, 'Issue found' => 0, 'Detected — Please verify' => 0, 'Unable to verify' => 0 );
    foreach ( $scan['results'] as $summary_item ) {
        $summary_status = isset( $summary_item['status'] ) ? $summary_item['status'] : 'Unable to verify';
        if ( ! isset( $status_counts[ $summary_status ] ) ) { $summary_status = 'Unable to verify'; }
        $status_counts[ $summary_status ]++;
    }
    echo '<div class="wpd-summary" aria-label="Health check summary"><strong class="wpd-summary-title">Check summary</strong><div class="wpd-summary-grid">';
    foreach ( $status_counts as $summary_status => $summary_count ) {
        $summary_class = 'wpd-summary-card-default';
        if ( $summary_status === 'Pass' ) { $summary_class = 'wpd-summary-card-pass'; }
        elseif ( $summary_status === 'Issue found' ) { $summary_class = 'wpd-summary-card-issue'; }
        elseif ( $summary_status === 'Detected — Please verify' ) { $summary_class = 'wpd-summary-card-review'; }
        echo '<div class="wpd-summary-card ' . esc_attr( $summary_class ) . '"><span class="wpd-summary-card-label">' . esc_html( $summary_status ) . '</span><strong class="wpd-summary-card-count">' . esc_html( (string) $summary_count ) . '</strong></div>';
    }
    echo '</div><p>Each item is a specific check, not an overall guarantee that the website is secure, accessible, or search-engine ready.</p></div>';
    foreach ( $scan['results'] as $item ) {
        $status_class = sanitize_html_class( strtolower( str_replace( array( ' ', '—' ), array( '-', '-' ), $item['status'] ) ) );
        echo '<div class="wpd-result-item"><div class="wpd-result-heading"><strong>' . esc_html( $item['name'] ) . '</strong>';
        echo '<span class="wpd-status wpd-status-' . esc_attr( $status_class ) . '">' . esc_html( $item['status'] ) . '</span></div><p>' . esc_html( $item['detail'] ) . '</p></div>';
    }
    echo '</div>';
}

function wpd_render_shortcode() {
    $scan = null;
    if ( isset( $_SERVER['REQUEST_METHOD'] ) && strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) === 'POST' && isset( $_POST['wpd_scan_submit'] ) ) {
        $nonce = isset( $_POST['wpd_scan_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['wpd_scan_nonce'] ) ) : '';
        if ( ! wp_verify_nonce( $nonce, 'wpd_scan_action' ) ) {
            $scan = array( 'error' => 'Your form session could not be verified. Refresh the page and try again.' );
        } else {
            $input = isset( $_POST['wpd_url'] ) ? sanitize_text_field( wp_unslash( $_POST['wpd_url'] ) ) : '';
            $url = wpd_normalize_url( $input );
            if ( is_wp_error( $url ) ) { $scan = array( 'error' => $url->get_error_message() ); }
            else { $scan = wpd_scan_website( $url ); }
        }
    }
    ob_start();
    ?>
    <style>
        .wpd-wrap{max-width:920px;margin:30px auto;color:#253142;font-family:inherit}
        .wpd-hero{padding:32px 24px;border-radius:14px;background:#263746;color:#fff;text-align:center;box-sizing:border-box}
        .wpd-hero h2{margin:0 0 10px;color:#fff;font-size:30px;line-height:1.25}
        .wpd-hero p{margin:0;color:#edf2f6;line-height:1.6}
        .wpd-form{display:flex;align-items:stretch;gap:10px;margin:24px 0}
        .wpd-form input[type="text"]{flex:1;min-width:0;padding:14px;border:1px solid #cbd5df;border-radius:7px;background:#fff;color:#253142;font-family:inherit;font-size:16px;box-sizing:border-box}
        .wpd-form input[type="text"]:focus{outline:none;border-color:#087f8c;box-shadow:0 0 0 2px rgba(8,127,140,.12)}
        .wpd-form button[type="submit"]{padding:14px 20px;border:0;border-radius:7px;background:#087f8c;color:#fff;font-family:inherit;font-size:15px;font-weight:700;white-space:nowrap;cursor:pointer;transition:background .2s ease}
        .wpd-form button[type="submit"]:hover{background:#066772;color:#fff}
        .wpd-results{margin-top:30px}.wpd-results h3{margin-bottom:8px;color:#263746}.wpd-scanned-url{overflow-wrap:anywhere;color:#555}
        .wpd-summary{margin:16px 0;padding:16px;border:1px solid #d8e0e7;border-radius:8px;background:#f7f9fb;color:#253142}.wpd-summary-title{display:block;margin-bottom:12px}.wpd-summary-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}.wpd-summary-card{display:flex;flex-direction:column;align-items:flex-start;justify-content:flex-start;gap:12px;min-width:0;min-height:104px;padding:14px 12px;border:1px solid #d8e0e7;border-radius:8px;background:#fff;box-sizing:border-box}.wpd-summary-card-label{display:block;width:100%;font-size:13px;font-weight:700;line-height:1.35;overflow-wrap:anywhere}.wpd-summary-card-count{display:flex;align-items:center;justify-content:center;min-width:42px;min-height:42px;padding:0 8px;border-radius:8px;background:#eef2f6;color:#344054;font-size:22px;line-height:1;box-sizing:border-box}.wpd-summary-card-pass{border-color:#b8e2c5;background:#f4fbf6}.wpd-summary-card-pass .wpd-summary-card-count{background:#d9f2e1;color:#176b36}.wpd-summary-card-issue{border-color:#f0c4be;background:#fff7f6}.wpd-summary-card-issue .wpd-summary-card-count{background:#ffe4df;color:#a52b1d}.wpd-summary-card-review{border-color:#ead79c;background:#fffbec}.wpd-summary-card-review .wpd-summary-card-count{background:#fff0bd;color:#795500}.wpd-summary-card-default{border-color:#d8e0e7;background:#fff}.wpd-summary p{margin:12px 0 0;color:#4b5563;line-height:1.5}
        .wpd-result-item{margin:12px 0;padding:16px;border:1px solid #e0e5ea;border-radius:8px;background:#fff}
        .wpd-result-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}
        .wpd-result-item p{margin:10px 0 0;line-height:1.6;overflow-wrap:anywhere;color:#4b5563}
        .wpd-status{display:inline-block;padding:5px 9px;border-radius:4px;background:#eef2f6;color:#344054;font-size:12px;font-weight:700}
        .wpd-status-pass{background:#e6f6ec;color:#176b36}.wpd-status-issue-found{background:#fff0ed;color:#a52b1d}
        .wpd-status-detected---please-verify{background:#fff5d8;color:#795500}.wpd-status-unable-to-verify{background:#eef2f6;color:#344054}
        .wpd-error{margin:20px 0;padding:15px;border:1px solid #f1c6c2;border-radius:7px;background:#fff1f0;color:#922b21;overflow-wrap:anywhere}
        @media(max-width:700px){.wpd-summary-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
        @media(max-width:600px){.wpd-hero{padding:25px 18px}.wpd-hero h2{font-size:25px}.wpd-form{flex-direction:column}.wpd-form input[type="text"],.wpd-form button[type="submit"]{width:100%}}
    </style>
    <div class="wpd-wrap">
        <div class="wpd-hero"><h2>WordPress Doctor</h2><p>Check important technical and SEO elements of your website.</p></div>
        <form class="wpd-form" method="post">
            <?php wp_nonce_field( 'wpd_scan_action', 'wpd_scan_nonce' ); ?>
            <input type="text" inputmode="url" autocomplete="url" id="wpd_url" name="wpd_url" placeholder="example.com" aria-label="Website address" required>
            <button type="submit" name="wpd_scan_submit" value="1">Check My Website</button>
        </form>
        <?php if ( is_array( $scan ) ) { wpd_render_results( $scan ); } ?>
    </div>
    <?php
    return ob_get_clean();
}