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

/* -------------------------------------------------------
   SMART MEDIA CLEANUP TRASH MANAGER
   Version: 1.1.9

    Media Library Trash Manager
   - Handles WordPress Media Library attachment Trash only.
   - Permanent delete requires the attachment to already be in Trash.
------------------------------------------------------- */

if (!function_exists('smcmlc_get_attachment_size_bytes')) {
    function smcmlc_get_attachment_size_bytes($attachment_id) {
        $attachment_id = absint($attachment_id);
        $file = $attachment_id ? get_attached_file($attachment_id) : '';

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

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

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

        if (!$attachment_id) {
            return 'Unknown file';
        }

        $file = get_attached_file($attachment_id);

        if ($file) {
            return basename((string) $file);
        }

        $meta_file = get_post_meta($attachment_id, '_wp_attached_file', true);

        if ($meta_file) {
            return basename((string) $meta_file);
        }

        return 'Unknown file';
    }
}

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

        $context = array(
            'risk_status'      => 'Review',
            'used_where'       => 'Trash Review',
            'used_in_html'     => '',
            'attached_to_html' => '',
            'size_bytes'       => 0,
        );

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

        $last_scan = get_option('smcmlc_last_scan_results', array());

        if (empty($last_scan) || !is_array($last_scan)) {
            return $context;
        }

        foreach ($last_scan as $item) {
            if (empty($item['id']) || absint($item['id']) !== $attachment_id) {
                continue;
            }

            if (!empty($item['risk_status'])) {
                $context['risk_status'] = sanitize_text_field($item['risk_status']);
            }

            if (!empty($item['used_where'])) {
                $context['used_where'] = sanitize_text_field($item['used_where']);
            }

            if (!empty($item['used_in_html'])) {
                $context['used_in_html'] = $item['used_in_html'];
            }

            if (!empty($item['attached_to_html'])) {
                $context['attached_to_html'] = $item['attached_to_html'];
            }

            if (!empty($item['size_bytes'])) {
                $context['size_bytes'] = absint($item['size_bytes']);
            }

            break;
        }

        return $context;
    }
}

if (!function_exists('smcmlc_allowed_trash_context_html')) {
    function smcmlc_allowed_trash_context_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_trash_status_class')) {
    function smcmlc_get_trash_status_class($status) {
        $status = strtolower((string) $status);
        $status = str_replace(' ', '-', $status);

        return sanitize_html_class($status);
    }
}

if (!function_exists('smcmlc_get_cleanup_action_label')) {
    function smcmlc_get_cleanup_action_label($type) {
        $type = sanitize_key($type);

        $labels = array(
            'trash'   => 'Image moved to Trash.',
            'restore' => 'Image restored from Trash.',
            'delete'  => 'Image permanently deleted.',
        );

        return isset($labels[$type]) ? $labels[$type] : 'Cleanup action completed.';
    }
}

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

        if (!$attachment_id) {
            return false;
        }

        if (get_post_type($attachment_id) !== 'attachment') {
            return false;
        }

        $mime_type = get_post_mime_type($attachment_id);

        if ($mime_type && strpos((string) $mime_type, 'image/') !== 0) {
            return false;
        }

        return true;
    }
}

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

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

        return get_post_status($attachment_id) === 'trash';
    }
}

if (!function_exists('smcmlc_get_cleanup_stats')) {
    function smcmlc_get_cleanup_stats() {
        $stats = get_option('smcmlc_cleanup_stats', array());

        if (!is_array($stats)) {
            $stats = array();
        }

        $defaults = array(
            'images_trashed'      => 0,
            'images_restored'     => 0,
            'images_deleted'      => 0,
            'bytes_moved_trash'   => 0,
            'bytes_restored'      => 0,
            'bytes_deleted'       => 0,
            'last_action'         => '',
            'last_action_time'    => '',
        );

        return wp_parse_args($stats, $defaults);
    }
}

