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

/* -------------------------------------------------------
   SMART MEDIA CLEANUP IMAGE SCANNER
   Version: 1.1.9
------------------------------------------------------- */


if (!function_exists('smcmlc_get_attachment_file_size_bytes')) {
    function smcmlc_get_attachment_file_size_bytes($attachment_id) {
        $file_path = get_attached_file($attachment_id);

        if (!$file_path || !file_exists($file_path)) {
            return 0;
        }

        return (int) filesize($file_path);
    }
}

if (!function_exists('smcmlc_get_attachment_file_health')) {
    function smcmlc_get_attachment_file_health($attachment_id) {
        $attachment_id = absint($attachment_id);

        $health = array(
            'missing_original'  => false,
            'missing_generated' => false,
            'missing_thumbnail' => false,
            'missing_count'     => 0,
            'notes'             => array(),
        );

        if (!$attachment_id) {
            $health['missing_original'] = true;
            $health['notes'][] = 'Invalid attachment ID.';
            return $health;
        }

        $file_path = get_attached_file($attachment_id);

        if (!$file_path || !file_exists($file_path)) {
            $health['missing_original'] = true;
            $health['notes'][] = 'Original image file is missing from uploads.';
            return $health;
        }

        $metadata = wp_get_attachment_metadata($attachment_id);

        if (empty($metadata) || !is_array($metadata)) {
            return $health;
        }

        $base_dir = trailingslashit(dirname($file_path));

        if (!empty($metadata['sizes']) && is_array($metadata['sizes'])) {
            foreach ($metadata['sizes'] as $size_name => $size_data) {
                if (empty($size_data['file'])) {
                    continue;
                }

                $size_path = $base_dir . $size_data['file'];

                if (!file_exists($size_path)) {
                    $health['missing_generated'] = true;
                    $health['missing_count']++;

                    if ($size_name === 'thumbnail') {
                        $health['missing_thumbnail'] = true;
                    }
                }
            }
        }

        if ($health['missing_generated']) {
            $health['notes'][] = sprintf(
                '%d generated image size(s) are missing from uploads.',
                absint($health['missing_count'])
            );
        }

        return $health;
    }
}

if (!function_exists('smcmlc_render_file_health_html')) {
    function smcmlc_render_file_health_html($file_health) {
        if (empty($file_health) || empty($file_health['notes']) || !is_array($file_health['notes'])) {
            return 'None detected';
        }

        $html = '<div class="smcmlc_used-in-list smcmlc_file-health-list">';
        $html .= '<div class="smcmlc_used-in-item smcmlc_file-health-item">';
        $html .= '<strong>File Health</strong>';

        foreach ($file_health['notes'] as $note) {
            $html .= '<span>' . esc_html($note) . '</span>';
        }

        $html .= '</div>';
        $html .= '</div>';

        return $html;
    }
}

if (!function_exists('smcmlc_is_woocommerce_available')) {
    function smcmlc_is_woocommerce_available() {
        return class_exists('WooCommerce') || post_type_exists('product');
    }
}

if (!function_exists('smcmlc_get_post_type_label_for_usage')) {
    function smcmlc_get_post_type_label_for_usage($post_type) {
        $post_type = sanitize_key($post_type);

        $labels = array(
            'product'           => 'Product',
            'product_variation' => 'Variation',
            'page'              => 'Page',
            'post'              => 'Post',
            'attachment'        => 'Attachment',
        );

        if (isset($labels[$post_type])) {
            return $labels[$post_type];
        }

        $object = get_post_type_object($post_type);

        if ($object && !empty($object->labels->singular_name)) {
            return $object->labels->singular_name;
        }

        return ucfirst(str_replace('_', ' ', $post_type));
    }
}

if (!function_exists('smcmlc_get_post_link_set')) {
    function smcmlc_get_post_link_set($post_id) {
        $post_id = absint($post_id);

        if (!$post_id) {
            return array(
                'edit' => '',
                'view' => '',
            );
        }

        return array(
            'edit' => get_edit_post_link($post_id, ''),
            'view' => get_permalink($post_id),
        );
    }
}

if (!function_exists('smcmlc_build_usage_item')) {
    function smcmlc_build_usage_item($label, $post_id = 0, $meta_key = '', $usage_type = '') {
        $post_id = absint($post_id);
        $post    = $post_id ? get_post($post_id) : null;
        $links   = $post_id ? smcmlc_get_post_link_set($post_id) : array('edit' => '', 'view' => '');

        return array(
            'label'      => sanitize_text_field($label),
            'post_id'    => $post_id,
            'post_title' => $post ? get_the_title($post_id) : '',
            'post_type'  => $post ? $post->post_type : '',
            'meta_key'   => sanitize_key($meta_key),
            'usage_type' => sanitize_key($usage_type),
            'edit_link'  => !empty($links['edit']) ? $links['edit'] : '',
            'view_link'  => !empty($links['view']) ? $links['view'] : '',
        );
    }
}

if (!function_exists('smcmlc_find_posts_by_meta_value')) {
    function smcmlc_find_posts_by_meta_value($meta_key, $meta_value, $post_types = array('product'), $compare = '=') {
        $meta_key   = sanitize_key($meta_key);
        $meta_value = sanitize_text_field((string) $meta_value);

        if (!$meta_key || $meta_value === '') {
            return array();
        }

        $post_types = array_filter(array_map('sanitize_key', (array) $post_types));

        if (empty($post_types)) {
            $post_types = array('product');
        }

        return get_posts(array(
            'post_type'      => $post_types,
            'post_status'    => array('publish', 'private', 'draft', 'pending', 'future'),
            'posts_per_page' => 20,
            'fields'         => 'ids',
            'meta_query'     => array(
                array(
                    'key'     => $meta_key,
                    'value'   => $meta_value,
                    'compare' => $compare,
                ),
            ),
            'no_found_rows'  => true,
        ));
    }
}

if (!function_exists('smcmlc_find_product_gallery_usage')) {
    function smcmlc_find_product_gallery_usage($attachment_id) {
        $attachment_id = absint($attachment_id);

        if (!$attachment_id || !post_type_exists('product')) {
            return array();
        }

        global $wpdb;

        $meta_key = '_product_image_gallery';

        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT post_id, meta_value
                 FROM {$wpdb->postmeta}
                 WHERE meta_key = %s
                 AND meta_value <> ''
                 AND (
                    meta_value = %s
                    OR meta_value LIKE %s
                    OR meta_value LIKE %s
                    OR meta_value LIKE %s
                    OR meta_value REGEXP %s
                 )
                 LIMIT 75",
                $meta_key,
                (string) $attachment_id,
                $wpdb->esc_like((string) $attachment_id . ',') . '%',
                '%,' . $wpdb->esc_like((string) $attachment_id) . ',%',
                '%,' . $wpdb->esc_like((string) $attachment_id),
                '(^|,)' . $attachment_id . '(,|$)'
            )
        );

        if (empty($rows)) {
            return array();
        }

        $product_ids = array();

        foreach ($rows as $row) {
            $ids = array_filter(array_map('absint', explode(',', (string) $row->meta_value)));

            if (in_array($attachment_id, $ids, true)) {
                $post = get_post(absint($row->post_id));

                if ($post && $post->post_type === 'product') {
                    $product_ids[] = absint($row->post_id);
                }
            }
        }

        return array_values(array_unique($product_ids));
    }
}

if (!function_exists('smcmlc_find_term_thumbnail_usage')) {
    function smcmlc_find_term_thumbnail_usage($attachment_id) {
        $attachment_id = absint($attachment_id);

        if (!$attachment_id) {
            return array();
        }

        global $wpdb;

        $term_ids = $wpdb->get_col(
            $wpdb->prepare(
                "SELECT term_id
                 FROM {$wpdb->termmeta}
                 WHERE meta_key = %s
                 AND meta_value = %s
                 LIMIT 50",
                'thumbnail_id',
                (string) $attachment_id
            )
        );

        if (empty($term_ids)) {
            return array();
        }

        $items = array();

        foreach ($term_ids as $term_id) {
            $term = get_term(absint($term_id));

            if (!$term || is_wp_error($term)) {
                continue;
            }

            $items[] = array(
                'term_id'  => absint($term->term_id),
                'name'     => $term->name,
                'taxonomy' => $term->taxonomy,
                'edit'     => get_edit_term_link($term->term_id, $term->taxonomy),
                'view'     => get_term_link($term),
            );
        }

        return $items;
    }
}

