<?php
/**
 * Name: 404 Redirect
 * Description: Redirect all 404 error pages to homepage or custom URL automatically to improve user experience and prevent visitors from landing on broken links
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Improve User Experience",
 *     "description": "Redirect users hitting broken links to homepage instead of showing ugly 404 page, reducing bounce rate."
 *   },
 *   {
 *     "title": "Site Restructure Recovery",
 *     "description": "Send old indexed URLs to new pages after site migration or permalink structure changes."
 *   },
 *   {
 *     "title": "SEO Preservation",
 *     "description": "Prevent visitors from dead-end 404s by routing them to custom landing page or search page."
 *   }
 * ]
 * Added: 2025-07-18
 * Tags: 404, redirect, error, seo, url
 * WhereToFind: {
 *   "location": "404 Page Test",
 *   "url": "/non-existent-page-test-404",
 *   "instructions": "Visit non-existent URL - should redirect to homepage or custom URL",
 *   "newTab": true
 * }
 */

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

class Switchboard404Redirect {

    public function __construct() {
        add_action('template_redirect', [$this, 'redirect_404']);
    }

    /**
     * Register data locations for cleanup system
     *
     * @return array Data storage locations
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_404-redirect_settings',
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
    
    /**
     * Render settings panel for 404 Redirect
     *
     * Displays settings interface for redirecting 404 errors to a custom URL with:
     * - URL input field for specifying the redirect destination
     * - Defaults to homepage if no URL is specified
     * - Clean, simple interface with clear labeling and helpful description
     *
     * The interface uses a standard URL input field with built-in browser validation
     * to ensure proper URL formatting. The redirect is implemented using a 301
     * permanent redirect, which is SEO-friendly and tells search engines that the
     * page has permanently moved. This module helps prevent visitors from landing
     * on broken links or ugly 404 error pages, instead routing them to a useful
     * destination like the homepage, a custom landing page, or a search page. This
     * is particularly valuable after site restructures, permalink changes, or when
     * dealing with dead links from external sources. The automatic redirect improves
     * user experience and can reduce bounce rates caused by 404 errors.
     *
     * @param array $settings Current module settings with 'redirect_url' key containing the destination URL
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $redirect_url = isset($settings['redirect_url']) ? $settings['redirect_url'] : home_url();
        ?>
        <input type="hidden" name="module" value="404-redirect">

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading"><?php esc_html_e('404 Redirect', 'wpswitchboard'); ?></h3>
            <p class="sb-sp-description"><?php esc_html_e('Redirect all 404 error pages to homepage or custom URL automatically to improve user experience and prevent visitors from landing on broken links.', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_redirect_url" class="sb-sp-label"><?php esc_html_e('Redirect URL', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Where to redirect 404 errors. Default: Homepage', 'wpswitchboard'); ?></p>
            </div>
            <input type="url" name="setting_redirect_url" id="setting_redirect_url" value="<?php echo esc_attr($redirect_url); ?>" class="sb-sp-input" placeholder="<?php echo esc_attr(home_url()); ?>">
        </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>
            <p class="sb-sp-description" style="margin: 0;">
                <?php esc_html_e('When a visitor encounters a 404 error (page not found), they will be automatically redirected to the URL specified above using a 301 permanent redirect. This helps prevent visitors from landing on broken links and improves user experience, especially after site restructures or permalink changes.', 'wpswitchboard'); ?>
            </p>
        </div>
        <?php
    }
    
    public function redirect_404() {
        if (is_404()) {
            $settings = get_option('switchboard_404-redirect_settings', []);
            $redirect_url = isset($settings['redirect_url']) ? $settings['redirect_url'] : home_url();
            
            wp_safe_redirect(esc_url($redirect_url), 301);
            exit;
        }
    }
}

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