if (!function_exists('smcmlc_update_cleanup_stats')) {
    function smcmlc_update_cleanup_stats($type, $count = 1, $bytes = 0, $message = '') {
        $type  = sanitize_key($type);
        $count = absint($count);
        $bytes = absint($bytes);

        if (!$count) {
            $count = 1;
        }

        $stats = smcmlc_get_cleanup_stats();

        if ($type === 'trash') {
            $stats['images_trashed'] += $count;
            $stats['bytes_moved_trash'] += $bytes;
        } elseif ($type === 'restore') {
            $stats['images_restored'] += $count;
            $stats['bytes_restored'] += $bytes;
        } elseif ($type === 'delete') {
            $stats['images_deleted'] += $count;
            $stats['bytes_deleted'] += $bytes;
        }

        $stats['last_action']      = sanitize_text_field($message ? $message : smcmlc_get_cleanup_action_label($type));
        $stats['last_action_time'] = current_time('mysql');

        update_option('smcmlc_cleanup_stats', $stats, false);

        return $stats;
    }
}

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

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

        $id = isset($_POST['id']) ? absint($_POST['id']) : 0;

        if (!$id || !smcmlc_is_valid_media_library_attachment($id)) {
            wp_send_json_error('Invalid Media Library image attachment.');
        }

        $bytes   = smcmlc_get_attachment_size_bytes($id);
        $trashed = wp_trash_post($id);

        if ($trashed) {
            smcmlc_update_cleanup_stats('trash', 1, $bytes, 'Image moved to Trash.');
            wp_send_json_success('Image moved to Trash. Review it before permanent deletion.');
        }

        wp_send_json_error('Could not move image to Trash.');
    }
}
add_action('wp_ajax_smcmlc_trash_image', 'smcmlc_ajax_trash_image');

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

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

        $id = isset($_POST['id']) ? absint($_POST['id']) : 0;

        if (!$id || !smcmlc_is_valid_media_library_attachment($id)) {
            wp_send_json_error('Invalid Media Library image attachment.');
        }

        if (!smcmlc_is_attachment_in_trash($id)) {
            wp_send_json_error('This image is not currently in Trash.');
        }

        $bytes    = smcmlc_get_attachment_size_bytes($id);
        $restored = wp_untrash_post($id);

        if ($restored) {
            smcmlc_update_cleanup_stats('restore', 1, $bytes, 'Image restored from Trash.');
            wp_send_json_success('Image restored.');
        }

        wp_send_json_error('Could not restore image.');
    }
}
add_action('wp_ajax_smcmlc_restore_image', 'smcmlc_ajax_restore_image');

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

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

        $id = isset($_POST['id']) ? absint($_POST['id']) : 0;

        if (!$id || !smcmlc_is_valid_media_library_attachment($id)) {
            wp_send_json_error('Invalid Media Library image attachment.');
        }

        if (!smcmlc_is_attachment_in_trash($id)) {
            wp_send_json_error('Move this image to Trash before permanently deleting it.');
        }

        $bytes   = smcmlc_get_attachment_size_bytes($id);
        $deleted = wp_delete_attachment($id, true);

        if ($deleted) {
            smcmlc_update_cleanup_stats('delete', 1, $bytes, 'Image permanently deleted.');
            wp_send_json_success('Image permanently deleted.');
        }

        wp_send_json_error('Could not permanently delete image.');
    }
}
add_action('wp_ajax_smcmlc_delete_image_permanently', 'smcmlc_ajax_delete_image_permanently');

if (!function_exists('smcmlc_ajax_bulk_restore_images')) {
    function smcmlc_ajax_bulk_restore_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_values(array_unique(array_filter(array_map('absint', $ids))));

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

        $restored     = 0;
        $failed       = 0;
        $restored_ids = array();
        $bytes        = 0;

        foreach ($ids as $id) {
            if (!$id || !smcmlc_is_valid_media_library_attachment($id) || !smcmlc_is_attachment_in_trash($id)) {
                $failed++;
                continue;
            }

            $item_bytes = smcmlc_get_attachment_size_bytes($id);
            $result = wp_untrash_post($id);

            if ($result) {
                $restored++;
                $restored_ids[] = $id;
                $bytes += $item_bytes;
            } else {
                $failed++;
            }
        }

        if ($restored) {
            smcmlc_update_cleanup_stats('restore', $restored, $bytes, 'Bulk restored images from Trash.');
        }

        wp_send_json_success(array(
            'message'      => sprintf(
                '%d image(s) restored%s.',
                $restored,
                $failed ? ' and ' . $failed . ' failed' : ''
            ),
            'restored'     => $restored,
            'failed'       => $failed,
            'restored_ids' => $restored_ids,
        ));
    }
}
add_action('wp_ajax_smcmlc_bulk_restore_images', 'smcmlc_ajax_bulk_restore_images');