if (!function_exists('smcmlc_get_woocommerce_usage')) {
    function smcmlc_get_woocommerce_usage($attachment_id) {
        $attachment_id = absint($attachment_id);

        $usage = array(
            'items'       => array(),
            'labels'      => array(),
            'html'        => 'None detected',
            'summary'     => 'None detected',
            'protected'   => false,
            'usage_count' => 0,
        );

        if (!$attachment_id || !smcmlc_is_woocommerce_available()) {
            return $usage;
        }

        $seen = array();

        $featured_products = smcmlc_find_posts_by_meta_value('_thumbnail_id', $attachment_id, array('product'), '=');

        foreach ($featured_products as $product_id) {
            $key = 'featured_product_' . absint($product_id);

            if (isset($seen[$key])) {
                continue;
            }

            $seen[$key] = true;
            $usage['items'][] = smcmlc_build_usage_item('Featured Product Image', $product_id, '_thumbnail_id', 'featured_product');
            $usage['labels'][] = 'Featured Product Image';
        }

        $gallery_products = smcmlc_find_product_gallery_usage($attachment_id);

        foreach ($gallery_products as $product_id) {
            $key = 'gallery_product_' . absint($product_id);

            if (isset($seen[$key])) {
                continue;
            }

            $seen[$key] = true;
            $usage['items'][] = smcmlc_build_usage_item('Product Gallery Image', $product_id, '_product_image_gallery', 'product_gallery');
            $usage['labels'][] = 'Product Gallery Image';
        }

        if (post_type_exists('product_variation')) {
            $variation_ids = smcmlc_find_posts_by_meta_value('_thumbnail_id', $attachment_id, array('product_variation'), '=');

            foreach ($variation_ids as $variation_id) {
                $key = 'variation_image_' . absint($variation_id);

                if (isset($seen[$key])) {
                    continue;
                }

                $seen[$key] = true;
                $usage['items'][] = smcmlc_build_usage_item('Variation Image', $variation_id, '_thumbnail_id', 'variation_image');
                $usage['labels'][] = 'Variation Image';
            }
        }

        $term_items = smcmlc_find_term_thumbnail_usage($attachment_id);

        foreach ($term_items as $term_item) {
            $key = 'term_thumbnail_' . absint($term_item['term_id']);

            if (isset($seen[$key])) {
                continue;
            }

            $seen[$key] = true;
            $usage['items'][] = array(
                'label'      => 'Category/Term Thumbnail',
                'term_id'    => absint($term_item['term_id']),
                'post_id'    => 0,
                'post_title' => $term_item['name'],
                'post_type'  => $term_item['taxonomy'],
                'meta_key'   => 'thumbnail_id',
                'usage_type' => 'term_thumbnail',
                'edit_link'  => !empty($term_item['edit']) ? $term_item['edit'] : '',
                'view_link'  => (!empty($term_item['view']) && !is_wp_error($term_item['view'])) ? $term_item['view'] : '',
            );
            $usage['labels'][] = 'Category/Term Thumbnail';
        }

        $usage['labels']      = array_values(array_unique(array_filter($usage['labels'])));
        $usage['usage_count'] = count($usage['items']);
        $usage['protected']   = $usage['usage_count'] > 0;

        if (!empty($usage['labels'])) {
            $usage['summary'] = implode(', ', $usage['labels']);
        }

        if (!empty($usage['items'])) {
            $html = '<div class="smcmlc_woo-usage-list">';

            foreach ($usage['items'] as $item) {
                $label = !empty($item['label']) ? $item['label'] : 'WooCommerce Usage';
                $title = !empty($item['post_title']) ? $item['post_title'] : '';
                $type  = !empty($item['post_type']) ? smcmlc_get_post_type_label_for_usage($item['post_type']) : '';
                $edit  = !empty($item['edit_link']) ? $item['edit_link'] : '';
                $view  = !empty($item['view_link']) ? $item['view_link'] : '';

                $html .= '<div class="smcmlc_woo-usage-item">';
                $html .= '<strong>' . esc_html($label) . '</strong>';

                if ($title) {
                    $html .= '<span>' . esc_html($title) . ($type ? ' · ' . esc_html($type) : '') . '</span>';
                }

                if ($edit || $view) {
                    $html .= '<div class="smcmlc_attached-actions smcmlc_woo-actions">';

                    if ($edit) {
                        $html .= '<a href="' . esc_url($edit) . '" target="_blank" rel="noopener noreferrer">✏️ Edit</a>';
                    }

                    if ($view) {
                        $html .= '<a href="' . esc_url($view) . '" target="_blank" rel="noopener noreferrer">👁 View</a>';
                    }

                    $html .= '</div>';
                }

                $html .= '</div>';
            }

            $html .= '</div>';
            $usage['html'] = $html;
        }

        return $usage;
    }
}


if (!function_exists('smcmlc_recursive_find_attachment_id_in_array')) {
    function smcmlc_recursive_find_attachment_id_in_array($value, $attachment_id) {
        $attachment_id = absint($attachment_id);

        if (!$attachment_id) {
            return false;
        }

        if (is_array($value)) {
            foreach ($value as $item) {
                if (smcmlc_recursive_find_attachment_id_in_array($item, $attachment_id)) {
                    return true;
                }
            }

            return false;
        }

        if (is_object($value)) {
            return smcmlc_recursive_find_attachment_id_in_array((array) $value, $attachment_id);
        }

        if (is_numeric($value) && absint($value) === $attachment_id) {
            return true;
        }

        return false;
    }
}

if (!function_exists('smcmlc_normalize_media_match_value')) {
    function smcmlc_normalize_media_match_value($value) {
        $value = trim((string) $value);

        if ($value === '') {
            return '';
        }

        $value = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
        $value = rawurldecode($value);
        $value = str_replace('\\/', '/', $value);
        $value = preg_replace('/-[0-9]+x[0-9]+(?=\.(?:jpg|jpeg|png|gif|webp|avif|svg)\b)/i', '', $value);

        return strtolower(trim($value));
    }
}

if (!function_exists('smcmlc_get_attachment_theme_match_values')) {
    function smcmlc_get_attachment_theme_match_values($attachment_id) {
        $attachment_id = absint($attachment_id);
        $values = array();

        if (!$attachment_id) {
            return $values;
        }

        $url       = wp_get_attachment_url($attachment_id);
        $meta_file = get_post_meta($attachment_id, '_wp_attached_file', true);
        $file_path = get_attached_file($attachment_id);

        if ($url) {
            $path = wp_parse_url($url, PHP_URL_PATH);
            $values[] = $url;
            $values[] = esc_url_raw($url);

            if ($path) {
                $values[] = $path;
                $values[] = ltrim($path, '/');
            }
        }

        if ($meta_file) {
            $values[] = $meta_file;
            $values[] = ltrim((string) $meta_file, '/');
            $values[] = basename((string) $meta_file);
        }

        if ($file_path) {
            $values[] = $file_path;
            $values[] = basename((string) $file_path);
        }

        $values = array_filter(array_map('smcmlc_normalize_media_match_value', $values));
        $values = array_values(array_unique($values));

        return $values;
    }
}




if (!function_exists('smcmlc_normalize_logo_family_token')) {
    function smcmlc_normalize_logo_family_token($value) {
        $value = smcmlc_normalize_media_match_value($value);
        $value = basename((string) $value);
        $value = preg_replace('/\.(jpg|jpeg|png|gif|webp|avif|svg)(\?.*)?$/i', '', $value);
        $value = preg_replace('/^cropped-/i', '', $value);
        $value = preg_replace('/-\d+$/', '', $value);
        $value = preg_replace('/-\d+x\d+$/', '', $value);
        $value = preg_replace('/[^a-z0-9]+/i', '-', $value);
        $value = trim($value, '-');

        return strtolower($value);
    }
}

if (!function_exists('smcmlc_is_logo_related_attachment')) {
    function smcmlc_is_logo_related_attachment($attachment_id) {
        $attachment_id = absint($attachment_id);

        if (!$attachment_id) {
            return false;
        }

        $title = strtolower((string) get_the_title($attachment_id));
        $alt   = strtolower((string) get_post_meta($attachment_id, '_wp_attachment_image_alt', true));
        $file  = strtolower((string) get_post_meta($attachment_id, '_wp_attached_file', true));
        $url   = strtolower((string) wp_get_attachment_url($attachment_id));

        $combined = $title . ' ' . $alt . ' ' . $file . ' ' . $url;

        return (
            strpos($combined, 'logo') !== false ||
            strpos($combined, 'site identity') !== false ||
            strpos($combined, 'brand') !== false
        );
    }
}

if (!function_exists('smcmlc_get_active_theme_logo_attachment_ids')) {
    function smcmlc_get_active_theme_logo_attachment_ids() {
        $ids = array();

        $custom_logo_id = absint(get_theme_mod('custom_logo'));
        $site_icon_id   = absint(get_option('site_icon'));

        if ($custom_logo_id) {
            $ids[] = $custom_logo_id;
        }

        if ($site_icon_id) {
            $ids[] = $site_icon_id;
        }

        $theme_mods = get_theme_mods();

        if (is_array($theme_mods)) {
            foreach ($theme_mods as $key => $value) {
                if (!smcmlc_theme_setting_key_is_media_related($key)) {
                    continue;
                }

                if (is_numeric($value)) {
                    $ids[] = absint($value);
                }

                if (is_array($value) || is_object($value)) {
                    $flat = wp_json_encode($value);

                    if ($flat && preg_match_all('/(?:id|attachment_id|image_id|logo_id|media_id)["\']?\s*[:=]\s*["\']?(\d+)/i', $flat, $matches)) {
                        foreach ($matches[1] as $match_id) {
                            $ids[] = absint($match_id);
                        }
                    }
                }
            }
        }

        return array_values(array_unique(array_filter(array_map('absint', $ids))));
    }
}

