<?php
/**
 * Name: Disable Thumbnail Generation
 * Description: Prevent WordPress from automatically generating multiple thumbnail sizes when uploading images, saving disk space and speeding up uploads
 * Category: Media
 * Icon: -
 * Added: 2025-12-24
 * Tags: media, thumbnails, images, optimization, disk space, uploads
 * WhereToFind: {
 *   "location": "Switchboard Settings",
 *   "url": "admin.php?page=switchboard",
 *   "instructions": "Find this module in the Media category and click to access settings",
 *   "newTab": false
 * }
 * UseCases: [
 *   {
 *     "title": "Save Disk Space",
 *     "description": "Stop WordPress from creating 5-10 thumbnail versions of every uploaded image, reducing storage usage by 50-80%."
 *   },
 *   {
 *     "title": "Faster Uploads",
 *     "description": "Speed up image uploads significantly by skipping the thumbnail generation process, especially useful for bulk uploads."
 *   },
 *   {
 *     "title": "Custom Theme Control",
 *     "description": "When your theme uses responsive images or CDN-based resizing, disable WordPress thumbnails to avoid redundant processing."
 *   }
 * ]
 */

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

class SwitchboardDisableThumbnails {

    private $option_key = 'switchboard_disable-thumbnails_settings';

    public function __construct() {
        $settings = get_option($this->option_key, []);
        $enabled = isset($settings['enabled']) ? (bool) $settings['enabled'] : true;

        if ($enabled) {
            add_filter('intermediate_image_sizes_advanced', [$this, 'filter_image_sizes'], 10, 3);

            if (!empty($settings['disable_big_image_threshold'])) {
                add_filter('big_image_size_threshold', '__return_false');
            }

            if (!empty($settings['disable_image_scaling'])) {
                add_filter('wp_editor_set_quality', function() { return 100; });
            }
        }

        Switchboard_Data_Registry::get_instance()->auto_register($this, __FILE__);
    }