if (!function_exists('smcmlc_ajax_bulk_delete_images_permanently')) {
    function smcmlc_ajax_bulk_delete_images_permanently() {
        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_values(array_unique(array_filter(array_map('absint', $ids))));

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

        $deleted     = 0;
        $failed      = 0;
        $deleted_ids = array();
        $bytes       = 0;

        foreach ($ids as $id) {
            if (!$id || !smcmlc_is_valid_media_library_attachment($id) || !smcmlc_is_attachment_in_trash($id)) {
                $failed++;
                continue;
            }

            $item_bytes = smcmlc_get_attachment_size_bytes($id);
            $result = wp_delete_attachment($id, true);

            if ($result) {
                $deleted++;
                $deleted_ids[] = $id;
                $bytes += $item_bytes;
            } else {
                $failed++;
            }
        }

        if ($deleted) {
            smcmlc_update_cleanup_stats('delete', $deleted, $bytes, 'Bulk permanently deleted images.');
        }

        wp_send_json_success(array(
            'message'     => sprintf(
                '%d image(s) permanently deleted%s.',
                $deleted,
                $failed ? ' and ' . $failed . ' failed' : ''
            ),
            'deleted'     => $deleted,
            'failed'      => $failed,
            'deleted_ids' => $deleted_ids,
            'bytes'       => $bytes,
            'size'        => size_format($bytes),
        ));
    }
}
add_action('wp_ajax_smcmlc_bulk_delete_images_permanently', 'smcmlc_ajax_bulk_delete_images_permanently');

if (!function_exists('smcmlc_get_trashed_images')) {
    function smcmlc_get_trashed_images($limit = 100) {
        $limit = (int) $limit;

        if ($limit === 0) {
            $limit = 100;
        }

        if ($limit < -1) {
            $limit = 100;
        }

        return get_posts(array(
            'post_type'      => 'attachment',
            'post_mime_type' => 'image',
            'post_status'    => 'trash',
            'posts_per_page' => $limit,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ));
    }
}

if (!function_exists('smcmlc_get_trash_summary')) {
    function smcmlc_get_trash_summary($items) {
        $summary = array(
            'count'       => 0,
            'bytes'       => 0,
            'size'        => '0 B',
            'unattached'  => 0,
            'attached'    => 0,
            'missing'     => 0,
            'cleanup_candidates' => 0,
            'review_items'       => 0,
            'protected_items'    => 0,
        );

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

        foreach ($items as $item) {
            if (!$item || empty($item->ID)) {
                continue;
            }

            $summary['count']++;

            $file = get_attached_file($item->ID);

            if ($file && file_exists($file)) {
                $summary['bytes'] += (int) filesize($file);
            } else {
                $summary['missing']++;
            }

            if (!empty($item->post_parent)) {
                $summary['attached']++;
            } else {
                $summary['unattached']++;
            }

            $context = smcmlc_get_last_scan_context_for_attachment($item->ID);
            $status  = strtolower((string) $context['risk_status']);

            if ($status === 'cleanup candidate') {
                $summary['cleanup_candidates']++;
            } elseif ($status === 'protected') {
                $summary['protected_items']++;
            } else {
                $summary['review_items']++;
            }
        }

        $summary['size'] = size_format($summary['bytes']);

        return $summary;
    }
}