if (!function_exists('smcmlc_is_related_to_active_theme_logo')) {
    function smcmlc_is_related_to_active_theme_logo($attachment_id) {
        $attachment_id = absint($attachment_id);

        if (!$attachment_id || !smcmlc_is_logo_related_attachment($attachment_id)) {
            return false;
        }

        $active_logo_ids = smcmlc_get_active_theme_logo_attachment_ids();

        if (empty($active_logo_ids)) {
            return false;
        }

        $current_tokens = array(
            smcmlc_normalize_logo_family_token(get_post_meta($attachment_id, '_wp_attached_file', true)),
            smcmlc_normalize_logo_family_token(wp_get_attachment_url($attachment_id)),
            smcmlc_normalize_logo_family_token(get_the_title($attachment_id)),
        );

        $current_tokens = array_values(array_unique(array_filter($current_tokens)));

        foreach ($active_logo_ids as $logo_id) {
            if ($logo_id === $attachment_id) {
                return true;
            }

            $active_tokens = array(
                smcmlc_normalize_logo_family_token(get_post_meta($logo_id, '_wp_attached_file', true)),
                smcmlc_normalize_logo_family_token(wp_get_attachment_url($logo_id)),
                smcmlc_normalize_logo_family_token(get_the_title($logo_id)),
            );

            $active_tokens = array_values(array_unique(array_filter($active_tokens)));

            foreach ($current_tokens as $current_token) {
                if (!$current_token || strlen($current_token) < 8) {
                    continue;
                }

                foreach ($active_tokens as $active_token) {
                    if (!$active_token || strlen($active_token) < 8) {
                        continue;
                    }

                    if (
                        $current_token === $active_token ||
                        strpos($current_token, $active_token) !== false ||
                        strpos($active_token, $current_token) !== false
                    ) {
                        return true;
                    }
                }
            }
        }

        return false;
    }
}

if (!function_exists('smcmlc_get_attachment_logo_filename_stems')) {
    function smcmlc_get_attachment_logo_filename_stems($attachment_id) {
        $attachment_id = absint($attachment_id);
        $stems = array();

        if (!$attachment_id) {
            return $stems;
        }

        $candidates = array(
            get_post_meta($attachment_id, '_wp_attached_file', true),
            get_attached_file($attachment_id),
            wp_get_attachment_url($attachment_id),
            get_the_title($attachment_id),
        );

        foreach ($candidates as $candidate) {
            if (!$candidate) {
                continue;
            }

            $candidate = smcmlc_normalize_media_match_value($candidate);
            $basename  = basename($candidate);
            $filename  = preg_replace('/\.(jpg|jpeg|png|gif|webp|avif|svg)(\?.*)?$/i', '', $basename);

            if (!$filename) {
                continue;
            }

            $stems[] = $filename;
            $stems[] = preg_replace('/-(scaled|rotated)$/i', '', $filename);
            $stems[] = preg_replace('/-[0-9]+$/', '', $filename);
            $stems[] = preg_replace('/-[0-9]+x[0-9]+$/', '', $filename);
        }

        $stems = array_filter(array_map('trim', $stems));
        $stems = array_values(array_unique($stems));

        return $stems;
    }
}

if (!function_exists('smcmlc_value_contains_logo_filename_match')) {
    function smcmlc_value_contains_logo_filename_match($value, $attachment_id, $parent_key = '') {
        $attachment_id = absint($attachment_id);

        if (!$attachment_id) {
            return false;
        }

        if (is_array($value)) {
            foreach ($value as $key => $item) {
                $combined_key = trim((string) $parent_key . ' ' . (string) $key);

                if (smcmlc_value_contains_logo_filename_match($item, $attachment_id, $combined_key)) {
                    return true;
                }
            }

            return false;
        }

        if (is_object($value)) {
            return smcmlc_value_contains_logo_filename_match((array) $value, $attachment_id, $parent_key);
        }

        if (is_numeric($value) && absint($value) === $attachment_id) {
            return true;
        }

        if (!is_string($value)) {
            return false;
        }

        $raw_value = trim($value);

        if ($raw_value === '') {
            return false;
        }

        $combined_key = strtolower((string) $parent_key . ' ' . $raw_value);

        if (
            strpos($combined_key, 'logo') === false &&
            strpos($combined_key, 'site_icon') === false &&
            strpos($combined_key, 'favicon') === false &&
            strpos($combined_key, 'header') === false &&
            strpos($combined_key, 'footer') === false
        ) {
            return false;
        }

        if (!smcmlc_theme_value_looks_like_media_reference($raw_value) && !smcmlc_theme_setting_key_is_media_related($parent_key)) {
            return false;
        }

        $normalized_value = smcmlc_normalize_media_match_value($raw_value);
        $stems = smcmlc_get_attachment_logo_filename_stems($attachment_id);

        foreach ($stems as $stem) {
            $stem = smcmlc_normalize_media_match_value($stem);

            if (!$stem || strlen($stem) < 8) {
                continue;
            }

            if (strpos($normalized_value, $stem) !== false) {
                return true;
            }

            $stem_without_number = preg_replace('/-[0-9]+$/', '', $stem);

            if ($stem_without_number && strlen($stem_without_number) >= 8 && strpos($normalized_value, $stem_without_number) !== false) {
                return true;
            }
        }

        return false;
    }
}



if (!function_exists('smcmlc_is_probable_brand_logo_attachment')) {
    function smcmlc_is_probable_brand_logo_attachment($attachment_id) {
        $attachment_id = absint($attachment_id);

        if (!$attachment_id) {
            return false;
        }

        $title = strtolower((string) get_the_title($attachment_id));
        $alt   = strtolower((string) get_post_meta($attachment_id, '_wp_attachment_image_alt', true));
        $file  = strtolower((string) get_post_meta($attachment_id, '_wp_attached_file', true));
        $url   = strtolower((string) wp_get_attachment_url($attachment_id));

        $combined = $title . ' ' . $alt . ' ' . $file . ' ' . $url;

        if (
            strpos($combined, 'logo') !== false ||
            strpos($combined, 'brand') !== false ||
            strpos($combined, 'site-identity') !== false ||
            strpos($combined, 'site_identity') !== false
        ) {
            return true;
        }

        return false;
    }
}

if (!function_exists('smcmlc_is_active_wordpress_logo_attachment')) {
    function smcmlc_is_active_wordpress_logo_attachment($attachment_id) {
        $attachment_id = absint($attachment_id);

        if (!$attachment_id) {
            return false;
        }

        $custom_logo_id = absint(get_theme_mod('custom_logo'));
        $site_icon_id   = absint(get_option('site_icon'));

        if (($custom_logo_id && $custom_logo_id === $attachment_id) || ($site_icon_id && $site_icon_id === $attachment_id)) {
            return true;
        }

        $attachment_url = wp_get_attachment_url($attachment_id);

        if (!$attachment_url) {
            return false;
        }

        $header_image = get_theme_mod('header_image');

        if ($header_image && esc_url_raw($header_image) === esc_url_raw($attachment_url)) {
            return true;
        }

        return false;
    }
}

if (!function_exists('smcmlc_theme_setting_key_is_media_related')) {
    function smcmlc_theme_setting_key_is_media_related($key) {
        $key = strtolower((string) $key);

        if ($key === '') {
            return false;
        }

        $media_signals = array(
            'logo',
            'icon',
            'favicon',
            'header',
            'footer',
            'image',
            'img',
            'picture',
            'photo',
            'background',
            'bg_',
            'banner',
            'hero',
            'thumbnail',
            'custom_logo',
            'site_icon',
            'mobile_logo',
            'retina_logo',
            'sticky_logo',
        );

        foreach ($media_signals as $signal) {
            if (strpos($key, $signal) !== false) {
                return true;
            }
        }

        return false;
    }
}

if (!function_exists('smcmlc_theme_value_looks_like_media_reference')) {
    function smcmlc_theme_value_looks_like_media_reference($value) {
        if (is_numeric($value)) {
            return true;
        }

        if (!is_string($value)) {
            return false;
        }

        $value = trim($value);

        if ($value === '') {
            return false;
        }

        if (preg_match('/\.(jpg|jpeg|png|gif|webp|avif|svg)(\?.*)?$/i', $value)) {
            return true;
        }

        if (preg_match('/\/uploads\//i', $value)) {
            return true;
        }

        if (preg_match('/wp-image-[0-9]+/i', $value)) {
            return true;
        }

        return false;
    }
}

