<?php
/**
 * Name: Default Featured Image
 * Description: Set default fallback featured image for posts without one across blog archives, category pages, social sharing, and anywhere featured images display automatically
 * Category: Media
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Consistent Blog Archives",
 *     "description": "Set branded placeholder for 200+ old blog posts missing featured images so archive pages don't show broken image gaps."
 *   },
 *   {
 *     "title": "Social Share Fallback",
 *     "description": "Ensure Facebook and Twitter show your logo when posts without featured images are shared instead of blank or random images."
 *   },
 *   {
 *     "title": "Legacy Content Fixes",
 *     "description": "Apply default featured image to imported posts from old CMS that didn't have featured image system, avoiding manual assignment."
 *   }
 * ]
 * Added: 2025-07-12
 * Tags: featured-image, default, thumbnail, media
 * WhereToFind: {
 *   "location": "Configure in module settings",
 *   "url": "",
 *   "instructions": "Select default image - appears on posts without featured images",
 *   "newTab": false
 * }
 */

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

class SwitchboardDefaultFeaturedImage {

    public function __construct() {
        add_filter('post_thumbnail_html', [$this, 'default_featured_image'], 10, 5);
        add_filter('has_post_thumbnail', [$this, 'has_default_thumbnail'], 10, 2);
    }

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

