<?php
/**
 * Name: Default OG Image
 * Description: Set fallback Open Graph image for social sharing on Facebook, Twitter, and LinkedIn when posts lack featured images to ensure consistent branded previews
 * Category: Content
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Social Share Fallback",
 *     "description": "Set company logo as default Open Graph image so posts without featured images still show branded image when shared on Facebook."
 *   },
 *   {
 *     "title": "Page Sharing",
 *     "description": "Provide fallback OG image for pages and archives that don't have featured images but get shared on social media."
 *   },
 *   {
 *     "title": "Brand Consistency",
 *     "description": "Ensure all social shares include at least your brand image rather than showing broken image or random content."
 *   }
 * ]
 * Added: 2025-08-01
 * Tags: og-image, social, facebook, twitter, seo, sharing
 * WhereToFind: {
 *   "location": "Configure in module settings",
 *   "url": "",
 *   "instructions": "Meta tags appear in page source automatically",
 *   "newTab": false
 * }
 */

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

class SwitchboardDefaultOgImage {
    
    public function __construct() {
        add_action('wp_head', [$this, 'add_og_image']);
        
        // 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__);
        }
    }
    
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_default-og-image_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'transients' => []
        ];
    }
    
    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) : '';
        ?>
        <input type="hidden" name="module" value="default-og-image">

        <div class="sb-sp-group">
            <label class="sb-sp-label"><?php esc_html_e('Default Open Graph Image', 'wpswitchboard'); ?></label>
            <p class="sb-sp-description"><?php esc_html_e('Set a default image for social media sharing (Facebook, Twitter, LinkedIn, etc.). This image will be used when posts/pages don\'t have a featured image.', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <label class="sb-sp-label"><?php esc_html_e('Current Image', 'wpswitchboard'); ?></label>

            <div id="default-og-image-preview" class="sb-sp-upload-preview" style="margin-bottom: 16px;">
                <?php if ($image_url): ?>
                    <img src="<?php echo esc_url($image_url); ?>" class="sb-sp-upload-image" alt="<?php esc_attr_e('Default OG Image', 'wpswitchboard'); ?>">
                <?php else: ?>
                    <div style="text-align: center; background: #f9fafb; border: 2px dashed #e5e7eb; border-radius: 8px; padding: 40px;">
                        <span class="dashicons dashicons-format-image" style="font-size: 48px; color: #cbd5e1; width: 48px; height: 48px;"></span>
                        <p style="color: #64748b; font-size: 13px; margin: 8px 0 0 0;"><?php esc_html_e('No image selected', 'wpswitchboard'); ?></p>
                    </div>
                <?php endif; ?>
            </div>

            <input type="hidden" id="default_og_image_id" name="setting_image_id" value="<?php echo esc_attr($image_id); ?>">

            <div class="sb-sp-button-group">
                <button type="button" class="button button-primary button-small" id="upload-default-og-image">
                    <span class="dashicons dashicons-upload" style="margin-top: 3px;"></span> <?php echo $image_url ? esc_html__('Change Image', 'wpswitchboard') : esc_html__('Select Image', 'wpswitchboard'); ?>
                </button>
                <?php if ($image_url): ?>
                    <button type="button" class="button button-small" id="remove-default-og-image" style="color: #dc2626;"><?php esc_html_e('Remove Image', 'wpswitchboard'); ?></button>
                <?php endif; ?>
            </div>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-info">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('How It Works', 'wpswitchboard'); ?></h4>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item"><?php esc_html_e('Posts/pages with featured images → Use their own featured image', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('Posts/pages without featured images → Use this default OG image', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('Appears when content is shared on Facebook, Twitter, LinkedIn, etc.', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('Changes apply immediately to all content without featured images', 'wpswitchboard'); ?></li>
            </ul>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-tip">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Image Guidelines', 'wpswitchboard'); ?></h4>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Recommended Size:', 'wpswitchboard'); ?></strong> <?php esc_html_e('1200×630px (optimal for Facebook & Twitter)', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Minimum Size:', 'wpswitchboard'); ?></strong> <?php esc_html_e('600×315px (required by Facebook)', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Format:', 'wpswitchboard'); ?></strong> <?php esc_html_e('JPG or PNG (avoid transparency issues with JPG)', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('File Size:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Keep under 1MB for faster loading', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Content:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Include your logo, brand colors, or a generic site image', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Text:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Avoid too much text, as it may be hard to read when scaled down', 'wpswitchboard'); ?></li>
            </ul>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-success">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Verification Tools', 'wpswitchboard'); ?></h4>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item"><strong><?php esc_html_e('View Page Source:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Right-click page → View Source → Search for "og:image"', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Facebook Debugger:', 'wpswitchboard'); ?></strong> <a href="https://developers.facebook.com/tools/debug/" target="_blank">developers.facebook.com/tools/debug/</a></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Twitter Card Validator:', 'wpswitchboard'); ?></strong> <a href="https://cards-dev.twitter.com/validator" target="_blank">cards-dev.twitter.com/validator</a></li>
            </ul>
        </div>

        <?php
        $i18n = [
            'selectTitle' => __('Select Default OG Image', 'wpswitchboard'),
            'useThisImage' => __('Use this image', 'wpswitchboard'),
            'changeImage' => __('Change Image', 'wpswitchboard'),
            'removeImage' => __('Remove Image', 'wpswitchboard'),
            'selectImage' => __('Select Image', 'wpswitchboard'),
            'confirmRemove' => __('Remove the default OG image?', 'wpswitchboard'),
            'noImageSet' => __('No OG image set', 'wpswitchboard')
        ];
        ?>
        <script>
        jQuery(document).ready(function($) {
            const i18n = <?php echo json_encode($i18n); ?>;
            var mediaUploader;

            $("#upload-default-og-image").on("click", function(e) {
                e.preventDefault();

                if (mediaUploader) {
                    mediaUploader.open();
                    return;
                }

                mediaUploader = wp.media({
                    title: i18n.selectTitle,
                    button: {
                        text: i18n.useThisImage
                    },
                    multiple: false
                });

                mediaUploader.on("select", function() {
                    var attachment = mediaUploader.state().get("selection").first().toJSON();
                    $("#default_og_image_id").val(attachment.id);
                    $("#default-og-image-preview").html("<img src=\"" + attachment.url + "\" class=\"sb-sp-upload-image\" alt=\"Default OG Image\">");
                    $("#upload-default-og-image").html("<span class=\"dashicons dashicons-upload\" style=\"margin-top: 3px;\"></span> " + i18n.changeImage);

                    if ($("#remove-default-og-image").length === 0) {
                        $("#upload-default-og-image").after(" <button type=\"button\" class=\"button button-small\" id=\"remove-default-og-image\" style=\"color: #dc2626;\">" + i18n.removeImage + "</button>");
                    }
                });

                mediaUploader.open();
            });

            $(document).on("click", "#remove-default-og-image", function(e) {
                e.preventDefault();

                if (!confirm(i18n.confirmRemove)) {
                    return;
                }

                $("#default_og_image_id").val("");
                $("#default-og-image-preview").html("<div style=\"text-align: center; background: #f9fafb; border: 2px dashed #e5e7eb; border-radius: 8px; padding: 40px;\"><span class=\"dashicons dashicons-format-image\" style=\"font-size: 48px; color: #cbd5e1; width: 48px; height: 48px;\"></span><p style=\"color: #64748b; font-size: 13px; margin: 8px 0 0 0;\">" + i18n.noImageSet + "</p></div>");
                $("#upload-default-og-image").html("<span class=\"dashicons dashicons-upload\" style=\"margin-top: 3px;\"></span> " + i18n.selectImage);
                $(this).remove();
            });
        });
        </script>
        <?php
    }
    
    public function add_og_image() {
        global $post;

        // Only check for featured image on singular posts/pages
        if (is_singular() && has_post_thumbnail()) {
            return;
        }

        $settings = get_option('switchboard_default-og-image_settings', []);

        // Support both old image_url and new image_id formats for backward compatibility
        $image_url = '';
        if (isset($settings['image_id']) && !empty($settings['image_id'])) {
            $image_id = intval($settings['image_id']);
            $image_url = wp_get_attachment_url($image_id);
        } elseif (isset($settings['image_url']) && !empty($settings['image_url'])) {
            // Fallback to old URL format for backward compatibility
            $image_url = $settings['image_url'];
        }

        if (!empty($image_url)) {
            echo '<meta property="og:image" content="' . esc_url($image_url) . '" />' . "\n";
            echo '<meta name="twitter:image" content="' . esc_url($image_url) . '" />' . "\n";
        }
    }
}

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