if (!function_exists('smcmlc_recursive_find_attachment_media_match')) {
    function smcmlc_recursive_find_attachment_media_match($value, $attachment_id, $match_values = array(), $parent_key = '') {
        $attachment_id = absint($attachment_id);

        if (!$attachment_id) {
            return false;
        }

        if (empty($match_values)) {
            $match_values = smcmlc_get_attachment_theme_match_values($attachment_id);
        }

        if (is_array($value)) {
            foreach ($value as $key => $item) {
                $combined_key = trim($parent_key . ' ' . (string) $key);

                if (smcmlc_recursive_find_attachment_media_match($item, $attachment_id, $match_values, $combined_key)) {
                    return true;
                }
            }

            return false;
        }

        if (is_object($value)) {
            return smcmlc_recursive_find_attachment_media_match((array) $value, $attachment_id, $match_values, $parent_key);
        }

        if (is_numeric($value) && absint($value) === $attachment_id) {
            return true;
        }

        if (!is_string($value)) {
            return false;
        }

        $raw_value = trim($value);

        if ($raw_value === '') {
            return false;
        }

        if (preg_match('/wp-image-' . preg_quote((string) $attachment_id, '/') . '\b/i', $raw_value)) {
            return true;
        }

        if (preg_match('/["\'](?:id|attachment_id|image_id|logo_id|media_id)["\']\s*:\s*["\']?' . preg_quote((string) $attachment_id, '/') . '["\']?/i', $raw_value)) {
            return true;
        }

        if (!smcmlc_theme_setting_key_is_media_related($parent_key) && !smcmlc_theme_value_looks_like_media_reference($raw_value)) {
            return false;
        }

        $normalized_value = smcmlc_normalize_media_match_value($raw_value);

        if ($normalized_value === '') {
            return false;
        }

        foreach ($match_values as $match_value) {
            if ($match_value === '') {
                continue;
            }

            if ($normalized_value === $match_value) {
                return true;
            }

            if (strlen($match_value) > 12 && strpos($normalized_value, $match_value) !== false) {
                return true;
            }

            $match_basename = basename($match_value);

            if ($match_basename && strlen($match_basename) > 6 && $normalized_value === smcmlc_normalize_media_match_value($match_basename)) {
                return true;
            }
        }

        return false;
    }
}

if (!function_exists('smcmlc_get_theme_usage_label_from_key')) {
    function smcmlc_get_theme_usage_label_from_key($key, $fallback = 'Theme Customizer Image') {
        $key = strtolower((string) $key);

        if (strpos($key, 'custom_logo') !== false || strpos($key, 'site_logo') !== false || strpos($key, 'logo') !== false) {
            if (strpos($key, 'footer') !== false) {
                return 'Footer Logo';
            }

            if (strpos($key, 'header') !== false) {
                return 'Header Logo';
            }

            if (strpos($key, 'mobile') !== false) {
                return 'Mobile Logo';
            }

            if (strpos($key, 'retina') !== false) {
                return 'Retina Logo';
            }

            if (strpos($key, 'sticky') !== false) {
                return 'Sticky Header Logo';
            }

            return 'Site Logo';
        }

        if (strpos($key, 'site_icon') !== false || strpos($key, 'favicon') !== false || strpos($key, 'icon') !== false) {
            return 'Site Icon';
        }

        if (strpos($key, 'footer') !== false) {
            return 'Theme Footer Image';
        }

        if (strpos($key, 'header') !== false) {
            return 'Theme Header Image';
        }

        if (strpos($key, 'banner') !== false) {
            return 'Theme Banner Image';
        }

        if (strpos($key, 'hero') !== false) {
            return 'Theme Hero Image';
        }

        if (strpos($key, 'background') !== false || strpos($key, 'bg_') !== false) {
            return 'Theme Background Image';
        }

        return $fallback;
    }
}

if (!function_exists('smcmlc_add_theme_usage_item')) {
    function smcmlc_add_theme_usage_item(&$usage, &$seen, $label, $source, $source_type = 'Theme / Customizer') {
        $label       = sanitize_text_field($label);
        $source      = sanitize_text_field($source);
        $source_type = sanitize_text_field($source_type);
        $seen_key    = md5($label . '|' . $source . '|' . $source_type);

        if (isset($seen[$seen_key])) {
            return;
        }

        $seen[$seen_key] = true;

        $usage['items'][] = array(
            'label'       => $label,
            'post_id'     => 0,
            'post_title'  => get_bloginfo('name'),
            'post_type'   => 'customizer',
            'source'      => $source,
            'source_type' => $source_type,
            'edit_link'   => admin_url('customize.php'),
            'view_link'   => home_url('/'),
        );

        $usage['labels'][] = $label;
    }
}

if (!function_exists('smcmlc_get_theme_option_rows_for_scan')) {
    function smcmlc_get_theme_option_rows_for_scan() {
        static $cached_rows = null;

        if (is_array($cached_rows)) {
            return $cached_rows;
        }

        global $wpdb;

        $stylesheet = get_stylesheet();
        $template   = get_template();
        $names      = array_filter(array_unique(array(
            'theme_mods_' . $stylesheet,
            'theme_mods_' . $template,
            'site_icon',
            'custom_logo',
            'header_image',
            'header_image_data',
            $stylesheet . '_options',
            $template . '_options',
            'theme_options',
            'neve_options',
            'astra-settings',
            'oceanwp_theme_panel',
            'generate_settings',
            'kadence_theme_options',
        )));

        $rows = array();

        if (!empty($names)) {
            $placeholders = implode(',', array_fill(0, count($names), '%s'));
            $rows = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT option_name, option_value
                     FROM {$wpdb->options}
                     WHERE option_name IN ({$placeholders})
                     LIMIT 100",
                    $names
                )
            );
        }

        $like_patterns = array(
            'theme_mods\_%',
            '%logo%',
            '%site_icon%',
            '%favicon%',
            '%header%image%',
            '%footer%image%',
            '%theme%option%',
            '%customizer%',
        );

        foreach ($like_patterns as $pattern) {
            $extra_rows = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT option_name, option_value
                     FROM {$wpdb->options}
                     WHERE option_name LIKE %s
                     AND option_value <> ''
                     LIMIT 50",
                    $pattern
                )
            );

            if (!empty($extra_rows)) {
                $rows = array_merge($rows, $extra_rows);
            }
        }

        $unique = array();

        foreach ($rows as $row) {
            if (empty($row->option_name)) {
                continue;
            }

            $unique[$row->option_name] = $row;
        }

        $cached_rows = array_values($unique);

        return $cached_rows;
    }
}

if (!function_exists('smcmlc_maybe_unserialize_deep')) {
    function smcmlc_maybe_unserialize_deep($value) {
        if (is_serialized($value)) {
            return maybe_unserialize($value);
        }

        if (is_string($value)) {
            $trimmed = trim($value);

            if ($trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
                $decoded = json_decode($trimmed, true);

                if (json_last_error() === JSON_ERROR_NONE) {
                    return $decoded;
                }
            }
        }

        return $value;
    }
}

