<?php
/**
 * Name: Image Sizes Panel
 * Description: Show all available image sizes with one-click copy URL buttons in media modal for easy access to thumbnail, medium, large versions without file manager
 * Category: Media
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Quick URL Access for Emails",
 *     "description": "Copy specific image size URLs from Media Library to insert in email newsletters without manually finding files in uploads folder."
 *   },
 *   {
 *     "title": "Development Testing",
 *     "description": "Verify that custom 450x300 'hero' size is generating correctly after adding new image dimensions to functions.php."
 *   },
 *   {
 *     "title": "Client Asset Delivery",
 *     "description": "Provide clients with direct URLs to specific image sizes (thumbnail, medium, large) without teaching them server file structure."
 *   }
 * ]
 * Added: 2025-09-05
 * Tags: images, sizes, media, thumbnails, urls
 * WhereToFind: {
 *   "location": "Media Library (Edit Image)",
 *   "url": "upload.php",
 *   "instructions": "Edit any image to see 'Image Sizes' panel with copy URL buttons",
 *   "newTab": false
 * }
 */

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

class SwitchboardImageSizesPanel {

    public function __construct() {
        // Add meta box in attachment editor sidebar
        add_action('add_meta_boxes_attachment', [$this, 'add_image_sizes_meta_box']);

        // Add quick action button in Media Library list/grid view
        add_filter('media_row_actions', [$this, 'add_media_row_action'], 10, 2);
        add_action('admin_footer', [$this, 'add_popover_styles_and_scripts']);

        // AJAX handler for loading image sizes
        add_action('wp_ajax_switchboard_get_image_sizes', [$this, 'ajax_get_image_sizes']);

        // Keep the modal field for backward compatibility (can be removed if not needed)
        add_filter('attachment_fields_to_edit', [$this, 'add_image_sizes_field'], 10, 2);
    }

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

    /**
     * Add meta box in attachment editor sidebar
     */
    public function add_image_sizes_meta_box() {
        add_meta_box(
            'switchboard-image-sizes',
            __('Available Image Sizes', 'wpswitchboard') . ' <span class="switchboard-badge">SWITCHBOARD</span>',
            [$this, 'render_meta_box'],
            'attachment',
            'side',
            'default'
        );
    }