if (!function_exists('smcmlc_render_trash_summary')) {
    function smcmlc_render_trash_summary($items, $permanent = false) {
        $summary = smcmlc_get_trash_summary($items);
        $stats   = smcmlc_get_cleanup_stats();

        echo '<div class="smcmlc_trash-summary">';
        echo '<div><span>Images In Trash</span><strong>' . esc_html(number_format_i18n($summary['count'])) . '</strong></div>';
        echo '<div><span>Estimated Trash Size</span><strong>' . esc_html($summary['size']) . '</strong></div>';
        echo '<div><span>Attached Before Trash</span><strong>' . esc_html(number_format_i18n($summary['attached'])) . '</strong></div>';
        echo '<div><span>Unattached Before Trash</span><strong>' . esc_html(number_format_i18n($summary['unattached'])) . '</strong></div>';
        echo '<div><span>Missing Files</span><strong>' . esc_html(number_format_i18n($summary['missing'])) . '</strong></div>';
        echo '<div><span>Cleanup Candidates</span><strong>' . esc_html(number_format_i18n($summary['cleanup_candidates'])) . '</strong></div>';
        echo '<div><span>Review Items</span><strong>' . esc_html(number_format_i18n($summary['review_items'])) . '</strong></div>';
        echo '<div><span>Protected Before Trash</span><strong>' . esc_html(number_format_i18n($summary['protected_items'])) . '</strong></div>';
        echo '<div><span>Images Cleaned</span><strong>' . esc_html(number_format_i18n($stats['images_deleted'])) . '</strong></div>';
        echo '<div><span>Storage Recovered</span><strong>' . esc_html(size_format(absint($stats['bytes_deleted']))) . '</strong></div>';

        if (!empty($stats['last_action'])) {
            echo '<div><span>Last Action</span><strong>' . esc_html($stats['last_action']) . '</strong></div>';
        }

        echo '</div>';

        if ($permanent) {
            echo '<div class="smcmlc_notice smcmlc_danger smcmlc_trash-danger-note"><strong>Final warning:</strong> permanent deletion removes the attachment and image files. Use Select All only after checking your site.</div>';
        } else {
            echo '<div class="smcmlc_notice smcmlc_warning smcmlc_trash-review-note"><strong>Trash review:</strong> restore anything that still appears on your site. Permanently delete only after checking pages and products.</div>';
        }
    }
}

if (!function_exists('smcmlc_get_attachment_parent_links')) {
    function smcmlc_get_attachment_parent_links($parent_id) {
        $parent_id = absint($parent_id);

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

        $parent = get_post($parent_id);

        if (!$parent) {
            return '';
        }

        $links = array();
        $edit_link = get_edit_post_link($parent_id);
        $view_link = get_permalink($parent_id);

        if ($edit_link) {
            $links[] = '<a class="smcmlc_mini-link" href="' . esc_url($edit_link) . '" target="_blank" rel="noopener noreferrer">✏️ Edit</a>';
        }

        if ($view_link) {
            $links[] = '<a class="smcmlc_mini-link" href="' . esc_url($view_link) . '" target="_blank" rel="noopener noreferrer">👁 View</a>';
        }

        if (empty($links)) {
            return '';
        }

        return '<div class="smcmlc_parent-links">' . implode(' <span class="smcmlc_link-separator">|</span> ', $links) . '</div>';
    }
}


if (!function_exists('smcmlc_extract_trash_usage_label_from_context')) {
    function smcmlc_extract_trash_usage_label_from_context($context) {
        if (empty($context) || empty($context['used_in_html'])) {
            return '';
        }

        $plain = wp_strip_all_tags((string) $context['used_in_html']);
        $plain = html_entity_decode($plain, ENT_QUOTES, 'UTF-8');
        $plain = preg_replace('/\s+/', ' ', $plain);
        $plain = trim($plain);

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

        if (preg_match('/Used In:\s*([^·|]+)/i', $plain, $matches)) {
            return sanitize_text_field(trim($matches[1]));
        }

        if (preg_match('/^(Site Logo|Header Logo|Footer Logo|Mobile Logo|Retina Logo|Sticky Header Logo|Site Icon|Header Image|Theme Customizer Image|Theme Option Image)/i', $plain, $matches)) {
            return sanitize_text_field(trim($matches[1]));
        }

        return '';
    }
}