if (!function_exists('smcmlc_get_media_library_theme_usage')) {
    function smcmlc_get_media_library_theme_usage($attachment_id) {
        $attachment_id = absint($attachment_id);

        $usage = array(
            'items'       => array(),
            'labels'      => array(),
            'html'        => 'None detected',
            'summary'     => 'None detected',
            'protected'   => false,
            'usage_count' => 0,
        );

        if (!$attachment_id) {
            return $usage;
        }

        $seen         = array();
        $match_values = smcmlc_get_attachment_theme_match_values($attachment_id);
        $attachment_url = wp_get_attachment_url($attachment_id);

        $custom_logo_id = absint(get_theme_mod('custom_logo'));

        if ($custom_logo_id && $custom_logo_id === $attachment_id) {
            smcmlc_add_theme_usage_item($usage, $seen, 'Site Logo', 'custom_logo', 'Theme Mod');
        }

        $site_icon_id = absint(get_option('site_icon'));

        if ($site_icon_id && $site_icon_id === $attachment_id) {
            smcmlc_add_theme_usage_item($usage, $seen, 'Site Icon', 'site_icon', 'WordPress Option');
        }

        $header_image = get_theme_mod('header_image');

        if ($header_image && $attachment_url && esc_url_raw($header_image) === esc_url_raw($attachment_url)) {
            smcmlc_add_theme_usage_item($usage, $seen, 'Header Image', 'header_image', 'Theme Mod');
        }

        if (smcmlc_is_active_wordpress_logo_attachment($attachment_id)) {
            smcmlc_add_theme_usage_item($usage, $seen, 'Site Logo', 'active_wordpress_logo_attachment', 'WordPress Active Logo');
        }

        if (function_exists('smcmlc_is_related_to_active_theme_logo') && smcmlc_is_related_to_active_theme_logo($attachment_id)) {
            smcmlc_add_theme_usage_item($usage, $seen, 'Site Logo Related Asset', 'active_theme_logo_family_match', 'Theme / Customizer Logo Family');
        }

        /*
         * Theme media checks used directly by the Media Library scanner.
         * These checks are part of the normal scan path and are not gated,
         * reduced, or reserved for any separate plugin.
         */
        $theme_mods = get_theme_mods();

        if (is_array($theme_mods)) {
            foreach ($theme_mods as $mod_key => $mod_value) {
                $source_key = sanitize_text_field((string) $mod_key);

                if ($source_key === '') {
                    continue;
                }

                if (!smcmlc_theme_setting_key_is_media_related($source_key) && !smcmlc_recursive_find_attachment_id_in_array($mod_value, $attachment_id)) {
                    continue;
                }

                if (
                    !smcmlc_recursive_find_attachment_media_match($mod_value, $attachment_id, $match_values, $source_key) &&
                    !smcmlc_value_contains_logo_filename_match($mod_value, $attachment_id, $source_key)
                ) {
                    continue;
                }

                $label = smcmlc_get_theme_usage_label_from_key($source_key, 'Theme Customizer Image');
                smcmlc_add_theme_usage_item($usage, $seen, $label, $source_key, 'Theme Mod');
            }
        }

        $option_rows = smcmlc_get_theme_option_rows_for_scan();

        foreach ($option_rows as $row) {
            $option_name = !empty($row->option_name) ? (string) $row->option_name : '';

            if ($option_name === '') {
                continue;
            }

            $option_value = smcmlc_maybe_unserialize_deep($row->option_value);

            if (!smcmlc_theme_setting_key_is_media_related($option_name) && !smcmlc_recursive_find_attachment_id_in_array($option_value, $attachment_id)) {
                continue;
            }

            if (
                !smcmlc_recursive_find_attachment_media_match($option_value, $attachment_id, $match_values, $option_name) &&
                !smcmlc_value_contains_logo_filename_match($option_value, $attachment_id, $option_name)
            ) {
                continue;
            }

            $label = smcmlc_get_theme_usage_label_from_key($option_name, 'Theme Option Image');
            smcmlc_add_theme_usage_item($usage, $seen, $label, $option_name, 'Theme Option');
        }

        $usage['labels']      = array_values(array_unique(array_filter($usage['labels'])));
        $usage['usage_count'] = count($usage['items']);
        $usage['protected']   = $usage['usage_count'] > 0;

        if (!empty($usage['labels'])) {
            $usage['summary'] = implode(', ', $usage['labels']);
        }

        if (!empty($usage['items'])) {
            $html = '<div class="smcmlc_used-in-list smcmlc_theme-usage-list">';

            foreach ($usage['items'] as $item) {
                $label       = !empty($item['label']) ? $item['label'] : 'Theme / Customizer Image';
                $title       = !empty($item['post_title']) ? $item['post_title'] : get_bloginfo('name');
                $source      = !empty($item['source']) ? $item['source'] : '';
                $source_type = !empty($item['source_type']) ? $item['source_type'] : 'Theme / Customizer';
                $edit        = !empty($item['edit_link']) ? $item['edit_link'] : '';
                $view        = !empty($item['view_link']) ? $item['view_link'] : '';

                $html .= '<div class="smcmlc_used-in-item smcmlc_theme-usage-item">';
                $html .= '<strong>Used In: ' . esc_html($label) . '</strong>';
                $html .= '<span>' . esc_html($title) . ' · ' . esc_html($source_type) . '</span>';

                if ($source) {
                    $html .= '<div class="smcmlc_usage-confidence">Theme relationship detected: ' . esc_html($source) . '</div>';
                }

                if ($edit || $view) {
                    $html .= '<div class="smcmlc_attached-actions smcmlc_used-in-actions">';

                    if ($edit) {
                        $html .= '<a href="' . esc_url($edit) . '" target="_blank" rel="noopener noreferrer">✏️ Customize</a>';
                    }

                    if ($view) {
                        $html .= '<a href="' . esc_url($view) . '" target="_blank" rel="noopener noreferrer">👁 View Site</a>';
                    }

                    $html .= '</div>';
                }

                $html .= '</div>';
            }

            $html .= '</div>';
            $usage['html'] = $html;
        }

        return $usage;
    }
}




if (!function_exists('smcmlc_get_empty_media_usage_result')) {
    function smcmlc_get_empty_media_usage_result() {
        return array(
            'items'       => array(),
            'labels'      => array(),
            'html'        => 'None detected',
            'summary'     => 'None detected',
            'protected'   => false,
            'likely_used' => false,
            'usage_count' => 0,
        );
    }
}

if (!function_exists('smcmlc_get_attachment_search_terms')) {
    function smcmlc_get_attachment_search_terms($attachment_id) {
        $attachment_id = absint($attachment_id);
        $terms = array();

        if (!$attachment_id) {
            return $terms;
        }

        $url = wp_get_attachment_url($attachment_id);
        $file = get_attached_file($attachment_id);
        $meta_file = get_post_meta($attachment_id, '_wp_attached_file', true);

        if ($url) {
            $terms[] = $url;
            $terms[] = esc_url_raw($url);
            $terms[] = wp_parse_url($url, PHP_URL_PATH);
        }

        if ($meta_file) {
            $terms[] = $meta_file;
            $terms[] = basename((string) $meta_file);
        }

        if ($file) {
            $terms[] = basename((string) $file);
        }

        $terms[] = 'wp-image-' . $attachment_id;
        $terms[] = '"id":' . $attachment_id;
        $terms[] = '"id":"' . $attachment_id . '"';
        $terms[] = 'attachment_' . $attachment_id;
        $terms[] = 'attachment-' . $attachment_id;

        $terms = array_filter(array_unique(array_map('trim', $terms)));

        return $terms;
    }
}

if (!function_exists('smcmlc_build_content_usage_item')) {
    function smcmlc_build_content_usage_item($label, $post_id = 0, $source = 'post_content') {
        $post_id = absint($post_id);
        $post    = $post_id ? get_post($post_id) : null;
        $links   = $post_id ? smcmlc_get_post_link_set($post_id) : array('edit' => '', 'view' => '');

        return array(
            'label'      => sanitize_text_field($label),
            'post_id'    => $post_id,
            'post_title' => $post ? get_the_title($post_id) : '',
            'post_type'  => $post ? $post->post_type : '',
            'source'     => sanitize_key($source),
            'edit_link'  => !empty($links['edit']) ? $links['edit'] : '',
            'view_link'  => !empty($links['view']) ? $links['view'] : '',
        );
    }
}

if (!function_exists('smcmlc_find_content_usage')) {
    function smcmlc_find_content_usage($attachment_id) {
        $attachment_id = absint($attachment_id);

        $usage = array(
            'items'       => array(),
            'labels'      => array(),
            'html'        => 'None detected',
            'summary'     => 'None detected',
            'likely_used' => false,
            'usage_count' => 0,
        );

        if (!$attachment_id) {
            return $usage;
        }

        global $wpdb;

        $terms = smcmlc_get_attachment_search_terms($attachment_id);

        if (empty($terms)) {
            return $usage;
        }

        /*
         * Conservative scan rule:
         * Only real content containers can create a "Likely Used" status.
         * Attachment pages/content are intentionally excluded because they can
         * create false positives and may show 404/empty attachment pages.
         */
        $post_types   = array('post', 'page', 'product');
        $public_types = get_post_types(array('public' => true), 'names');

        if (is_array($public_types)) {
            $post_types = array_values(array_unique(array_merge($post_types, $public_types)));
        }

        $post_types = array_filter(array_map('sanitize_key', $post_types));
        $post_types = array_diff($post_types, array('attachment', 'product_variation', 'revision', 'nav_menu_item', 'wp_template', 'wp_template_part'));

        if (empty($post_types)) {
            $post_types = array('post', 'page', 'product');
        }

        $where_parts = array();
        $params      = array();

        foreach ($terms as $term) {
            if ($term === '') {
                continue;
            }

            $where_parts[] = 'post_content LIKE %s';
            $params[]      = '%' . $wpdb->esc_like($term) . '%';
        }

        if (empty($where_parts)) {
            return $usage;
        }

        $post_type_placeholders = implode(',', array_fill(0, count($post_types), '%s'));
        $params = array_merge($post_types, $params);

        $sql = "SELECT ID, post_type, post_status FROM {$wpdb->posts}
                WHERE post_status IN ('publish', 'private', 'draft', 'pending', 'future')
                AND post_type IN ({$post_type_placeholders})
                AND (" . implode(' OR ', $where_parts) . ")
                ORDER BY post_modified_gmt DESC
                LIMIT 50";

        $rows = $wpdb->get_results($wpdb->prepare($sql, $params));

        if (empty($rows)) {
            return $usage;
        }

        $seen = array();

        foreach ($rows as $row) {
            $post_id = absint($row->ID);

            if (!$post_id || isset($seen[$post_id])) {
                continue;
            }

            if ($row->post_type === 'attachment' || $row->post_status === 'trash' || $post_id === $attachment_id) {
                continue;
            }

            $seen[$post_id] = true;
            $label = smcmlc_get_post_type_label_for_usage($row->post_type) . ' Content';

            $usage['items'][] = smcmlc_build_content_usage_item($label, $post_id, 'post_content');
            $usage['labels'][] = $label;
        }

        $usage['labels']      = array_values(array_unique(array_filter($usage['labels'])));
        $usage['usage_count'] = count($usage['items']);
        $usage['likely_used'] = $usage['usage_count'] > 0;

        if (!empty($usage['labels'])) {
            $usage['summary'] = implode(', ', $usage['labels']);
        }

        if (!empty($usage['items'])) {
            $html = '<div class="smcmlc_used-in-list">';

            foreach ($usage['items'] as $item) {
                $label = !empty($item['label']) ? $item['label'] : 'Content Usage';
                $title = !empty($item['post_title']) ? $item['post_title'] : '';
                $type  = !empty($item['post_type']) ? smcmlc_get_post_type_label_for_usage($item['post_type']) : '';
                $edit  = !empty($item['edit_link']) ? $item['edit_link'] : '';
                $view  = !empty($item['view_link']) ? $item['view_link'] : '';

                $html .= '<div class="smcmlc_used-in-item">';
                $html .= '<strong>Used In: ' . esc_html($label) . '</strong>';

                if ($title) {
                    $html .= '<span>' . esc_html($title) . ($type ? ' · ' . esc_html($type) : '') . '</span>';
                }

                if ($edit || $view) {
                    $html .= '<div class="smcmlc_attached-actions smcmlc_used-in-actions">';

                    if ($edit) {
                        $html .= '<a href="' . esc_url($edit) . '" target="_blank" rel="noopener noreferrer">✏️ Edit</a>';
                    }

                    if ($view) {
                        $html .= '<a href="' . esc_url($view) . '" target="_blank" rel="noopener noreferrer">👁 View</a>';
                    }

                    $html .= '</div>';
                }

                $html .= '</div>';
            }

            $html .= '</div>';
            $usage['html'] = $html;
        }

        return $usage;
    }
}