    /**
     * Render settings panel for Default Featured Image
     * 
     * Displays settings interface for configuring a fallback featured image with:
     * - Image preview showing current default image or placeholder
     * - WordPress media uploader integration for selecting/changing image
     * - Remove button to clear the default image
     * - Informational panels explaining how the feature works
     * - Tips for optimal image dimensions and usage
     * 
     * The interface uses WordPress's built-in media uploader (wp.media) for a native
     * experience. When an image is selected, it updates the preview immediately using
     * jQuery. The module applies the default image automatically to any posts without
     * their own featured images across blog listings, archives, category pages, and
     * social sharing contexts. This is especially useful for sites with legacy content
     * or imported posts that lack featured images, providing visual consistency.
     * 
     * @param array $settings Current module settings with 'image_id' key containing attachment ID
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        // Get image ID from module settings
        $image_id = isset($settings['image_id']) ? intval($settings['image_id']) : 0;
        $image_url = $image_id ? wp_get_attachment_url($image_id) : '';
        
        $html = '
            <input type="hidden" name="module" value="default-featured-image">

            <div class="sb-sp-group">
                <h3 class="sb-sp-heading">' . esc_html__('Default Featured Image', 'wpswitchboard') . '</h3>
                <p class="sb-sp-description">' . esc_html__('Set a fallback image that will be displayed for posts/pages that don\'t have a featured image.', 'wpswitchboard') . '</p>
                <p class="sb-sp-description">' . esc_html__('This image will appear in blog listings, archives, and anywhere featured images are displayed.', 'wpswitchboard') . '</p>
            </div>

            <div class="sb-sp-group">
                <h3 class="sb-sp-heading">' . esc_html__('Current Default Image', 'wpswitchboard') . '</h3>

                <div id="default-featured-image-preview" class="sb-sp-card">
                    ' . ($image_url ?
                        '<img src="' . esc_url($image_url) . '" style="max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">' :
                        '<div style="padding: 40px; text-align: center;"><span class="dashicons dashicons-format-image" style="font-size: 64px; width: 64px; height: 64px; opacity: 0.3; color: #94a3b8;"></span><p class="sb-sp-description" style="margin-top: 16px;"><em>' . esc_html__('No default image set', 'wpswitchboard') . '</em></p></div>'
                    ) . '
                </div>

                <input type="hidden" id="default_featured_image_id" name="setting_image_id" value="' . esc_attr($image_id) . '">

                <div class="sb-sp-button-group">
                    <button type="button" class="button button-primary button-large" id="upload-default-featured-image">
                        <span class="dashicons dashicons-upload"></span> ' . ($image_url ? esc_html__('Change Image', 'wpswitchboard') : esc_html__('Select Image', 'wpswitchboard')) . '
                    </button>
                    ' . ($image_url ? '<button type="button" class="button button-large" id="remove-default-featured-image">' . esc_html__('Remove Image', 'wpswitchboard') . '</button>' : '') . '
                </div>
            </div>

            <div class="sb-sp-info-box sb-sp-info-box-info">
                <h4 class="sb-sp-heading-sm">' . esc_html__('How It Works', 'wpswitchboard') . '</h4>
                <ul class="sb-sp-list">
                    <li class="sb-sp-list-item">' .
                    // translators: %1$s and %2$s are HTML bold tags wrapping the word "with"
                    sprintf(esc_html__('Posts %1$swith%2$s featured images → Show their own image', 'wpswitchboard'), '<strong>', '</strong>') . '</li>
                    <li class="sb-sp-list-item">' .
                    // translators: %1$s and %2$s are HTML bold tags wrapping the word "without"
                    sprintf(esc_html__('Posts %1$swithout%2$s featured images → Show this default image', 'wpswitchboard'), '<strong>', '</strong>') . '</li>
                    <li class="sb-sp-list-item">' . esc_html__('Works in blog listings, archives, category pages, etc.', 'wpswitchboard') . '</li>
                    <li class="sb-sp-list-item">' . esc_html__('Changes apply immediately to all posts without featured images', 'wpswitchboard') . '</li>
                </ul>
            </div>

            <div class="sb-sp-info-box sb-sp-info-box-tip">
                <h4 class="sb-sp-heading-sm">' . esc_html__('Tips', 'wpswitchboard') . '</h4>
                <ul class="sb-sp-list">
                    <li class="sb-sp-list-item"><strong>' . esc_html__('Size:', 'wpswitchboard') . '</strong> ' . esc_html__('Use an image that matches your theme\'s featured image size (usually 1200×630px)', 'wpswitchboard') . '</li>
                    <li class="sb-sp-list-item"><strong>' . esc_html__('Design:', 'wpswitchboard') . '</strong> ' . esc_html__('Choose a neutral, generic image that works with any content', 'wpswitchboard') . '</li>
                    <li class="sb-sp-list-item"><strong>' . esc_html__('Branding:', 'wpswitchboard') . '</strong> ' . esc_html__('Consider adding your logo or brand colors', 'wpswitchboard') . '</li>
                    <li class="sb-sp-list-item"><strong>' . esc_html__('Quality:', 'wpswitchboard') . '</strong> ' . esc_html__('Use a high-resolution image for best results', 'wpswitchboard') . '</li>
                </ul>
            </div>
            
            <script>
            jQuery(document).ready(function($) {
                var mediaUploader;
                
                $("#upload-default-featured-image").on("click", function(e) {
                    e.preventDefault();
                    
                    if (mediaUploader) {
                        mediaUploader.open();
                        return;
                    }
                    
                    mediaUploader = wp.media({
                        title: "Select Default Featured Image",
                        button: {
                            text: "Use this image"
                        },
                        multiple: false
                    });
                    
                    mediaUploader.on("select", function() {
                        var attachment = mediaUploader.state().get("selection").first().toJSON();
                        $("#default_featured_image_id").val(attachment.id);
                        $("#default-featured-image-preview").html("<img src=\"" + attachment.url + "\" style=\"max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);\">");
                        $("#upload-default-featured-image").html("<span class=\"dashicons dashicons-upload\"></span> Change Image");

                        if ($("#remove-default-featured-image").length === 0) {
                            $("#upload-default-featured-image").after(" <button type=\"button\" class=\"button button-large\" id=\"remove-default-featured-image\">Remove Image</button>");
                        }
                    });
                    
                    mediaUploader.open();
                });
                
                $(document).on("click", "#remove-default-featured-image", function(e) {
                    e.preventDefault();

                    if (!confirm("Remove the default featured image?")) {
                        return;
                    }

                    $("#default_featured_image_id").val("");
                    $("#default-featured-image-preview").html("<div style=\"padding: 40px; text-align: center;\"><span class=\"dashicons dashicons-format-image\" style=\"font-size: 64px; width: 64px; height: 64px; opacity: 0.3; color: #94a3b8;\"></span><p class=\"sb-sp-description\" style=\"margin-top: 16px;\"><em>No default image set</em></p></div>");
                    $("#upload-default-featured-image").html("<span class=\"dashicons dashicons-upload\"></span> Select Image");
                    $(this).remove();
                });
            });
            </script>
        ';
        
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is built safely with proper escaping throughout
        echo $html;
    }

    public function has_default_thumbnail($has_thumbnail, $post) {
        // If post already has thumbnail, return true
        if ($has_thumbnail) {
            return true;
        }

        // Check if we have a default image configured
        $settings = get_option('switchboard_default-featured-image_settings', []);
        $default_image_id = isset($settings['image_id']) ? intval($settings['image_id']) : 0;

        // If we have a default image, pretend this post has a thumbnail
        return !empty($default_image_id);
    }

    public function default_featured_image($html, $post_id, $post_thumbnail_id, $size, $attr) {
        // If post already has a featured image, return it
        if (!empty($html)) {
            return $html;
        }

        // Only apply default to posts without featured images
        if (!empty($post_thumbnail_id)) {
            return $html;
        }

        // Get image ID from module settings
        $settings = get_option('switchboard_default-featured-image_settings', []);
        $default_image_id = isset($settings['image_id']) ? intval($settings['image_id']) : 0;

        if (empty($default_image_id)) {
            return $html;
        }

        // Generate image HTML with same parameters
        return wp_get_attachment_image($default_image_id, $size, false, $attr);
    }
}

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