if (!function_exists('smcmlc_get_trash_attached_display_html')) {
    function smcmlc_get_trash_attached_display_html($item, $context = array()) {
        if (!empty($item->post_parent)) {
            $parent_title = get_the_title($item->post_parent);
            $parent_links = smcmlc_get_attachment_parent_links($item->post_parent);

            $html  = '<strong>' . esc_html($parent_title ? $parent_title : 'Attached Item') . '</strong>';
            $html .= $parent_links; // Already escaped in helper.

            return $html;
        }

        if (!empty($context['attached_to_html'])) {
            $attached_text = trim(wp_strip_all_tags((string) $context['attached_to_html']));

            if ($attached_text !== '' && strtolower($attached_text) !== 'unattached') {
                return wp_kses($context['attached_to_html'], smcmlc_allowed_trash_context_html());
            }
        }

        $relationship_label = smcmlc_extract_trash_usage_label_from_context($context);

        if ($relationship_label) {
            $html  = '<strong>' . esc_html($relationship_label) . '</strong>';
            $html .= '<div class="smcmlc_parent-links"><span class="smcmlc_mini-link">Protected relationship before Trash</span></div>';

            return $html;
        }

        $used_where = !empty($context['used_where']) ? sanitize_text_field($context['used_where']) : '';

        if ($used_where && !in_array($used_where, array('Trash Review', 'Media Library'), true)) {
            $html  = '<strong>' . esc_html($used_where) . '</strong>';
            $html .= '<div class="smcmlc_parent-links"><span class="smcmlc_mini-link">Detected before Trash</span></div>';

            return $html;
        }

        return '<strong>Unattached</strong>';
    }
}



if (!function_exists('smcmlc_render_trash_bulk_bar')) {
    function smcmlc_render_trash_bulk_bar($permanent = false, $position = 'top') {
        $position = sanitize_key($position);
        $position_class = $position === 'bottom' ? ' smcmlc_trash-bulk-bottom' : ' smcmlc_trash-bulk-top';

        echo '<div class="smcmlc_trash-bulk-actions' . esc_attr($position_class) . '">';
        echo '<div class="smcmlc_trash-bulk-left">';
        echo '<label class="smcmlc_bulk-select-label">';
        echo '<input type="checkbox" class="smcmlc_trash-select-all-control" data-smcmlc_trash-select-position="' . esc_attr($position) . '" aria-label="Select all trashed images">';
        echo '<span>Select All</span>';
        echo '</label>';
        echo '<span class="smcmlc_selected-pill"><strong class="smcmlc_trash-selected-count">0</strong> selected</span>';
        echo '<span class="smcmlc_selected-pill"><strong class="smcmlc_trash-selected-storage-count" data-smcmlc_trash-selected-storage>0 B</strong> selected storage</span>';
        echo '</div>';

        echo '<div class="smcmlc_trash-bulk-right">';

        if (!$permanent) {
            echo '<button type="button" class="smcmlc_btn smcmlc_bulk-restore-selected" disabled>Restore Selected</button>';
        }

        echo '<button type="button" class="smcmlc_btn smcmlc_bulk-delete-permanent" disabled>Permanent Delete Selected</button>';
        echo '</div>';
        echo '</div>';
    }
}