if (!function_exists('smcmlc_get_parent_usage')) {
    function smcmlc_get_parent_usage($attachment_id, $parent_id = 0) {
        $attachment_id = absint($attachment_id);
        $parent_id     = absint($parent_id);

        $usage = array(
            'items'       => array(),
            'labels'      => array(),
            'html'        => 'None detected',
            'summary'     => 'None detected',
            'likely_used' => false,
            'protected'   => false,
            'usage_count' => 0,
        );

        if (!$attachment_id || !$parent_id) {
            return $usage;
        }

        $parent = get_post($parent_id);

        if (!$parent || $parent->post_status === 'trash') {
            return $usage;
        }

        $post_type_label = smcmlc_get_post_type_label_for_usage($parent->post_type);
        $label           = $post_type_label . ' Attachment Relationship';

        if ($parent->post_type === 'product') {
            $label = 'Attached Product Image';
        } elseif ($parent->post_type === 'page') {
            $label = 'Attached Page Image';
        } elseif ($parent->post_type === 'post') {
            $label = 'Attached Post Image';
        }

        $links = smcmlc_get_post_link_set($parent_id);

        $usage['items'][] = array(
            'label'      => $label,
            'post_id'    => $parent_id,
            'post_title' => get_the_title($parent_id),
            'post_type'  => $parent->post_type,
            'source'     => 'post_parent',
            'edit_link'  => !empty($links['edit']) ? $links['edit'] : '',
            'view_link'  => !empty($links['view']) ? $links['view'] : '',
        );

        $usage['labels'][]    = $label;
        $usage['usage_count'] = 1;
        $usage['likely_used'] = false;
        $usage['protected']   = false;
        $usage['summary']     = $label;

        $html = '<div class="smcmlc_used-in-list">';
        $html .= '<div class="smcmlc_used-in-item smcmlc_used-in-parent">';
        $html .= '<strong>Used In: ' . esc_html($label) . '</strong>';
        $html .= '<span>' . esc_html(get_the_title($parent_id)) . ' · ' . esc_html($post_type_label) . '</span>';

        if (!empty($links['edit']) || !empty($links['view'])) {
            $html .= '<div class="smcmlc_attached-actions smcmlc_used-in-actions">';

            if (!empty($links['edit'])) {
                $html .= '<a href="' . esc_url($links['edit']) . '" target="_blank" rel="noopener noreferrer">✏️ Edit</a>';
            }

            if (!empty($links['view'])) {
                $html .= '<a href="' . esc_url($links['view']) . '" target="_blank" rel="noopener noreferrer">👁 View</a>';
            }

            $html .= '</div>';
        }

        $html .= '<div class="smcmlc_usage-confidence smcmlc_usage-review-note">Attachment relationship only — review before deleting</div>';
        $html .= '</div>';
        $html .= '</div>';

        $usage['html'] = $html;

        return $usage;
    }
}

if (!function_exists('smcmlc_merge_usage_html')) {
    function smcmlc_merge_usage_html($woo_usage, $content_usage, $parent_usage = array(), $theme_usage = array(), $file_health_html = '') {
        $parts = array();

        if (!empty($woo_usage['html']) && $woo_usage['html'] !== 'None detected') {
            $parts[] = $woo_usage['html'];
        }

        if (!empty($content_usage['html']) && $content_usage['html'] !== 'None detected') {
            $parts[] = $content_usage['html'];
        }

        if (!empty($parent_usage['html']) && $parent_usage['html'] !== 'None detected') {
            $parts[] = $parent_usage['html'];
        }

        if (!empty($theme_usage['html']) && $theme_usage['html'] !== 'None detected') {
            $parts[] = $theme_usage['html'];
        }

        if (!empty($file_health_html) && $file_health_html !== 'None detected') {
            $parts[] = $file_health_html;
        }

        if (empty($parts)) {
            return 'None detected';
        }

        return '<div class="smcmlc_used-in-combined">' . implode('', $parts) . '</div>';
    }
}

if (!function_exists('smcmlc_get_scan_summary')) {
    function smcmlc_get_scan_summary($results) {
        $summary = array(
            'total'          => 0,
            'used'           => 0,
            'protected'      => 0,
            'unattached'     => 0,
            'cleanup'        => 0,
            'review'         => 0,
            'missing_files'  => 0,
            'broken_images'  => 0,
            'woocommerce'    => 0,
            'theme_customizer' => 0,
            'likely_used'    => 0,
            'total_bytes'    => 0,
            'total_size'     => '0 B',
        );

        if (empty($results) || !is_array($results)) {
            return $summary;
        }

        foreach ($results as $item) {
            $summary['total']++;

            $status = isset($item['risk_status']) ? strtolower((string) $item['risk_status']) : 'review';

            if ($status === 'protected') {
                $summary['protected']++;
                $summary['used']++;
            } elseif ($status === 'likely used') {
                $summary['likely_used']++;
                $summary['used']++;
            } elseif ($status === 'used') {
                $summary['used']++;
            } elseif ($status === 'cleanup candidate') {
                $summary['cleanup']++;
                $summary['unattached']++;
            } elseif ($status === 'unattached') {
                $summary['unattached']++;
            } elseif ($status === 'missing file') {
                $summary['missing_files']++;
            } elseif ($status === 'broken image') {
                $summary['broken_images']++;
            } else {
                $summary['review']++;
            }

            if (!empty($item['woo_usage_count'])) {
                $summary['woocommerce']++;
            }

            if (!empty($item['theme_usage_count'])) {
                $summary['theme_customizer']++;
            }

            if (!empty($item['content_usage_count'])) {
                $summary['likely_used']++;
            }

            if (!empty($item['missing_file']) && $status !== 'missing file') {
                $summary['missing_files']++;
            }

            if (!empty($item['broken_image']) && $status !== 'broken image') {
                $summary['broken_images']++;
            }

            if (isset($item['size_bytes'])) {
                $summary['total_bytes'] += absint($item['size_bytes']);
            }
        }

        $summary['total_size'] = size_format($summary['total_bytes']);

        return $summary;
    }
}

if (!function_exists('smcmlc_get_parent_links_html')) {
    function smcmlc_get_parent_links_html($parent_id, $attached_to) {
        $parent_id = absint($parent_id);

        if (!$parent_id) {
            return 'Unattached';
        }

        $parent_edit_link = get_edit_post_link($parent_id, '');
        $parent_view_link = get_permalink($parent_id);

        $html  = '<div class="smcmlc_attached-title">';

        if ($parent_edit_link) {
            $html .= '<a href="' . esc_url($parent_edit_link) . '" target="_blank" rel="noopener noreferrer">' . esc_html($attached_to) . '</a>';
        } else {
            $html .= esc_html($attached_to);
        }

        $html .= '</div>';
        $html .= '<div class="smcmlc_attached-actions">';

        if ($parent_edit_link) {
            $html .= '<a href="' . esc_url($parent_edit_link) . '" target="_blank" rel="noopener noreferrer">✏️ Edit</a>';
        }

        if ($parent_view_link) {
            $html .= '<a href="' . esc_url($parent_view_link) . '" target="_blank" rel="noopener noreferrer">👁 View</a>';
        }

        $html .= '</div>';

        return $html;
    }
}

