<?php
/**
 * Name: External Permalinks
 * Description: Redirect individual posts or pages to external URLs while keeping them in your WordPress database for organization, navigation, and menu management purposes
 * Category: Content
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Affiliate Product Links",
 *     "description": "Create menu items linking directly to Amazon products or external affiliate offers without placeholder WordPress pages."
 *   },
 *   {
 *     "title": "Social Media Menu",
 *     "description": "Add Facebook, Twitter, Instagram links in navigation menu that go directly to social profiles, not WordPress pages."
 *   },
 *   {
 *     "title": "Partner Resources",
 *     "description": "Link to partner login portals or external resources from WordPress menu without creating redirect pages."
 *   }
 * ]
 * Added: 2025-06-18
 * Tags: redirect, external, url, permalink, links
 * WhereToFind: {
 *   "location": "Post editor sidebar",
 *   "url": "",
 *   "instructions": "Add external URL in metabox to redirect post",
 *   "newTab": false
 * }
 */

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

class SwitchboardExternalPermalinks {
    
    public function __construct() {
        add_action('add_meta_boxes', [$this, 'add_meta_box']);
        add_action('save_post', [$this, 'save_meta_box']);
        add_action('wp', [$this, 'redirect_external'], 1);
    }
    
    public function render_settings($settings = []) {
        $selected_post_types = isset($settings['post_types']) ? explode(',', $settings['post_types']) : ['post', 'page'];
        $selected_post_types = array_map('trim', $selected_post_types);

        // Exclude media and system post types
        $all_post_types = get_post_types(['public' => true], 'objects');
        $exclude_types = ['attachment', 'wp_block', 'wp_template', 'wp_template_part', 'wp_navigation'];
        $all_post_types = array_diff_key($all_post_types, array_flip($exclude_types));
        ?>
        <input type="hidden" name="module" value="external-permalinks">
        <input type="hidden" name="setting_post_types" id="setting_post_types" value="<?php echo esc_attr(implode(',', $selected_post_types)); ?>">

        <div class="sb-sp-group">
            <label class="sb-sp-label"><?php esc_html_e('Select Post Types', 'wpswitchboard'); ?></label>
            <p class="sb-sp-description"><?php esc_html_e('Enable external permalinks for these post types. An "External URL" metabox will appear in the post editor sidebar.', 'wpswitchboard'); ?></p>

            <div class="switchboard-tag-selector" data-input-id="setting_post_types">
                <div class="switchboard-selected-tags" id="selected-post-types">
                    <?php foreach ($selected_post_types as $pt_slug):
                        if (isset($all_post_types[$pt_slug])): ?>
                            <span class="switchboard-tag" data-value="<?php echo esc_attr($pt_slug); ?>">
                                <?php echo esc_html($all_post_types[$pt_slug]->label); ?>
                                <span class="remove-tag">×</span>
                            </span>
                        <?php endif;
                    endforeach; ?>
                </div>
                <div class="switchboard-available-tags">
                    <?php foreach ($all_post_types as $pt_slug => $pt_obj):
                        $is_selected = in_array($pt_slug, $selected_post_types) ? 'selected' : ''; ?>
                        <span class="switchboard-tag-option <?php echo esc_attr($is_selected); ?>" data-value="<?php echo esc_attr($pt_slug); ?>">
                            <?php echo esc_html($pt_obj->label); ?>
                        </span>
                    <?php endforeach; ?>
                </div>
            </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('Add an external URL in the "External URL" metabox when editing a post', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('When someone visits that post, they\'ll be redirected to the external URL', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('Uses a 301 (permanent) redirect for SEO benefits', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><?php esc_html_e('Post stays in WordPress for organization and navigation menu purposes', '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('Common Use Cases', 'wpswitchboard'); ?></h4>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Affiliate Links:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Create menu items linking to Amazon products or partner offers', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Social Media:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Add social profile links in your navigation menu', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('External Resources:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Link to partner portals or documentation sites', 'wpswitchboard'); ?></li>
                <li class="sb-sp-list-item"><strong><?php esc_html_e('Downloads:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Redirect to file hosting services or app stores', '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('Important Note', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description" style="margin: 0;"><?php esc_html_e('The post content won\'t be visible to visitors since they\'ll be redirected. Use the post for internal notes or SEO data only.', 'wpswitchboard'); ?></p>
        </div>
        <?php
    }

    public function add_meta_box() {
        $settings = get_option('switchboard_external-permalinks_settings', []);
        $post_types = ['post', 'page']; // Default
        if (isset($settings['post_types']) && is_string($settings['post_types']) && !empty($settings['post_types'])) {
            $post_types = explode(',', $settings['post_types']);
        }

        foreach ($post_types as $post_type) {
            add_meta_box(
                'switchboard_external_url',
                __('External URL', 'wpswitchboard') . ' <span class="switchboard-badge">SWITCHBOARD</span>',
                [$this, 'render_meta_box'],
                trim($post_type),
                'side',
                'high'
            );
        }
    }

    public function render_meta_box($post) {
        wp_nonce_field('switchboard_external_url', 'switchboard_external_url_nonce');
        $external_url = get_post_meta($post->ID, '_switchboard_external_url', true);
        ?>
        <div style="padding: 4px 0;">
            <label for="switchboard_external_url" class="sb-sp-label" style="display: block; margin-bottom: 8px;"><?php esc_html_e('External URL', 'wpswitchboard'); ?></label>
            <input type="url" id="switchboard_external_url" name="switchboard_external_url"
                   value="<?php echo esc_url($external_url); ?>" class="sb-sp-input" style="width: 100%;"
                   placeholder="https://example.com">
            <p class="sb-sp-description" style="margin: 8px 0 0 0;"><?php esc_html_e('If set, this post will redirect to the external URL using a 301 redirect.', 'wpswitchboard'); ?></p>
        </div>
        <?php
    }
    
    public function save_meta_box($post_id) {
        if (!isset($_POST['switchboard_external_url_nonce']) ||
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['switchboard_external_url_nonce'])), 'switchboard_external_url')) {
            return;
        }
        
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        if (isset($_POST['switchboard_external_url'])) {
            $external_url = esc_url_raw(wp_unslash($_POST['switchboard_external_url']));
            update_post_meta($post_id, '_switchboard_external_url', $external_url);
        }
    }
    
    public function redirect_external() {
        global $wp_query;
        
        if (!is_singular()) {
            return;
        }
        
        $post_id = get_queried_object_id();
        if (!$post_id) {
            return;
        }
        
        $external_url = get_post_meta($post_id, '_switchboard_external_url', true);
        
        if (!empty($external_url)) {
            // Prevent any output buffering or headers already sent
            if (!headers_sent()) {
                header('Location: ' . esc_url_raw($external_url), true, 301);
                exit;
            }
        }
    }

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_external-permalinks_settings',
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [
                '_switchboard_external_url',
            ],
            'user_meta' => [],
        ];
    }
}

$switchboard_instance = new SwitchboardExternalPermalinks();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