    public function register_data_locations() {
        return [
            'options' => [$this->option_key],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }

    public function filter_image_sizes($sizes, $metadata = [], $attachment_id = 0) {
        $settings = get_option($this->option_key, []);
        $mode = isset($settings['mode']) ? $settings['mode'] : 'all';

        if ($mode === 'all') {
            return [];
        }

        $disabled_sizes = isset($settings['disabled_sizes']) ? (array) $settings['disabled_sizes'] : [];
        foreach ($disabled_sizes as $size) {
            unset($sizes[$size]);
        }

        return $sizes;
    }

    private function get_all_image_sizes() {
        global $_wp_additional_image_sizes;
        $sizes = [];

        foreach (['thumbnail', 'medium', 'medium_large', 'large'] as $size) {
            $sizes[$size] = [
                'name' => $size,
                'width' => intval(get_option($size . '_size_w')),
                'height' => intval(get_option($size . '_size_h')),
                'crop' => ($size === 'thumbnail') ? (bool) get_option('thumbnail_crop') : false,
                'source' => 'WordPress Core',
            ];
        }

        if (!empty($_wp_additional_image_sizes)) {
            foreach ($_wp_additional_image_sizes as $name => $size) {
                $sizes[$name] = [
                    'name' => $name,
                    'width' => intval($size['width']),
                    'height' => intval($size['height']),
                    'crop' => $size['crop'],
                    'source' => 'Theme/Plugin',
                ];
            }
        }

        return $sizes;
    }

    public function render_settings($settings = []) {
        $enabled = isset($settings['enabled']) ? (bool) $settings['enabled'] : true;
        $mode = isset($settings['mode']) ? $settings['mode'] : 'all';
        $disabled_sizes = isset($settings['disabled_sizes']) ? (array) $settings['disabled_sizes'] : [];
        $disable_big_image_threshold = !empty($settings['disable_big_image_threshold']);
        $disable_image_scaling = !empty($settings['disable_image_scaling']);
        $all_sizes = $this->get_all_image_sizes();
        ?>
        <style>
            .sb-disable-thumbnails .sb-mode-selector { display: flex; gap: 8px; margin-bottom: 16px; }
            .sb-disable-thumbnails .sb-mode-option { flex: 1; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 8px; cursor: pointer; transition: all 0.2s ease; text-align: center; background: #fff; }
            .sb-disable-thumbnails .sb-mode-option:hover { border-color: #2271b1; }
            .sb-disable-thumbnails .sb-mode-option.active { border-color: #2271b1; background: #eff6ff; }
            .sb-disable-thumbnails .sb-mode-option input { display: none; }
            .sb-disable-thumbnails .sb-mode-option .sb-mode-title { font-size: 13px; font-weight: 600; margin-bottom: 4px; }
            .sb-disable-thumbnails .sb-mode-option .sb-mode-desc { font-size: 11px; color: #6b7280; }
            .sb-disable-thumbnails .sb-sizes-list { border: 1px solid #e5e7eb; border-radius: 6px; max-height: 300px; overflow-y: auto; background: #fff; }
            .sb-disable-thumbnails .sb-size-item { display: flex; align-items: center; gap: 12px; padding: 12px; border-bottom: 1px solid #f3f4f6; }
            .sb-disable-thumbnails .sb-size-item:last-child { border-bottom: none; }
            .sb-disable-thumbnails .sb-size-item input[type="checkbox"] { margin: 0; width: 16px; height: 16px; }
            .sb-disable-thumbnails .sb-size-item .sb-size-info { flex: 1; }
            .sb-disable-thumbnails .sb-size-item .sb-size-name { font-size: 13px; font-weight: 500; }
            .sb-disable-thumbnails .sb-size-item .sb-size-dimensions { font-size: 11px; color: #6b7280; }
            .sb-disable-thumbnails .sb-size-item .sb-size-source { font-size: 10px; color: #9ca3af; background: #f3f4f6; padding: 2px 6px; border-radius: 4px; }
            .sb-disable-thumbnails .sb-select-actions { display: flex; gap: 8px; margin-bottom: 8px; }
            .sb-disable-thumbnails .sb-select-actions button { padding: 4px 8px; font-size: 11px; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 4px; cursor: pointer; }
            .sb-disable-thumbnails .sb-select-actions button:hover { background: #e5e7eb; }
        </style>

        <div class="sb-disable-thumbnails">
            <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-bottom: 24px;">
                <h4 class="sb-sp-heading-sm">Disable Thumbnail Generation</h4>
                <p class="sb-sp-description" style="margin: 0;">Prevent WordPress from automatically generating multiple thumbnail sizes when uploading images, saving disk space and speeding up uploads.</p>
            </div>

            <div class="sb-sp-group" style="margin-bottom: 24px;">
                <div class="sb-module-option-item sb-module-toggle-item">
                    <div class="sb-module-option-content">
                        <div class="sb-module-toggle-header">
                            <strong class="sb-module-option-title">Enable Thumbnail Blocking</strong>
                            <label class="sb-module-toggle">
                                <input type="checkbox" name="enabled" value="1" <?php checked($enabled); ?>>
                                <span class="sb-module-toggle-slider"></span>
                            </label>
                        </div>
                        <p class="sb-module-option-text">When enabled, WordPress will skip thumbnail generation based on your settings below.</p>
                    </div>
                </div>
            </div>

            <div id="thumbnail-options" style="<?php echo $enabled ? '' : 'opacity: 0.5; pointer-events: none;'; ?>">
                <div class="sb-sp-group" style="margin-bottom: 24px;">
                    <h3 class="sb-sp-heading">Disable Mode</h3>
                    <p class="sb-sp-description" style="margin-bottom: 16px;">Choose whether to disable all thumbnails or select specific sizes.</p>
                    <div class="sb-mode-selector">
                        <label class="sb-mode-option <?php echo $mode === 'all' ? 'active' : ''; ?>">
                            <input type="radio" name="mode" value="all" <?php checked($mode, 'all'); ?>>
                            <div class="sb-mode-title">Disable All</div>
                            <div class="sb-mode-desc">Stop all thumbnail generation</div>
                        </label>
                        <label class="sb-mode-option <?php echo $mode === 'selected' ? 'active' : ''; ?>">
                            <input type="radio" name="mode" value="selected" <?php checked($mode, 'selected'); ?>>
                            <div class="sb-mode-title">Select Sizes</div>
                            <div class="sb-mode-desc">Choose which sizes to disable</div>
                        </label>
                    </div>
                </div>

                <div class="sb-sp-group" id="size-selection" style="margin-bottom: 24px; <?php echo $mode === 'selected' ? '' : 'display: none;'; ?>">
                    <h3 class="sb-sp-heading">Select Sizes to Disable</h3>
                    <p class="sb-sp-description" style="margin-bottom: 16px;">Check the image sizes you want to prevent WordPress from generating.</p>
                    <div class="sb-select-actions">
                        <button type="button" id="select-all-sizes">Select All</button>
                        <button type="button" id="deselect-all-sizes">Deselect All</button>
                    </div>
                    <div class="sb-sizes-list">
                        <?php foreach ($all_sizes as $size_name => $size_info):
                            $is_disabled = in_array($size_name, $disabled_sizes);
                            $dimensions = $size_info['width'] . ' × ' . $size_info['height'];
                            if ($size_info['crop']) $dimensions .= ' (cropped)';
                        ?>
                        <div class="sb-size-item">
                            <input type="checkbox" name="disabled_sizes[]" value="<?php echo esc_attr($size_name); ?>" id="size-<?php echo esc_attr($size_name); ?>" <?php checked($is_disabled); ?>>
                            <div class="sb-size-info">
                                <div class="sb-size-name"><?php echo esc_html($size_name); ?></div>
                                <div class="sb-size-dimensions"><?php echo esc_html($dimensions); ?></div>
                            </div>
                            <span class="sb-size-source"><?php echo esc_html($size_info['source']); ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

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

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

                    <div class="sb-module-option-item sb-module-toggle-item" style="margin-bottom: 16px;">
                        <div class="sb-module-option-content">
                            <div class="sb-module-toggle-header">
                                <strong class="sb-module-option-title">Disable Big Image Threshold</strong>
                                <label class="sb-module-toggle">
                                    <input type="checkbox" name="disable_big_image_threshold" value="1" <?php checked($disable_big_image_threshold); ?>>
                                    <span class="sb-module-toggle-slider"></span>
                                </label>
                            </div>
                            <p class="sb-module-option-text">WordPress 5.3+ automatically scales images larger than 2560px. Enable this to keep original dimensions.</p>
                        </div>
                    </div>

                    <div class="sb-module-option-item sb-module-toggle-item">
                        <div class="sb-module-option-content">
                            <div class="sb-module-toggle-header">
                                <strong class="sb-module-option-title">Preserve Original Quality</strong>
                                <label class="sb-module-toggle">
                                    <input type="checkbox" name="disable_image_scaling" value="1" <?php checked($disable_image_scaling); ?>>
                                    <span class="sb-module-toggle-slider"></span>
                                </label>
                            </div>
                            <p class="sb-module-option-text">Prevent WordPress from reducing image quality during processing (keeps 100% quality).</p>
                        </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">This setting only affects <strong>new image uploads</strong></li>
                        <li class="sb-sp-list-item">Existing thumbnails will remain on your server</li>
                        <li class="sb-sp-list-item">To remove existing thumbnails, use a plugin like "Force Regenerate Thumbnails"</li>
                    </ul>
                </div>
            </div>
        </div>

        <script>
        jQuery(document).ready(function($) {
            $('input[name="enabled"]').on('change', function() {
                $('#thumbnail-options').css($(this).is(':checked') ? {opacity: 1, pointerEvents: 'auto'} : {opacity: 0.5, pointerEvents: 'none'});
            });
            $('.sb-mode-option').on('click', function() {
                $('.sb-mode-option').removeClass('active');
                $(this).addClass('active');
                $('#size-selection')[$(this).find('input').val() === 'selected' ? 'slideDown' : 'slideUp']();
            });
            $('#select-all-sizes').on('click', function() { $('.sb-sizes-list input[type="checkbox"]').prop('checked', true); });
            $('#deselect-all-sizes').on('click', function() { $('.sb-sizes-list input[type="checkbox"]').prop('checked', false); });
        });
        </script>
        <?php
    }
}

$switchboard_instance = new SwitchboardDisableThumbnails();
