<?php
defined( 'ABSPATH' ) || exit;

class SITECL_Image_Audit {

    /** Flag images larger than this (bytes). */
    private const SIZE_THRESHOLD = 512000; // 500 KB

    public static function scan(): array {
        $attachments = get_posts( [
            'post_type'      => 'attachment',
            'post_mime_type' => 'image',
            'post_status'    => 'inherit',
            'posts_per_page' => 500,
            'fields'         => 'ids',
        ] );

        if ( empty( $attachments ) ) {
            return [];
        }

        $oversized = [];

        foreach ( $attachments as $id ) {
            $path = get_attached_file( $id );
            if ( ! $path || ! file_exists( $path ) ) {
                continue;
            }

            $size = filesize( $path );
            if ( $size < self::SIZE_THRESHOLD ) {
                continue;
            }

            $image_meta = wp_get_attachment_metadata( $id );
            $width      = $image_meta['width']  ?? 0;
            $height     = $image_meta['height'] ?? 0;
            $used_in    = self::find_usage( $id );

            $oversized[] = [
                'id'       => $id,
                'filename' => basename( $path ),
                'size_kb'  => round( $size / 1024 ),
                'width'    => $width,
                'height'   => $height,
                'edit_url' => get_edit_post_link( $id, 'raw' ),
                'used_in'  => $used_in,
            ];
        }

        if ( empty( $oversized ) ) {
            return [];
        }

        // Sort by file size descending.
        usort( $oversized, fn( $a, $b ) => $b['size_kb'] <=> $a['size_kb'] );

        $issues = [];
        foreach ( $oversized as $img ) {
            $issues[] = [
                'type'     => 'image_audit',
                'severity' => $img['size_kb'] >= 1024 ? 'warning' : 'info',
                'title'    => sprintf(
                    /* translators: %1$s filename, %2$s size in KB */
                    __( '%1$s is %2$s KB (too large)', 'site-cliniq' ),
                    esc_html( $img['filename'] ),
                    number_format( $img['size_kb'] )
                ),
                'detail'   => sprintf(
                    /* translators: %1$d: image width in pixels, %2$d: image height in pixels, %3$d: number of posts using this image */
                    __( 'Dimensions: %1$dx%2$d px. Used in %3$d post(s). Compress this image to improve page load speed.', 'site-cliniq' ),
                    $img['width'],
                    $img['height'],
                    count( $img['used_in'] )
                ),
                'image'    => $img,
            ];
        }

        return $issues;
    }

    /** Return array of post IDs that reference this attachment in their content. */
    private static function find_usage( int $attachment_id ): array {
        global $wpdb;

        $url = wp_get_attachment_url( $attachment_id );
        if ( ! $url ) {
            return [];
        }

        // Strip protocol for wider matching.
        $pattern = '%' . $wpdb->esc_like( preg_replace( '/^https?:/', '', $url ) ) . '%';

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        return $wpdb->get_col(
            $wpdb->prepare(
                "SELECT ID FROM {$wpdb->posts}
                 WHERE post_status = 'publish'
                   AND post_content LIKE %s
                 LIMIT 20",
                $pattern
            )
        );
    }
}
