<?php
if (!defined('ABSPATH')) exit;

class AIIO_Usage {
    public static function get_used_attachment_ids($limit = 5000) {
        $ids = [];
        $post_types = apply_filters('aiio_used_post_types', ['post', 'page', 'product']);

        $q = new WP_Query([
            'post_type'      => $post_types,
            'post_status'    => 'publish',
            'posts_per_page' => min(500, $limit),
            'fields'         => 'ids',
            'no_found_rows'  => true,
        ]);

        foreach ($q->posts as $post_id) {
            $thumb = (int) get_post_thumbnail_id($post_id);
            if ($thumb) {
                $ids[$thumb] = true;
            }
            $content = get_post_field('post_content', $post_id);
            if (preg_match_all('/wp-image-(\d+)/', $content, $m)) {
                foreach ($m[1] as $aid) {
                    $ids[(int) $aid] = true;
                }
            }
            if (preg_match_all('/image="(\d+)"/', $content, $m2)) {
                foreach ($m2[1] as $aid) {
                    $ids[(int) $aid] = true;
                }
            }
        }

        return array_map('intval', array_keys($ids));
    }

    public static function matches_exclude_pattern($filename, $patterns) {
        $filename = (string) $filename;
        foreach ($patterns as $pattern) {
            $pattern = trim($pattern);
            if ($pattern === '') {
                continue;
            }
            if (fnmatch($pattern, $filename, FNM_CASEFOLD)) {
                return true;
            }
        }
        return false;
    }

    public static function parse_exclude_patterns($raw) {
        $lines = preg_split('/\r\n|\r|\n/', (string) $raw);
        return array_values(array_filter(array_map('trim', $lines)));
    }
}