/* -------------------------------------------------------
   MEDIA LIBRARY SCAN
   The dashboard scan checks image attachments, WordPress logo/header/theme
   relationships, WooCommerce relationships, parent relationships, real
   post/page/product content usage, and file health.
------------------------------------------------------- */

if (!function_exists('smcmlc_scan_media_library_images')) {
    function smcmlc_scan_media_library_images() {
        if (function_exists('set_time_limit')) {
            @set_time_limit(0);
        }

        $attachments = get_posts(array(
            'post_type'      => 'attachment',
            'post_mime_type' => 'image',
            'post_status'    => array('inherit', 'private'),
            'posts_per_page' => -1,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ));

        $results = array();

        foreach ($attachments as $attachment) {
            $file_path       = get_attached_file($attachment->ID);
            $file_health     = smcmlc_get_attachment_file_health($attachment->ID);
            $size_bytes      = smcmlc_get_attachment_file_size_bytes($attachment->ID);
            $file_size       = $size_bytes ? size_format($size_bytes) : 'Missing file';
            $file_name       = $file_path ? basename($file_path) : basename((string) get_post_meta($attachment->ID, '_wp_attached_file', true));
            $missing_file    = !empty($file_health['missing_original']);
            $broken_image    = (!$missing_file && (!empty($file_health['missing_generated']) || !empty($file_health['missing_thumbnail'])));
            $file_health_html = smcmlc_render_file_health_html($file_health);

            $attached_to      = 'Unattached';
            $attached_to_html = 'Unattached';
            $used_where       = 'Media Library';
            $risk_status      = 'Review';
            $parent_id        = 0;
            $parent_edit_link = '';
            $parent_view_link = '';
            $attachment_link  = get_edit_post_link($attachment->ID);
            $empty_usage         = smcmlc_get_empty_media_usage_result();
            $woo_usage           = smcmlc_get_woocommerce_usage($attachment->ID);
            $theme_usage         = smcmlc_get_media_library_theme_usage($attachment->ID);
            $content_usage       = smcmlc_find_content_usage($attachment->ID);
            $parent_usage     = array('html' => 'None detected', 'summary' => 'None detected', 'usage_count' => 0, 'likely_used' => false, 'protected' => false);

            if (!empty($attachment->post_parent)) {
                $parent = get_post($attachment->post_parent);

                if ($parent) {
                    $parent_id        = absint($parent->ID);
                    $attached_to      = get_the_title($parent_id);
                    $used_where       = smcmlc_get_post_type_label_for_usage($parent->post_type);
                    $risk_status      = 'Review';
                    $parent_edit_link = get_edit_post_link($parent_id, '');
                    $parent_view_link = get_permalink($parent_id);
                    $attached_to_html = smcmlc_get_parent_links_html($parent_id, $attached_to);
                }
            } else {
                $risk_status = 'Cleanup Candidate';
            }

            if ($parent_id) {
                $parent_usage = smcmlc_get_parent_usage($attachment->ID, $parent_id);
            }

            /*
             * Conservative safety rules:
             * - WooCommerce direct relationships are Protected.
             * - Site Logo, Site Icon, Header Image, and theme option relationships are Protected.
             * - Real product/page/post content references are Likely Used.
             * - Attachment parent alone is Review, not Likely Used.
             * - No parent + no detected usage is Cleanup Candidate.
             * - Missing/broken files are surfaced separately.
             */
            if (!empty($woo_usage['protected'])) {
                $risk_status = 'Protected';
                $used_where  = 'WooCommerce';
            } elseif (!empty($theme_usage['protected'])) {
                $risk_status = 'Protected';
                $used_where  = 'Theme / Customizer';
            } elseif (!empty($content_usage['likely_used'])) {
                $risk_status = 'Likely Used';
                $used_where  = 'Content';
            } elseif ($parent_id) {
                $risk_status = 'Review';
            } else {
                $risk_status = 'Cleanup Candidate';
            }

            if ($missing_file) {
                $risk_status = 'Missing File';
            } elseif ($broken_image) {
                $risk_status = 'Broken Image';
            }

            $results[] = array(
                'id'                 => $attachment->ID,
                'preview'            => wp_get_attachment_image_url($attachment->ID, 'thumbnail'),
                'file_name'          => $file_name ? $file_name : 'Unknown file',
                'attached_to'        => $attached_to,
                'attached_to_html'   => $attached_to_html,
                'used_where'         => $used_where,
                'woo_usage'          => isset($woo_usage['summary']) ? $woo_usage['summary'] : 'None detected',
                'woo_usage_html'     => isset($woo_usage['html']) ? $woo_usage['html'] : 'None detected',
                'woo_usage_count'    => isset($woo_usage['usage_count']) ? absint($woo_usage['usage_count']) : 0,
                'content_usage'      => isset($content_usage['summary']) ? $content_usage['summary'] : 'None detected',
                'content_usage_html' => isset($content_usage['html']) ? $content_usage['html'] : 'None detected',
                'content_usage_count'=> isset($content_usage['usage_count']) ? absint($content_usage['usage_count']) : 0,
                'theme_usage'        => isset($theme_usage['summary']) ? $theme_usage['summary'] : 'None detected',
                'theme_usage_html'   => isset($theme_usage['html']) ? $theme_usage['html'] : 'None detected',
                'theme_usage_count'  => isset($theme_usage['usage_count']) ? absint($theme_usage['usage_count']) : 0,
                'parent_usage'       => isset($parent_usage['summary']) ? $parent_usage['summary'] : 'None detected',
                'parent_usage_html'  => isset($parent_usage['html']) ? $parent_usage['html'] : 'None detected',
                'parent_usage_count' => isset($parent_usage['usage_count']) ? absint($parent_usage['usage_count']) : 0,
                'used_in_html'       => smcmlc_merge_usage_html($woo_usage, $content_usage, $parent_usage, $theme_usage, $file_health_html),
                'risk_status'        => $risk_status,
                'size'               => $file_size,
                'size_bytes'         => $size_bytes,
                'missing_file'       => $missing_file,
                'broken_image'       => $broken_image,
                'file_health'        => $file_health,
                'edit_link'          => $attachment_link,
                'parent_id'          => $parent_id,
                'parent_edit_link'   => $parent_edit_link,
                'parent_view_link'   => $parent_view_link,
            );
        }

        update_option('smcmlc_last_scan_results', $results, false);
        update_option('smcmlc_last_scan_summary', smcmlc_get_scan_summary($results), false);

        return $results;
    }
}

if (!function_exists('smcmlc_ajax_scan_media_library')) {
    function smcmlc_ajax_scan_media_library() {
        if (function_exists('set_time_limit')) {
            @set_time_limit(0);
        }

        check_ajax_referer('smcmlc_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied.');
        }

        $results = smcmlc_scan_media_library_images();
        $summary = smcmlc_get_scan_summary($results);

        ob_start();
        smcmlc_render_scan_table($results, $summary);
        $html = ob_get_clean();

        wp_send_json_success(array(
            'html'    => $html,
            'count'   => count($results),
            'summary' => $summary,
        ));
    }
}
add_action('wp_ajax_smcmlc_scan_media_library', 'smcmlc_ajax_scan_media_library');

if (!function_exists('smcmlc_ajax_bulk_trash_images')) {
    function smcmlc_ajax_bulk_trash_images() {
        check_ajax_referer('smcmlc_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied.');
        }

        $ids = isset($_POST['ids']) ? (array) $_POST['ids'] : array();
        $ids = array_filter(array_map('absint', $ids));

        if (empty($ids)) {
            wp_send_json_error('No images selected.');
        }

        $trashed = 0;
        $failed  = 0;

        foreach ($ids as $id) {
            if (!$id || get_post_type($id) !== 'attachment') {
                $failed++;
                continue;
            }

            $result = wp_trash_post($id);

            if ($result) {
                $trashed++;
            } else {
                $failed++;
            }
        }

        wp_send_json_success(array(
            'message' => sprintf(
                '%d image(s) moved to Trash%s.',
                $trashed,
                $failed ? ' and ' . $failed . ' failed' : ''
            ),
            'trashed' => $trashed,
            'failed'  => $failed,
            'trashed_ids' => $ids,
        ));
    }
}
add_action('wp_ajax_smcmlc_bulk_trash_images', 'smcmlc_ajax_bulk_trash_images');