if (!function_exists('smcmlc_render_trash_table')) {
    function smcmlc_render_trash_table($permanent = false) {
        $items = smcmlc_get_trashed_images();

        if (empty($items)) {
            echo '<p>No trashed images found.</p>';
            return;
        }

        smcmlc_render_trash_summary($items, $permanent);
        smcmlc_render_trash_bulk_bar($permanent, 'top');

        echo '<div class="smcmlc_trash-table-scroll smcmlc_trash-table-responsive smcmlc_trash-table-frame-v159 smcmlc_trash-table-frame-v160 smcmlc_trash-table-frame-v161" role="region" aria-label="Media Library trash review table with action buttons moved left for safer visibility" tabindex="0">';
        echo '<table class="smcmlc_table smcmlc_trash-table smcmlc_trash-table-v157 smcmlc_trash-table-v158 smcmlc_trash-table-v159 smcmlc_trash-table-v160 smcmlc_trash-table-v161 smcmlc_trash-table-compact smcmlc_trash-actions-roomy smcmlc_trash-actions-roomy-v160 smcmlc_trash-actions-left-v161" style="table-layout:fixed;width:100%;max-width:100%;">';
        echo '<colgroup>';
        echo '<col class="smcmlc_trash-col-select" style="width:4%;">';
        echo '<col class="smcmlc_trash-col-actions" style="width:17%;">';
        echo '<col class="smcmlc_trash-col-preview" style="width:7%;">';
        echo '<col class="smcmlc_trash-col-file" style="width:18%;">';
        echo '<col class="smcmlc_trash-col-attached" style="width:15%;">';
        echo '<col class="smcmlc_trash-col-status" style="width:8%;">';
        echo '<col class="smcmlc_trash-col-source" style="width:23%;">';
        echo '<col class="smcmlc_trash-col-size" style="width:8%;">';
        echo '</colgroup>';
        echo '<thead><tr>';
        echo '<th class="smcmlc_check-col" style="width:4%;"><input type="checkbox" class="smcmlc_trash-select-all-control" data-smcmlc_trash-select-position="header" aria-label="Select all trashed images"></th>';
        echo '<th class="smcmlc_trash-action-col" style="width:17%;min-width:170px;">Actions</th>';
        echo '<th class="smcmlc_trash-preview-col" style="width:7%;">Preview</th>';
        echo '<th class="smcmlc_trash-file-col" style="width:18%;">File</th>';
        echo '<th class="smcmlc_trash-attached-col" style="width:15%;">Usage</th>';
        echo '<th class="smcmlc_trash-status-col" style="width:8%;">Status</th>';
        echo '<th class="smcmlc_trash-source-col" style="width:23%;">Detected Usage</th>';
        echo '<th class="smcmlc_trash-size-col" style="width:8%;">Size</th>';
        echo '</tr></thead><tbody>';

        foreach ($items as $item) {
            $file = get_attached_file($item->ID);
            $file_name = smcmlc_get_attachment_file_name_for_cleanup($item->ID);
            $size_bytes = ($file && file_exists($file)) ? (int) filesize($file) : 0;
            $size = $size_bytes ? size_format($size_bytes) : 'Missing file';
            $context = smcmlc_get_last_scan_context_for_attachment($item->ID);
            $attached_display_html = smcmlc_get_trash_attached_display_html($item, $context);
            $risk_status = !empty($context['risk_status']) ? $context['risk_status'] : 'Review';
            $used_where = !empty($context['used_where']) ? $context['used_where'] : 'Trash Review';
            $status_class = smcmlc_get_trash_status_class($risk_status);

            echo '<tr data-attachment-id="' . esc_attr($item->ID) . '" data-smcmlc_trash-row-id="' . esc_attr($item->ID) . '" data-size-bytes="' . esc_attr($size_bytes) . '">';
            echo '<td class="smcmlc_check-col" style="width:4%;"><input type="checkbox" class="smcmlc_trash-image-select smcmlc_trash-image-checkbox" value="' . esc_attr($item->ID) . '" aria-label="Select trashed image"></td>';
            echo '<td class="smcmlc_trash-actions smcmlc_trash-actions-cell smcmlc_trash-actions-left-cell" style="width:17%;min-width:170px;overflow:visible;white-space:normal;">';
            echo '<div class="smcmlc_trash-action-stack smcmlc_trash-action-stack-v159 smcmlc_trash-action-stack-v160 smcmlc_trash-action-stack-v161" aria-label="Trash row actions" style="display:flex;flex-direction:column;gap:9px;align-items:stretch;justify-content:center;width:100%;min-width:150px;max-width:210px;">';

            if ($permanent) {
                echo '<button type="button" class="smcmlc_btn smcmlc_btn-pink smcmlc_delete-permanent smcmlc_trash-action-button smcmlc_trash-delete-button" style="display:flex;width:100%;min-width:145px;min-height:42px;padding:10px 12px;margin:0;white-space:normal;text-align:center;line-height:1.12;" data-id="' . esc_attr($item->ID) . '">Delete Permanently</button>';
            } else {
                echo '<button type="button" class="smcmlc_btn smcmlc_restore-image smcmlc_btn-restore-neon smcmlc_trash-action-button smcmlc_trash-restore-button" style="display:flex;width:100%;min-width:145px;min-height:42px;padding:10px 12px;margin:0;white-space:normal;text-align:center;line-height:1.12;color:#06150f !important;font-weight:950;" data-id="' . esc_attr($item->ID) . '">Restore</button>';
                echo '<button type="button" class="smcmlc_btn smcmlc_btn-pink smcmlc_delete-permanent smcmlc_trash-action-button smcmlc_trash-delete-button" style="display:flex;width:100%;min-width:145px;min-height:42px;padding:10px 12px;margin:0;white-space:normal;text-align:center;line-height:1.12;" data-id="' . esc_attr($item->ID) . '">Delete Permanently</button>';
            }

            echo '</div>';
            echo '</td>';
            echo '<td class="smcmlc_trash-preview-cell" style="width:7%;">' . wp_kses_post(wp_get_attachment_image($item->ID, 'thumbnail', false, array('class' => 'smcmlc_thumb'))) . '</td>';
            echo '<td class="smcmlc_trash-file-cell" style="width:18%;word-break:break-word;overflow-wrap:anywhere;">';
            echo '<strong>' . esc_html($file_name) . '</strong>';
            echo '</td>';
            echo '<td class="smcmlc_trash-attached-cell" style="width:15%;word-break:break-word;overflow-wrap:anywhere;">';
            echo wp_kses($attached_display_html, smcmlc_allowed_trash_context_html());
            echo '</td>';
            echo '<td class="smcmlc_trash-status-cell" style="width:8%;text-align:center;"><span class="smcmlc_badge smcmlc_status-' . esc_attr($status_class) . '">' . esc_html($risk_status) . '</span></td>';
            echo '<td class="smcmlc_trash-source-cell" style="width:23%;word-break:break-word;overflow-wrap:anywhere;">' . esc_html($used_where) . '</td>';
            echo '<td class="smcmlc_trash-size-cell" style="width:8%;white-space:nowrap;">' . esc_html($size) . '</td>';
            echo '</tr>';
        }

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

        smcmlc_render_trash_bulk_bar($permanent, 'bottom');
    }
}


