<?php
/**
 * Name: Resize Images on Upload
 * Description: Automatically resize uploaded images to maximum dimensions while preserving aspect ratio to prevent oversized files from slowing down your site and wasting storage space
 * Category: Media
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Prevent Oversized Uploads",
 *     "description": "Automatically resize 6000x4000px phone photos to 1920x1920px max to reduce file sizes and improve page load times."
 *   },
 *   {
 *     "title": "Control Storage Costs",
 *     "description": "Limit image dimensions to prevent clients from uploading massive files that consume hosting storage and bandwidth."
 *   },
 *   {
 *     "title": "Optimize Mobile Photos",
 *     "description": "Resize high-resolution smartphone photos to web-appropriate dimensions while maintaining quality and aspect ratio."
 *   }
 * ]
 * Added: 2025-11-23
 * Tags: resize, images, upload, dimensions, optimization, storage
 * WhereToFind: {
 *   "location": "Media Library",
 *   "url": "upload.php",
 *   "instructions": "Upload images - automatically resized if larger than max dimensions",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardResizeImagesOnUpload {

    private $settings;

    public function __construct() {
        $this->settings = get_option('switchboard_resize-images-on-upload_settings', []);

        // Hook into upload with priority 5 (runs before WebP conversion at priority 10)
        add_filter('wp_handle_upload', [$this, 'resize_uploaded_image'], 5, 2);

        // Register with data registry
        $this->register_with_data_registry();
    }

    private function register_with_data_registry() {
        if (class_exists('Switchboard_Data_Registry')) {
            $registry = Switchboard_Data_Registry::get_instance();
            $registry->auto_register($this, __FILE__);
        }
    }

    /**
     * Register data locations for cleanup system
     *
     * @return array Data storage locations
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_resize-images-on-upload_settings',
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'term_meta' => [],
            'transients' => []
        ];
    }

    /**
     * Render settings panel for Resize Images on Upload
     *
     * Displays settings interface for automatic image resizing with:
     * - Maximum width and height dimension controls
     * - Aspect ratio preservation notice
     * - Exclusion suffix for bypassing resize on specific files
     * - Visual examples and implementation notes
     *
     * @param array $settings Current module settings
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $max_width = isset($settings['max_width']) ? $settings['max_width'] : '1920';
        $max_height = isset($settings['max_height']) ? $settings['max_height'] : '1920';
        $exclusion_suffix = isset($settings['exclusion_suffix']) ? $settings['exclusion_suffix'] : '-full';

        ?>
        <input type="hidden" name="module" value="resize-images-on-upload">

        <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm">How It Works</h4>
            <p class="sb-sp-description" style="margin-bottom: 12px;">Images larger than the maximum dimensions are automatically resized to fit within those limits while <strong>preserving the original aspect ratio</strong>. The oversized original is deleted to save storage space.</p>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item"><strong>Square images stay square:</strong> 1500×1500 with max 800×600 → becomes 600×600</li>
                <li class="sb-sp-list-item"><strong>Wide images stay wide:</strong> 3000×2000 with max 800×600 → becomes 800×534</li>
                <li class="sb-sp-list-item"><strong>Tall images stay tall:</strong> 2000×3000 with max 800×600 → becomes 400×600</li>
            </ul>
            <p class="sb-sp-description" style="margin-top: 12px; margin-bottom: 0; font-style: italic;">The module ensures images fit within BOTH max width and max height without distortion or cropping.</p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Maximum Dimensions</h3>

            <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 16px;">
                <div class="sb-sp-field-horizontal-left">
                    <label for="setting_max_width" class="sb-sp-label">Max Width</label>
                    <p class="sb-sp-description">pixels (Recommended: 1920-2560)</p>
                </div>
                <input type="number" name="setting_max_width" id="setting_max_width" value="<?php echo esc_attr($max_width); ?>" min="100" max="10000" step="10" style="width: 150px;">
            </div>

            <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 16px;">
                <div class="sb-sp-field-horizontal-left">
                    <label for="setting_max_height" class="sb-sp-label">Max Height</label>
                    <p class="sb-sp-description">pixels (Recommended: 1920-2560)</p>
                </div>
                <input type="number" name="setting_max_height" id="setting_max_height" value="<?php echo esc_attr($max_height); ?>" min="100" max="10000" step="10" style="width: 150px;">
            </div>

            <div class="sb-sp-info-box sb-sp-info-box-tip">
                <h4 class="sb-sp-heading-sm">Aspect Ratio Preservation</h4>
                <p class="sb-sp-description" style="margin-bottom: 8px;">Images are resized proportionally to fit within these dimensions. <strong>Aspect ratio is always preserved</strong> - no distortion or cropping occurs.</p>
                <p class="sb-sp-description" style="margin: 0;"><strong>Example:</strong> 3000×2000px image with max 1920×1920 becomes <strong>1920×1280px</strong> (maintains 3:2 ratio)</p>
            </div>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Exclusion Suffix</h3>
            <div class="sb-sp-group sb-sp-field-horizontal">
                <div class="sb-sp-field-horizontal-left">
                    <label for="setting_exclusion_suffix" class="sb-sp-label">
                        Skip resize for images with this suffix
                    </label>
                    <p class="sb-sp-description">Images with this suffix in the filename will keep their original size (e.g., <code>hero-banner<strong><?php echo esc_html($exclusion_suffix); ?></strong>.jpg</code>)</p>
                </div>
                <input type="text" name="setting_exclusion_suffix" id="setting_exclusion_suffix" value="<?php echo esc_attr($exclusion_suffix); ?>" placeholder="-full" class="sb-sp-input" style="width: 200px;">
            </div>
            <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-top: 12px;">
                <p class="sb-sp-description" style="margin: 0;"><strong>Example:</strong> If set to <code>-full</code>, uploading <code>header-image-full.jpg</code> will keep the original dimensions unchanged, even if it exceeds the maximum width/height.</p>
            </div>
        </div>

        <hr class="sb-sp-divider">

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Resize Examples</h3>
            <p class="sb-sp-description" style="margin-bottom: 16px;">See how different image sizes are automatically resized while preserving aspect ratio:</p>
            <div class="sb-sp-card" style="border: 1px solid #e5e7eb; overflow: hidden;">
                <div class="sb-sp-card-body" style="padding: 0;">
                    <div style="overflow-x: auto;">
                        <table style="width: 100%; border-collapse: collapse; margin: 0;">
                            <thead>
                                <tr style="background: #f9fafb; border-bottom: 2px solid #e5e7eb;">
                                    <th style="padding: 12px 16px; text-align: left; font-size: 13px; font-weight: 600; color: #374151; white-space: nowrap;">Original Size</th>
                                    <th style="padding: 12px 16px; text-align: left; font-size: 13px; font-weight: 600; color: #374151; white-space: nowrap;">Aspect Ratio</th>
                                    <th style="padding: 12px 16px; text-align: left; font-size: 13px; font-weight: 600; color: #374151; white-space: nowrap;">Max Dimensions</th>
                                    <th style="padding: 12px 16px; text-align: left; font-size: 13px; font-weight: 600; color: #374151; white-space: nowrap;">Result</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr style="border-bottom: 1px solid #f3f4f6;">
                                    <td style="padding: 14px 16px; vertical-align: top;">
                                        <div style="display: flex; align-items: center; gap: 8px;">
                                            <span class="dashicons dashicons-camera" style="font-size: 18px; color: #9ca3af; width: 20px;"></span>
                                            <div>
                                                <strong style="font-size: 14px; color: #111827; display: block; margin-bottom: 2px;">6000×4000</strong>
                                                <span style="font-size: 12px; color: #6b7280;">Camera photo</span>
                                            </div>
                                        </div>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <span class="sb-sp-badge" style="background: #dbeafe; color: #1e40af; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 500; display: inline-block;">3:2 (wide)</span>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <code style="background: #f3f4f6; padding: 4px 8px; border-radius: 4px; font-size: 13px; color: #374151; font-family: 'Monaco', 'Menlo', monospace;">1920×1920</code>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <div style="display: flex; align-items: center; gap: 6px;">
                                            <span style="color: #166534; font-weight: 600; font-size: 14px; font-family: 'Monaco', 'Menlo', monospace;">1920×1280</span>
                                            <span class="dashicons dashicons-yes-alt" style="color: var(--primary-500); font-size: 16px; width: 16px; height: 16px;"></span>
                                        </div>
                                    </td>
                                </tr>
                                <tr style="border-bottom: 1px solid #f3f4f6; background: #fafafa;">
                                    <td style="padding: 14px 16px; vertical-align: top;">
                                        <div style="display: flex; align-items: center; gap: 8px;">
                                            <span class="dashicons dashicons-smartphone" style="font-size: 18px; color: #9ca3af; width: 20px;"></span>
                                            <div>
                                                <strong style="font-size: 14px; color: #111827; display: block; margin-bottom: 2px;">4032×3024</strong>
                                                <span style="font-size: 12px; color: #6b7280;">iPhone photo</span>
                                            </div>
                                        </div>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <span class="sb-sp-badge" style="background: #dbeafe; color: #1e40af; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 500; display: inline-block;">4:3 (wide)</span>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <code style="background: #f3f4f6; padding: 4px 8px; border-radius: 4px; font-size: 13px; color: #374151; font-family: 'Monaco', 'Menlo', monospace;">1920×1920</code>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <div style="display: flex; align-items: center; gap: 6px;">
                                            <span style="color: #166534; font-weight: 600; font-size: 14px; font-family: 'Monaco', 'Menlo', monospace;">1920×1440</span>
                                            <span class="dashicons dashicons-yes-alt" style="color: var(--primary-500); font-size: 16px; width: 16px; height: 16px;"></span>
                                        </div>
                                    </td>
                                </tr>
                                <tr style="border-bottom: 1px solid #f3f4f6;">
                                    <td style="padding: 14px 16px; vertical-align: top;">
                                        <div style="display: flex; align-items: center; gap: 8px;">
                                            <span class="dashicons dashicons-format-image" style="font-size: 18px; color: #9ca3af; width: 20px;"></span>
                                            <div>
                                                <strong style="font-size: 14px; color: #111827; display: block; margin-bottom: 2px;">1500×1500</strong>
                                                <span style="font-size: 12px; color: #6b7280;">Square image</span>
                                            </div>
                                        </div>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <span class="sb-sp-badge" style="background: #fef3c7; color: #92400e; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 500; display: inline-block;">1:1 (square)</span>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <code style="background: #f3f4f6; padding: 4px 8px; border-radius: 4px; font-size: 13px; color: #374151; font-family: 'Monaco', 'Menlo', monospace;">800×600</code>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <div style="display: flex; align-items: center; gap: 6px;">
                                            <span style="color: #166534; font-weight: 600; font-size: 14px; font-family: 'Monaco', 'Menlo', monospace;">600×600</span>
                                            <span class="dashicons dashicons-yes-alt" style="color: var(--primary-500); font-size: 16px; width: 16px; height: 16px;"></span>
                                        </div>
                                    </td>
                                </tr>
                                <tr style="border-bottom: 1px solid #f3f4f6; background: #fafafa;">
                                    <td style="padding: 14px 16px; vertical-align: top;">
                                        <div style="display: flex; align-items: center; gap: 8px;">
                                            <span class="dashicons dashicons-portrait" style="font-size: 18px; color: #9ca3af; width: 20px;"></span>
                                            <div>
                                                <strong style="font-size: 14px; color: #111827; display: block; margin-bottom: 2px;">2000×3000</strong>
                                                <span style="font-size: 12px; color: #6b7280;">Portrait photo</span>
                                            </div>
                                        </div>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <span class="sb-sp-badge" style="background: #fce7f3; color: #9f1239; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 500; display: inline-block;">2:3 (tall)</span>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <code style="background: #f3f4f6; padding: 4px 8px; border-radius: 4px; font-size: 13px; color: #374151; font-family: 'Monaco', 'Menlo', monospace;">800×1200</code>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <div style="display: flex; align-items: center; gap: 6px;">
                                            <span style="color: #166534; font-weight: 600; font-size: 14px; font-family: 'Monaco', 'Menlo', monospace;">800×1200</span>
                                            <span class="dashicons dashicons-yes-alt" style="color: var(--primary-500); font-size: 16px; width: 16px; height: 16px;"></span>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="padding: 14px 16px; vertical-align: top;">
                                        <div style="display: flex; align-items: center; gap: 8px;">
                                            <span class="dashicons dashicons-images-alt" style="font-size: 18px; color: #9ca3af; width: 20px;"></span>
                                            <div>
                                                <strong style="font-size: 14px; color: #111827; display: block; margin-bottom: 2px;">1200×800</strong>
                                                <span style="font-size: 12px; color: #6b7280;">Small image</span>
                                            </div>
                                        </div>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <span class="sb-sp-badge" style="background: #dbeafe; color: #1e40af; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 500; display: inline-block;">3:2 (wide)</span>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <code style="background: #f3f4f6; padding: 4px 8px; border-radius: 4px; font-size: 13px; color: #374151; font-family: 'Monaco', 'Menlo', monospace;">1920×1920</code>
                                    </td>
                                    <td style="padding: 14px 16px; vertical-align: middle;">
                                        <div style="display: flex; align-items: center; gap: 6px;">
                                            <span style="color: #6b7280; font-size: 14px; font-family: 'Monaco', 'Menlo', monospace;">1200×800</span>
                                            <span style="background: #f3f4f6; color: #6b7280; padding: 2px 6px; border-radius: 4px; font-size: 11px; font-weight: 500;">unchanged</span>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-tip" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm">Key Point</h4>
            <p class="sb-sp-description" style="margin: 0;">The resize always uses the <strong>smaller calculated dimension</strong> to ensure the image fits within BOTH width and height limits. This means square images (1:1 ratio) will be resized to the smaller of your two max values.</p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Benefits</h3>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px;">
                <div class="sb-sp-card" style="border-left: 3px solid var(--primary-500);">
                    <div class="sb-sp-card-body">
                        <h4 style="margin: 0 0 8px 0; font-size: 16px; font-weight: 600; color: #111827;">Save Storage Space</h4>
                        <p class="sb-sp-description" style="margin: 0; font-size: 13px; line-height: 1.5;">Reduce hosting costs by preventing unnecessarily large image files from consuming your storage quota</p>
                    </div>
                </div>
                <div class="sb-sp-card" style="border-left: 3px solid var(--primary-500);">
                    <div class="sb-sp-card-body">
                        <h4 style="margin: 0 0 8px 0; font-size: 16px; font-weight: 600; color: #111827;">Faster Page Loads</h4>
                        <p class="sb-sp-description" style="margin: 0; font-size: 13px; line-height: 1.5;">Smaller images mean faster download times for visitors, improving user experience and SEO scores</p>
                    </div>
                </div>
                <div class="sb-sp-card" style="border-left: 3px solid #f59e0b;">
                    <div class="sb-sp-card-body">
                        <h4 style="margin: 0 0 8px 0; font-size: 16px; font-weight: 600; color: #111827;">Fully Automatic</h4>
                        <p class="sb-sp-description" style="margin: 0; font-size: 13px; line-height: 1.5;">No manual resizing needed - works automatically on every upload without any additional steps</p>
                    </div>
                </div>
                <div class="sb-sp-card" style="border-left: 3px solid #8b5cf6;">
                    <div class="sb-sp-card-body">
                        <h4 style="margin: 0 0 8px 0; font-size: 16px; font-weight: 600; color: #111827;">Preserves Quality</h4>
                        <p class="sb-sp-description" style="margin: 0; font-size: 13px; line-height: 1.5;">Maintains aspect ratio and uses high-quality resampling algorithms for crisp, professional results</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-tip">
            <h4 class="sb-sp-heading-sm">Important Notes</h4>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item">Only affects <strong>new uploads</strong> after enabling this module</li>
                <li class="sb-sp-list-item">Existing images in your media library are not affected</li>
                <li class="sb-sp-list-item">Original oversized files are deleted after resizing to save storage</li>
                <li class="sb-sp-list-item">Works great with the <strong>WebP Conversion</strong> module for maximum optimization</li>
                <li class="sb-sp-list-item">Supports JPEG, PNG, and BMP formats (BMP converted to JPEG)</li>
            </ul>
        </div>
        <?php
    }

    /**
     * Resize uploaded image if it exceeds maximum dimensions
     *
     * @param array $upload Upload data
     * @return array Modified upload data
     */
    public function resize_uploaded_image($upload) {
        // Check if upload was successful
        if (isset($upload['error']) && $upload['error']) {
            return $upload;
        }

        $file_path = $upload['file'];
        $file_type = $upload['type'];

        // Get settings
        $max_width = isset($this->settings['max_width']) ? intval($this->settings['max_width']) : 1920;
        $max_height = isset($this->settings['max_height']) ? intval($this->settings['max_height']) : 1920;
        $exclusion_suffix = isset($this->settings['exclusion_suffix']) ? $this->settings['exclusion_suffix'] : '-full';

        // Check if file should be excluded based on suffix
        $filename = basename($file_path);
        if (!empty($exclusion_suffix) && strpos($filename, $exclusion_suffix) !== false) {
            return $upload; // Skip resizing
        }

        // Only process image files
        if (!in_array($file_type, ['image/jpeg', 'image/png', 'image/bmp'])) {
            return $upload;
        }

        // Resize the image
        $resized_path = $this->resize_image($file_path, $file_type, $max_width, $max_height);

        if ($resized_path && $resized_path !== $file_path) {
            // Update upload info with resized image
            $upload['file'] = $resized_path;

            // Update MIME type if BMP was converted to JPEG
            if ($file_type === 'image/bmp' && strpos($resized_path, '.jpg') !== false) {
                $upload['type'] = 'image/jpeg';
                $upload['url'] = str_replace('.bmp', '.jpg', $upload['url']);
            }
        }

        return $upload;
    }

    /**
     * Resize image to maximum dimensions
     *
     * @param string $file_path Path to the image file
     * @param string $file_type MIME type of the image
     * @param int $max_width Maximum width
     * @param int $max_height Maximum height
     * @return string|false Path to resized image or original path if no resize needed
     */
    private function resize_image($file_path, $file_type, $max_width, $max_height) {
        if (!function_exists('imagecreatefromjpeg')) {
            return false;
        }

        // Get current dimensions
        $image_info = @getimagesize($file_path);
        if (!$image_info) {
            return false;
        }

        list($width, $height) = $image_info;

        // Check if resize is needed
        if ($width <= $max_width && $height <= $max_height) {
            return $file_path; // No resize needed
        }

        // Calculate new dimensions maintaining aspect ratio
        $ratio = min($max_width / $width, $max_height / $height);
        $new_width = round($width * $ratio);
        $new_height = round($height * $ratio);

        // Create source image
        $source_image = false;
        if ($file_type === 'image/jpeg') {
            $source_image = @imagecreatefromjpeg($file_path);
        } elseif ($file_type === 'image/png') {
            $source_image = @imagecreatefrompng($file_path);
        } elseif ($file_type === 'image/bmp') {
            if (function_exists('imagecreatefrombmp')) {
                $source_image = @imagecreatefrombmp($file_path);
            }
        }

        if (!$source_image) {
            return false;
        }

        // Create new resized image
        $new_image = imagecreatetruecolor($new_width, $new_height);

        // Preserve transparency for PNG
        if ($file_type === 'image/png') {
            imagealphablending($new_image, false);
            imagesavealpha($new_image, true);
            $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
            imagefilledrectangle($new_image, 0, 0, $new_width, $new_height, $transparent);
        }

        // Resize with high quality
        imagecopyresampled($new_image, $source_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        imagedestroy($source_image);

        // Save resized image
        $success = false;
        $quality = 90; // High quality for resize

        if ($file_type === 'image/png') {
            // Check if PNG has transparency
            $has_transparency = $this->png_has_transparency($file_path);

            if ($has_transparency) {
                // Save as PNG to preserve transparency
                $success = @imagepng($new_image, $file_path, 9);
            } else {
                // Convert to JPEG for better compression on non-transparent PNGs
                $filename = basename($file_path);
                $new_filename = preg_replace('/\.png$/i', '.jpg', $filename);
                $jpg_path = dirname($file_path) . '/' . $new_filename;
                $success = @imagejpeg($new_image, $jpg_path, $quality);
                if ($success) {
                    wp_delete_file($file_path); // Delete original PNG
                    $file_path = $jpg_path;
                }
            }
        } elseif ($file_type === 'image/bmp') {
            // Convert BMP to JPEG
            $filename = basename($file_path);
            $new_filename = preg_replace('/\.bmp$/i', '.jpg', $filename);
            $jpg_path = dirname($file_path) . '/' . $new_filename;
            $success = @imagejpeg($new_image, $jpg_path, $quality);
            if ($success) {
                wp_delete_file($file_path); // Delete original BMP
                $file_path = $jpg_path;
            }
        } else {
            // JPEG
            $success = @imagejpeg($new_image, $file_path, $quality);
        }

        imagedestroy($new_image);

        return $success ? $file_path : false;
    }

    /**
     * Check if PNG has transparency
     *
     * @param string $file_path Path to PNG file
     * @return bool
     */
    private function png_has_transparency($file_path) {
        if (!function_exists('imagecreatefrompng')) {
            return true; // Assume transparency if can't check
        }

        $image = @imagecreatefrompng($file_path);
        if (!$image) {
            return true;
        }

        $width = imagesx($image);
        $height = imagesy($image);

        // Check a sample of pixels for transparency
        // Checking every pixel would be too slow for large images
        $step = max(1, min($width, $height) / 10);

        for ($x = 0; $x < $width; $x += $step) {
            for ($y = 0; $y < $height; $y += $step) {
                $rgba = imagecolorat($image, $x, $y);
                $alpha = ($rgba & 0x7F000000) >> 24;
                if ($alpha > 0) {
                    imagedestroy($image);
                    return true;
                }
            }
        }

        imagedestroy($image);
        return false;
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardResizeImagesOnUpload();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