if (!function_exists('smcmlc_render_scan_summary')) {
    function smcmlc_render_scan_summary($summary) {
        if (empty($summary) || !is_array($summary)) {
            return;
        }

        echo '<div class="smcmlc_scan-summary">';
        echo '<div><span>Total Scanned</span><strong>' . esc_html(number_format_i18n($summary['total'])) . '</strong></div>';
        echo '<div><span>Protected</span><strong>' . esc_html(number_format_i18n($summary['protected'])) . '</strong></div>';
        echo '<div><span>WooCommerce</span><strong>' . esc_html(number_format_i18n($summary['woocommerce'])) . '</strong></div>';
        echo '<div><span>Theme / Logo</span><strong>' . esc_html(number_format_i18n(isset($summary['theme_customizer']) ? $summary['theme_customizer'] : 0)) . '</strong></div>';
        echo '<div><span>Likely Used</span><strong>' . esc_html(number_format_i18n($summary['likely_used'])) . '</strong></div>';
        echo '<div><span>Cleanup Candidates</span><strong>' . esc_html(number_format_i18n($summary['cleanup'])) . '</strong></div>';
        echo '<div><span>Missing Files</span><strong>' . esc_html(number_format_i18n($summary['missing_files'])) . '</strong></div>';
        echo '<div><span>Broken Images</span><strong>' . esc_html(number_format_i18n(isset($summary['broken_images']) ? $summary['broken_images'] : 0)) . '</strong></div>';
        echo '<div><span>Total Size</span><strong>' . esc_html($summary['total_size']) . '</strong></div>';
        echo '</div>';
    }
}

if (!function_exists('smcmlc_render_bulk_action_bar')) {
    function smcmlc_render_bulk_action_bar($position = 'top') {
        $position = sanitize_key($position);

        if (!in_array($position, array('top', 'bottom'), true)) {
            $position = 'top';
        }

        $is_bottom = ($position === 'bottom');
        $bar_class = $is_bottom ? ' smcmlc_bulk-actions-bottom' : ' smcmlc_bulk-actions-top';
        $label     = $is_bottom ? 'Bottom bulk cleanup bar' : 'Top bulk cleanup bar';

        echo '<div class="smcmlc_bulk-actions smcmlc_scan-bulk-actions' . esc_attr($bar_class) . '" aria-label="' . esc_attr($label) . '">';
        echo '<div class="smcmlc_bulk-actions-left">';
        echo '<label class="smcmlc_bulk-select-label">';
        echo '<input type="checkbox" class="smcmlc_select-all-images-control" data-smcmlc_select-position="' . esc_attr($position) . '" aria-label="Select all images in scan results">';
        echo '<span>Select All</span>';
        echo '</label>';
        echo '<span class="smcmlc_selected-pill"><strong class="smcmlc_selected-count">0</strong> selected</span>';
        echo '</div>';
        echo '<div class="smcmlc_bulk-actions-right">';
        echo '<button type="button" class="smcmlc_btn smcmlc_btn-pink smcmlc_bulk-trash-selected smcmlc_bulk-trash-action" data-smcmlc_bulk-position="' . esc_attr($position) . '" disabled>Move Selected to Trash</button>';
        echo '</div>';
        echo '</div>';
    }
}

if (!function_exists('smcmlc_render_scan_toolbar')) {
    function smcmlc_render_scan_toolbar($summary = array()) {
        echo '<div class="smcmlc_scan-toolbar">';
        echo '<div class="smcmlc_scan-toolbar-left">';
        echo '<span class="smcmlc_toolbar-help">The scan checks all image attachments in the Media Library.</span>';
        echo '</div>';
        echo '<div class="smcmlc_scan-toolbar-right">';
        echo '<span class="smcmlc_toolbar-help">Select images below, then use the top or bottom bulk cleanup bar.</span>';
        echo '</div>';
        echo '</div>';

        smcmlc_render_scan_summary($summary);
        smcmlc_render_bulk_action_bar('top');
    }
}

if (!function_exists('smcmlc_allowed_attached_html')) {
    function smcmlc_allowed_attached_html() {
        return array(
            'div' => array(
                'class' => array(),
            ),
            'strong' => array(),
            'span' => array(
                'class' => array(),
            ),
            'a' => array(
                'href'   => array(),
                'target' => array(),
                'rel'    => array(),
                'class'  => array(),
            ),
        );
    }
}

if (!function_exists('smcmlc_get_status_class')) {
    function smcmlc_get_status_class($status) {
        $status = strtolower((string) $status);
        $status = str_replace(' ', '-', $status);

        return sanitize_html_class($status);
    }
}

if (!function_exists('smcmlc_is_trash_or_delete_admin_page')) {
    function smcmlc_is_trash_or_delete_admin_page() {
        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';

        return in_array($page, array(
            'smart-media-cleanup-trash',
            'smart-media-cleanup-delete',
            'smart-media-cleanup-permanent-delete',
            'smart-media-cleanup-trash-review',
        ), true);
    }
}

if (!function_exists('smcmlc_should_show_media_details_link')) {
    function smcmlc_should_show_media_details_link($attachment_id) {
        $attachment_id = absint($attachment_id);

        if (!$attachment_id || smcmlc_is_trash_or_delete_admin_page()) {
            return false;
        }

        $status = get_post_status($attachment_id);

        if ($status === 'trash') {
            return false;
        }

        return (bool) get_edit_post_link($attachment_id);
    }
}

if (!function_exists('smcmlc_render_media_file_actions')) {
    function smcmlc_render_media_file_actions($attachment_id, $edit_link = '') {
        $attachment_id = absint($attachment_id);

        if (!$attachment_id || !smcmlc_should_show_media_details_link($attachment_id)) {
            return;
        }

        if (!$edit_link) {
            $edit_link = get_edit_post_link($attachment_id);
        }

        if (!$edit_link) {
            return;
        }

        echo '<div class="smcmlc_file-actions"><a href="' . esc_url($edit_link) . '" target="_blank" rel="noopener noreferrer">Media Details</a></div>';
    }
}

if (!function_exists('smcmlc_render_scan_table')) {
    function smcmlc_render_scan_table($results, $summary = array()) {
        if (empty($results)) {
            echo '<p>No images found.</p>';
            return;
        }

        if (empty($summary)) {
            $summary = smcmlc_get_scan_summary($results);
        }

        smcmlc_render_scan_toolbar($summary);

        echo '<table class="smcmlc_table smcmlc_scan-table">';
        echo '<thead><tr>';
        echo '<th class="smcmlc_check-col"><input type="checkbox" id="smcmlc_select-all-images" class="smcmlc_select-all-images-control" data-smcmlc_select-position="header" aria-label="Select all images"></th>';
        echo '<th>Image Preview</th>';
        echo '<th>File Name</th>';
        echo '<th>Attached To</th>';
        echo '<th>Used Where</th>';
        echo '<th>Used In</th>';
        echo '<th>Risk Status</th>';
        echo '<th>Size</th>';
        echo '<th>Action</th>';
        echo '</tr></thead><tbody>';

        foreach ($results as $item) {
            $preview      = !empty($item['preview']) ? $item['preview'] : includes_url('images/media/default.png');
            $risk_status  = isset($item['risk_status']) ? $item['risk_status'] : 'Review';
            $status_class = smcmlc_get_status_class($risk_status);
            $woo_html     = !empty($item['used_in_html']) ? $item['used_in_html'] : (!empty($item['woo_usage_html']) ? $item['woo_usage_html'] : 'None detected');

            echo '<tr data-attachment-id="' . esc_attr($item['id']) . '" data-smcmlc_row-id="' . esc_attr($item['id']) . '">';
            echo '<td class="smcmlc_check-col"><input type="checkbox" class="smcmlc_image-select smcmlc_image-checkbox" value="' . esc_attr($item['id']) . '" aria-label="Select image"></td>';
            echo '<td><img class="smcmlc_thumb" src="' . esc_url($preview) . '" alt=""></td>';
            echo '<td>';
            echo '<strong>' . esc_html($item['file_name']) . '</strong>';

            smcmlc_render_media_file_actions($item['id'], !empty($item['edit_link']) ? $item['edit_link'] : '');

            echo '</td>';
            echo '<td>';

            if (!empty($item['attached_to_html'])) {
                echo wp_kses($item['attached_to_html'], smcmlc_allowed_attached_html());
            } else {
                echo esc_html($item['attached_to']);
            }

            echo '</td>';
            echo '<td>' . esc_html($item['used_where']) . '</td>';
            echo '<td>';

            if ($woo_html && $woo_html !== 'None detected') {
                echo wp_kses($woo_html, smcmlc_allowed_attached_html());
            } else {
                echo '<span class="smcmlc_muted">None detected</span>';
            }

            echo '</td>';
            echo '<td><span class="smcmlc_badge smcmlc_status-' . esc_attr($status_class) . '">' . esc_html($risk_status) . '</span></td>';
            echo '<td>' . esc_html($item['size']) . '</td>';
            echo '<td><button type="button" class="smcmlc_btn smcmlc_btn-small smcmlc_trash-image" data-id="' . esc_attr($item['id']) . '">Move to Trash</button></td>';
            echo '</tr>';
        }

        echo '</tbody></table>';

        smcmlc_render_bulk_action_bar('bottom');
    }
}