/* -------------------------------------------------------
   TRASH / PERMANENT DELETE PAGE CONNECTIONS
   Version: 1.1.9

   These wrappers connect the admin dashboard pages to the existing
   trash table renderer. They do not change cleanup behavior.
------------------------------------------------------- */

if (!function_exists('smcmlc_render_trash_manager')) {
    function smcmlc_render_trash_manager($permanent = false) {
        $permanent = (bool) $permanent;
        $items = smcmlc_get_trashed_images(-1);

        if (empty($items)) {
            echo '<p>No images are currently in Media Library Trash.</p>';
            return;
        }

        smcmlc_render_trash_summary($items, $permanent);
        smcmlc_render_trash_table($items, $permanent);
    }
}

if (!function_exists('smcmlc_render_media_library_trash_manager')) {
    function smcmlc_render_media_library_trash_manager() {
        smcmlc_render_trash_manager(false);
    }
}

if (!function_exists('smcmlc_render_free_trash_manager')) {
    function smcmlc_render_free_trash_manager() {
        smcmlc_render_trash_manager(false);
    }
}

if (!function_exists('smcmlc_render_permanent_delete_manager')) {
    function smcmlc_render_permanent_delete_manager() {
        smcmlc_render_trash_manager(true);
    }
}

if (!function_exists('smcmlc_render_media_library_delete_manager')) {
    function smcmlc_render_media_library_delete_manager() {
        smcmlc_render_trash_manager(true);
    }
}

if (!function_exists('smcmlc_render_free_permanent_delete_manager')) {
    function smcmlc_render_free_permanent_delete_manager() {
        smcmlc_render_trash_manager(true);
    }
}