    /**
     * Render meta box content
     */
    public function render_meta_box($post) {
        if (!wp_attachment_is_image($post->ID)) {
            echo '<p class="sb-sp-not-image-text">' . esc_html__('This attachment is not an image.', 'wpswitchboard') . '</p>';
            return;
        }

        $sizes = get_intermediate_image_sizes();
        $sizes[] = 'full';

        echo '<div class="sb-sp-image-sizes-metabox">';

        foreach ($sizes as $size) {
            $image = wp_get_attachment_image_src($post->ID, $size);
            if ($image) {
                $url = $image[0];
                $width = $image[1];
                $height = $image[2];
                $size_name = ucfirst(str_replace(['_', '-'], ' ', $size));

                echo '<div class="sb-sp-size-item">';
                echo '<div class="sb-sp-size-header">';
                echo '<strong class="sb-sp-size-name">' . esc_html($size_name) . '</strong>';
                echo '<span class="sb-sp-size-dimensions">(' . esc_html($width) . 'x' . esc_html($height) . ')</span>';
                echo '</div>';
                echo '<div class="sb-sp-size-url-wrapper">';
                echo '<input type="text" readonly value="' . esc_url($url) . '" class="sb-sp-size-url-input switchboard-size-url">';
                echo '<button type="button" class="button button-small sb-sp-size-copy-btn switchboard-copy-url-btn" data-url="' . esc_url($url) . '">' . esc_html__('Copy', 'wpswitchboard') . '</button>';
                echo '</div>';
                echo '</div>';
            }
        }

        echo '</div>';

        // Add copy functionality
        ?>
        <script>
        jQuery(document).ready(function($) {
            $('.switchboard-copy-url-btn').on('click', function(e) {
                e.preventDefault();
                var url = $(this).data('url');
                var $btn = $(this);
                var originalText = $btn.text();

                // Copy to clipboard
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(url).then(function() {
                        $btn.text('Copied!').css('color', 'var(--primary-600)');
                        setTimeout(function() {
                            $btn.text(originalText).css('color', '');
                        }, 2000);
                    });
                } else {
                    // Fallback for older browsers
                    var $input = $btn.siblings('input');
                    $input.select();
                    document.execCommand('copy');
                    $btn.text('Copied!').css('color', 'var(--primary-600)');
                    setTimeout(function() {
                        $btn.text(originalText).css('color', '');
                    }, 2000);
                }
            });
        });
        </script>
        <?php
    }

    public function add_image_sizes_field($fields, $post) {
        if (!wp_attachment_is_image($post->ID)) {
            return $fields;
        }

        $sizes = get_intermediate_image_sizes();
        $sizes[] = 'full';

        if (!is_array($sizes)) {
            $sizes = [];
        }

        $html = '<div class="image-sizes-panel">';
        $html .= '<strong>Available Sizes:</strong><br>';

        foreach ($sizes as $size) {
            $image = wp_get_attachment_image_src($post->ID, $size);
            if ($image) {
                $url = $image[0];
                $width = $image[1];
                $height = $image[2];

                $html .= '<div class="sb-sp-size-item">';
                $html .= '<strong>' . esc_html(ucfirst($size)) . '</strong> (' . esc_html($width) . 'x' . esc_html($height) . ')<br>';
                $html .= '<input type="text" readonly value="' . esc_url($url) . '" class="sb-sp-size-url-input" onclick="this.select();">';
                $html .= '</div>';
            }
        }

        $html .= '</div>';

        $fields['switchboard_image_sizes'] = [
            'label' => __('Image Sizes', 'wpswitchboard') . ' <span class="switchboard-badge">SWITCHBOARD</span>',
            'input' => 'html',
            'html' => $html,
        ];

        return $fields;
    }

    /**
     * Add quick action button in Media Library list view
     */
    public function add_media_row_action($actions, $post) {
        if (!wp_attachment_is_image($post->ID)) {
            return $actions;
        }

        $actions['switchboard_sizes'] = '<a href="#" class="switchboard-show-sizes" data-attachment-id="' . $post->ID . '">' . esc_html__('Image Sizes', 'wpswitchboard') . '</a>';

        return $actions;
    }

    /**
     * Add popover styles and scripts
     */
    public function add_popover_styles_and_scripts() {
        $screen = get_current_screen();
        if (!$screen || $screen->base !== 'upload') {
            return;
        }
        ?>
        <style>
        .switchboard-sizes-popover {
            display: none;
            position: fixed;
            background: white;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
            z-index: 999999;
            max-width: 450px;
            max-height: 500px;
            overflow: hidden;
        }
        .switchboard-sizes-popover-header {
            padding: 12px 16px;
            border-bottom: 1px solid #e5e7eb;
            background: #f9fafb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .switchboard-sizes-popover-header h3 {
            margin: 0;
            font-size: 14px;
            font-weight: 600;
            color: #374151;
        }
        .switchboard-sizes-popover-close {
            background: none;
            border: none;
            font-size: 20px;
            color: #6b7280;
            cursor: pointer;
            padding: 0;
            line-height: 1;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
        }
        .switchboard-sizes-popover-close:hover {
            background: #e5e7eb;
            color: #374151;
        }
        .switchboard-sizes-popover-body {
            padding: 12px;
            max-height: 400px;
            overflow-y: auto;
        }
        .switchboard-size-item {
            margin-bottom: 10px;
            padding: 10px;
            background: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 4px;
        }
        .switchboard-size-item:last-child {
            margin-bottom: 0;
        }
        .switchboard-size-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 6px;
        }
        .switchboard-size-name {
            font-size: 12px;
            font-weight: 600;
            color: #374151;
        }
        .switchboard-size-dimensions {
            font-size: 11px;
            color: #6b7280;
        }
        .switchboard-size-url-wrapper {
            position: relative;
        }
        .switchboard-size-url-input {
            width: 100%;
            padding: 6px 60px 6px 8px;
            font-size: 11px;
            font-family: monospace;
            background: white;
            border: 1px solid #d1d5db;
            border-radius: 3px;
            color: #374151;
        }
        .switchboard-popover-copy-btn {
            position: absolute;
            right: 4px;
            top: 4px;
            padding: 2px 8px;
            font-size: 11px;
            height: auto;
            line-height: 1.4;
            background: var(--primary-500);
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        .switchboard-popover-copy-btn:hover {
            background: var(--primary-600);
        }
        .switchboard-popover-copy-btn.copied {
            background: var(--primary-600);
        }
        </style>

        <div id="switchboard-sizes-popover" class="switchboard-sizes-popover">
            <div class="switchboard-sizes-popover-header">
                <h3><?php echo esc_html__('Available Image Sizes', 'wpswitchboard'); ?></h3>
                <button type="button" class="switchboard-sizes-popover-close">&times;</button>
            </div>
            <div class="switchboard-sizes-popover-body" id="switchboard-sizes-popover-content">
                <!-- Content will be loaded dynamically -->
            </div>
        </div>

        <script>
        jQuery(document).ready(function($) {
            var $popover = $('#switchboard-sizes-popover');
            var $popoverContent = $('#switchboard-sizes-popover-content');

            // Show popover on click
            $(document).on('click', '.switchboard-show-sizes', function(e) {
                e.preventDefault();
                var attachmentId = $(this).data('attachment-id');
                var $link = $(this);

                // Position popover near the clicked link
                var offset = $link.offset();
                var linkHeight = $link.outerHeight();

                $popover.css({
                    top: offset.top + linkHeight + 5,
                    left: Math.min(offset.left, $(window).width() - 470)
                }).fadeIn(200);

                // Load sizes via AJAX
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_get_image_sizes',
                        attachment_id: attachmentId,
                        nonce: '<?php echo esc_attr(wp_create_nonce('switchboard_image_sizes')); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            $popoverContent.html(response.data.html);
                        } else {
                            $popoverContent.html('<p class="sb-sp-error-text"><?php echo esc_js(__('Failed to load image sizes.', 'wpswitchboard')); ?></p>');
                        }
                    },
                    error: function() {
                        $popoverContent.html('<p class="sb-sp-error-text"><?php echo esc_js(__('Error loading image sizes.', 'wpswitchboard')); ?></p>');
                    }
                });
            });

            // Close popover
            $('.switchboard-sizes-popover-close').on('click', function() {
                $popover.fadeOut(200);
            });

            // Close on outside click
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.switchboard-sizes-popover, .switchboard-show-sizes').length) {
                    $popover.fadeOut(200);
                }
            });

            // Close on escape key
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape') {
                    $popover.fadeOut(200);
                }
            });

            // Copy URL button
            $(document).on('click', '.switchboard-popover-copy-btn', function(e) {
                e.preventDefault();
                var url = $(this).data('url');
                var $btn = $(this);
                var originalText = $btn.text();

                if (navigator.clipboard) {
                    navigator.clipboard.writeText(url).then(function() {
                        $btn.text('Copied!').addClass('copied');
                        setTimeout(function() {
                            $btn.text(originalText).removeClass('copied');
                        }, 2000);
                    });
                } else {
                    var $input = $btn.siblings('.switchboard-size-url-input');
                    $input.select();
                    document.execCommand('copy');
                    $btn.text('Copied!').addClass('copied');
                    setTimeout(function() {
                        $btn.text(originalText).removeClass('copied');
                    }, 2000);
                }
            });
        });
        </script>
        <?php
    }

    /**
     * AJAX handler to get image sizes
     */
    public function ajax_get_image_sizes() {
        check_ajax_referer('switchboard_image_sizes', 'nonce');

        if (!current_user_can('upload_files')) {
            wp_send_json_error(['message' => __('Unauthorized', 'wpswitchboard')]);
        }

        $attachment_id = isset($_POST['attachment_id']) ? intval($_POST['attachment_id']) : 0;

        if (!$attachment_id || !wp_attachment_is_image($attachment_id)) {
            wp_send_json_error(['message' => __('Invalid attachment', 'wpswitchboard')]);
        }

        $sizes = get_intermediate_image_sizes();
        $sizes[] = 'full';

        $html = '';

        foreach ($sizes as $size) {
            $image = wp_get_attachment_image_src($attachment_id, $size);
            if ($image) {
                $url = $image[0];
                $width = $image[1];
                $height = $image[2];
                $size_name = ucfirst(str_replace(['_', '-'], ' ', $size));

                $html .= '<div class="switchboard-size-item">';
                $html .= '<div class="switchboard-size-header">';
                $html .= '<span class="switchboard-size-name">' . esc_html($size_name) . '</span>';
                $html .= '<span class="switchboard-size-dimensions">(' . esc_html($width) . 'x' . esc_html($height) . ')</span>';
                $html .= '</div>';
                $html .= '<div class="switchboard-size-url-wrapper">';
                $html .= '<input type="text" readonly value="' . esc_url($url) . '" class="switchboard-size-url-input">';
                $html .= '<button type="button" class="switchboard-popover-copy-btn" data-url="' . esc_url($url) . '">' . esc_html__('Copy', 'wpswitchboard') . '</button>';
                $html .= '</div>';
                $html .= '</div>';
            }
        }

        wp_send_json_success(['html' => $html]);
    }
}

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