<?php
/**
 * Name: Conditional Redirects
 * Description: Redirect users based on browser language, URL parameters, referrer, and login status to create personalized user experiences and improve targeting
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Language-Based Redirects",
 *     "description": "Automatically redirect users to localized content based on their browser language preferences."
 *   },
 *   {
 *     "title": "Campaign Tracking",
 *     "description": "Redirect users from specific marketing campaigns (URL parameters) to dedicated landing pages."
 *   },
 *   {
 *     "title": "Referrer-Based Routing",
 *     "description": "Send visitors from social media or partner sites to custom welcome pages."
 *   },
 *   {
 *     "title": "Login-Based Access",
 *     "description": "Show different content to logged-in vs logged-out users for better personalization."
 *   }
 * ]
 * Added: 2025-01-13
 * Tags: redirects, conditional, language, referrer, parameters, login
 * WhereToFind: {
 *   "location": "Switchboard → Conditional Redirects",
 *   "url": "admin.php?page=conditional-redirects",
 *   "instructions": "Manage your conditional redirect rules from dedicated dashboard",
 *   "newTab": false
 * }
 */

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

class SwitchboardConditionalRedirects {

    private $table_name;
    private $version = '1.2';

    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'switchboard_conditional_redirects';

        // Create table on activation
        add_action('admin_init', [$this, 'maybe_create_table']);

        // Admin menu
        add_action('admin_menu', [$this, 'add_admin_menu']);

        // Form submission handler (WordPress standard way)
        add_action('admin_post_cr_save', [$this, 'handle_save']);

        // Keep toggle AJAX (for quick enable/disable in list view)
        add_action('wp_ajax_switchboard_conditional_redirects_toggle', [$this, 'ajax_toggle']);

        // Enqueue admin scripts
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);

        // Admin notices
        add_action('admin_notices', [$this, 'show_admin_notices']);

        // Check and execute redirects
        add_action('template_redirect', [$this, 'check_and_redirect'], 1);
    }

    /**
     * Clear cached rules
     */
    public function clear_rules_cache() {
        delete_transient('switchboard_conditional_redirect_rules');
    }

    /**
     * Add admin menu for Conditional Redirects
     */
    public function add_admin_menu() {
        add_submenu_page(
            'switchboard',
            'Conditional Redirects',
            'Conditional Redirects',
            'manage_options',
            'conditional-redirects',
            [$this, 'render_admin_page']
        );
    }

    /**
     * Render admin page
     * Always show admin.php which handles routing internally
     */
    public function render_admin_page() {
        // Handle delete action
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['rule'])) {
            $this->handle_delete();
            return;
        }

        // Always include admin.php which handles all views (list, add, edit)
        $admin_file = plugin_dir_path(__FILE__) . '../../assets/conditional-redirects/admin.php';
        if (file_exists($admin_file)) {
            include $admin_file;
        } else {
            echo '<div class="wrap"><h1>' . esc_html__('Admin page not found', 'wpswitchboard') . '</h1></div>';
        }
    }

    /**
     * Handle delete action
     */
    private function handle_delete() {
        if (!isset($_GET['rule'])) {
            wp_die(esc_html__('No rule specified', 'wpswitchboard'));
        }

        $rule_id = intval($_GET['rule']);

        // Verify nonce
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'delete_rule_' . $rule_id)) {
            wp_die(esc_html__('Security check failed', 'wpswitchboard'));
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Permission denied', 'wpswitchboard'));
        }

        // Delete rule
        global $wpdb;
        $result = $wpdb->delete(
            $this->table_name,
            ['id' => $rule_id],
            ['%d']
        );

        if ($result) {
            $this->clear_rules_cache();

            // Redirect with success message
            wp_redirect(add_query_arg([
                'page' => 'conditional-redirects',
                'message' => 'deleted'
            ], admin_url('admin.php')));
            exit;
        } else {
            wp_die(esc_html__('Failed to delete rule', 'wpswitchboard'));
        }
    }

    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets($hook) {
        // Check if we're on the conditional redirects page
        $is_redirects_page = (
            (isset($_GET['page']) && $_GET['page'] === 'conditional-redirects') ||
            strpos($hook, 'conditional-redirects') !== false
        );

        if (!$is_redirects_page) {
            return;
        }

        // Enqueue the main Switchboard admin CSS (contains all sb-mp-* and sb-sp-* classes)
        if (defined('SWITCHBOARD_URL') && defined('SWITCHBOARD_VERSION')) {
            wp_enqueue_style(
                'switchboard-admin',
                SWITCHBOARD_URL . 'switchboard-admin.css',
                [],
                SWITCHBOARD_VERSION
            );
        }
    }

    /**
     * Conditional Redirects has no settings panel - uses dedicated page only
     * All management happens on dedicated page: admin.php?page=conditional-redirects
     */

    /**
     * Handle form submission (WordPress admin_post_ action)
     * This is the reliable, standard WordPress way
     */
    public function handle_save() {
        // Verify nonce
        if (!isset($_POST['cr_nonce']) || !wp_verify_nonce($_POST['cr_nonce'], 'cr_save')) {
            wp_die(esc_html__('Security check failed', 'wpswitchboard'));
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Permission denied', 'wpswitchboard'));
        }

        // Get form data
        $is_edit = !empty($_POST['is_edit']);
        $rule_id = $is_edit ? intval($_POST['rule_id']) : 0;

        // Validate required POST fields exist
        if (!isset($_POST['rule_name'], $_POST['redirect_url'], $_POST['redirect_action'], $_POST['redirect_type'])) {
            wp_die(esc_html__('Missing required fields', 'wpswitchboard'));
        }

        // Collect and sanitize basic data (wp_unslash before sanitize_text_field)
        $rule_data = [
            'rule_name' => sanitize_text_field(wp_unslash($_POST['rule_name'])),
            'priority' => isset($_POST['priority']) ? intval($_POST['priority']) : 10,
            'source_url' => isset($_POST['source_url']) ? sanitize_text_field(wp_unslash($_POST['source_url'])) : '',
            'redirect_action' => in_array($_POST['redirect_action'], ['fixed', 'append', 'parameter'], true) ? $_POST['redirect_action'] : 'fixed',
            'redirect_url' => sanitize_text_field(wp_unslash($_POST['redirect_url'])),
            'redirect_type' => in_array($_POST['redirect_type'], ['301', '302'], true) ? $_POST['redirect_type'] : '301',
            'is_active' => !empty($_POST['is_active']) ? 1 : 0,
        ];

        // Build conditions object
        $conditions = [];

        if (!empty($_POST['cond_language_enabled'])) {
            $conditions['language'] = [
                'enabled' => true,
                'languages' => isset($_POST['cond_language_codes']) ? sanitize_text_field(wp_unslash($_POST['cond_language_codes'])) : ''
            ];
        }

        if (!empty($_POST['cond_param_enabled'])) {
            $conditions['url_param'] = [
                'enabled' => true,
                'param_name' => isset($_POST['cond_param_name']) ? sanitize_text_field(wp_unslash($_POST['cond_param_name'])) : '',
                'param_value' => isset($_POST['cond_param_value']) ? sanitize_text_field(wp_unslash($_POST['cond_param_value'])) : ''
            ];
        }

        if (!empty($_POST['cond_referrer_enabled'])) {
            $conditions['referrer'] = [
                'enabled' => true,
                'referrer_pattern' => isset($_POST['cond_referrer_pattern']) ? sanitize_text_field(wp_unslash($_POST['cond_referrer_pattern'])) : ''
            ];
        }

        if (!empty($_POST['cond_login_enabled'])) {
            $conditions['login_status'] = [
                'enabled' => true,
                'status' => isset($_POST['cond_login_status']) ? sanitize_text_field(wp_unslash($_POST['cond_login_status'])) : 'logged_out'
            ];
        }

        $rule_data['conditions'] = wp_json_encode($conditions);

        // Validate required fields
        if (empty($rule_data['rule_name']) || empty($rule_data['redirect_url'])) {
            wp_die(esc_html__('Rule name and redirect URL are required', 'wpswitchboard'));
        }

        // Validate condition data
        if (isset($conditions['url_param']) && $conditions['url_param']['enabled'] && empty($conditions['url_param']['param_name'])) {
            wp_die(esc_html__('Parameter name is required when URL Parameter condition is enabled', 'wpswitchboard'));
        }
        if (isset($conditions['language']) && $conditions['language']['enabled'] && empty($conditions['language']['languages'])) {
            wp_die(esc_html__('Language codes are required when Language condition is enabled', 'wpswitchboard'));
        }
        if (isset($conditions['referrer']) && $conditions['referrer']['enabled'] && empty($conditions['referrer']['referrer_pattern'])) {
            wp_die(esc_html__('Referrer pattern is required when Referrer condition is enabled', 'wpswitchboard'));
        }

        global $wpdb;

        if ($is_edit && $rule_id > 0) {
            // Update existing rule
            $result = $wpdb->update(
                $this->table_name,
                $rule_data,
                ['id' => $rule_id],
                ['%s', '%d', '%s', '%s', '%s', '%s', '%d', '%s'],
                ['%d']
            );

            $message = 'updated';
        } else {
            // Insert new rule
            $result = $wpdb->insert(
                $this->table_name,
                array_merge($rule_data, ['hit_count' => 0]),
                ['%s', '%d', '%s', '%s', '%s', '%s', '%d', '%s', '%d']
            );

            $message = 'created';
        }

        if ($result !== false) {
            $this->clear_rules_cache();

            // Redirect with success message
            wp_redirect(add_query_arg([
                'page' => 'conditional-redirects',
                'message' => $message
            ], admin_url('admin.php')));
            exit;
        } else {
            wp_die(esc_html__('Failed to save rule', 'wpswitchboard'));
        }
    }

    /**
     * Show admin notices after actions
     */
    public function show_admin_notices() {
        if (!isset($_GET['page']) || $_GET['page'] !== 'conditional-redirects') {
            return;
        }

        if (!isset($_GET['message'])) {
            return;
        }

        $message = sanitize_text_field($_GET['message']);
        $messages = [
            'created' => __('Redirect rule created successfully!', 'wpswitchboard'),
            'updated' => __('Redirect rule updated successfully!', 'wpswitchboard'),
            'deleted' => __('Redirect rule deleted successfully!', 'wpswitchboard'),
        ];

        if (isset($messages[$message])) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html($messages[$message]) . '</p></div>';
        }
    }

    /**
     * Create database table for conditional redirects
     */
    public function maybe_create_table() {
        $current_version = get_option('switchboard_conditional_redirects_version', '0');

        if (version_compare($current_version, $this->version, '<')) {
            global $wpdb;

            $charset_collate = $wpdb->get_charset_collate();

            $sql = "CREATE TABLE {$this->table_name} (
                id bigint(20) NOT NULL AUTO_INCREMENT,
                rule_name varchar(255) NOT NULL,
                is_active tinyint(1) DEFAULT 1,
                priority int(11) DEFAULT 0,
                conditions text NOT NULL,
                source_url varchar(500) DEFAULT NULL,
                redirect_action varchar(20) DEFAULT 'fixed',
                redirect_url varchar(500) NOT NULL,
                redirect_type varchar(3) DEFAULT '301',
                hit_count bigint(20) DEFAULT 0,
                created_at datetime DEFAULT CURRENT_TIMESTAMP,
                updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                KEY is_active (is_active),
                KEY priority (priority)
            ) $charset_collate;";

            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);

            update_option('switchboard_conditional_redirects_version', $this->version);
        }
    }

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_conditional-redirects_settings',
                'switchboard_conditional_redirects_version',
            ],
            'option_patterns' => [],
            'tables' => [$this->table_name],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }

    /**
     * OLD RENDER SETTINGS METHOD - NO LONGER USED
     * Kept for reference but not called anymore
     */
    private function OLD_render_settings_DEPRECATED($settings = []) {
        echo '<input type="hidden" name="module" value="conditional-redirects">';

        // Inline styles
        echo '<style>
            .conditional-redirects-container { max-width: 100%; }
            .cr-stats-bar { display: flex; gap: 20px; margin-bottom: 20px; }
            .cr-stat-card { flex: 1; background: white; border: 1px solid #e5e7eb; border-radius: 6px; padding: 15px; }
            .cr-stat-label { font-size: 12px; color: #6b7280; text-transform: uppercase; margin-bottom: 5px; }
            .cr-stat-value { font-size: 24px; font-weight: 700; color: #1f2937; }
            .cr-add-form { background: #f9fafb; padding: 20px; border-radius: 8px; border: 1px solid #e5e7eb; margin-bottom: 20px; }
            .cr-form-section { margin-bottom: 20px; }
            .cr-form-section h4 { margin: 0 0 10px 0; font-size: 14px; color: #374151; }
            .cr-form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px; }
            .cr-form-field label { display: block; margin-bottom: 5px; font-weight: 600; font-size: 13px; color: #374151; }
            .cr-form-field input, .cr-form-field select { width: 100%; padding: 8px 10px; border: 1px solid #d1d5db; border-radius: 4px; font-size: 13px; }
            .cr-form-field input:focus, .cr-form-field select:focus { outline: none; border-color: var(--primary-500); box-shadow: 0 0 0 1px var(--primary-500); }
            .cr-form-field input[type="checkbox"] { width: auto; margin-right: 5px; }
            .cr-condition-group { background: white; padding: 15px; border-radius: 6px; border: 1px solid #e5e7eb; margin-bottom: 10px; }
            .cr-condition-header { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }
            .cr-condition-header input[type="checkbox"] { width: auto; }
            .cr-condition-body { padding-left: 25px; }
            .cr-table-wrapper { background: white; border: 1px solid #e5e5e5; border-radius: 4px; overflow: hidden; }
            .cr-table { width: 100%; border-collapse: collapse; font-size: 13px; }
            .cr-table thead { background: #f9fafb; border-bottom: 1px solid #e5e5e5; }
            .cr-table th { padding: 12px; text-align: left; font-weight: 600; color: #374151; font-size: 12px; text-transform: uppercase; }
            .cr-table td { padding: 12px; border-bottom: 1px solid #f3f4f6; color: #1f2937; }
            .cr-table tbody tr:last-child td { border-bottom: none; }
            .cr-table tbody tr:hover { background: #fafafa; }
            .cr-table tbody tr.disabled { opacity: 0.5; }
            .cr-toggle-cell { width: 50px; text-align: center; }
            .cr-badge { display: inline-block; padding: 3px 8px; border-radius: 3px; font-size: 11px; font-weight: 600; margin-right: 5px; }
            .cr-badge-language { background: #dbeafe; color: #1e40af; }
            .cr-badge-param { background: #fef3c7; color: #92400e; }
            .cr-badge-referrer { background: var(--primary-100); color: var(--primary-800); }
            .cr-badge-login { background: #dcfce7; color: #166534; }
            .cr-type-badge { display: inline-block; padding: 3px 8px; border-radius: 3px; font-size: 11px; font-weight: 600; }
            .cr-type-301 { background: #dcfce7; color: #166534; }
            .cr-type-302 { background: #fef3c7; color: #92400e; }
            .cr-hits-cell { text-align: center; font-weight: 600; color: #1DA1F2; }
            .cr-actions-cell { text-align: right; white-space: nowrap; }
            .cr-action-btn { padding: 6px 10px; background: transparent; color: #6b7280; border: 1px solid #e5e7eb; border-radius: 3px; font-size: 12px; cursor: pointer; margin-left: 4px; }
            .cr-action-btn:hover { background: #f3f4f6; color: #374151; border-color: #d1d5db; }
            .cr-action-btn.delete:hover { background: #fef2f2; color: #dc2626; border-color: #fecaca; }
            .cr-toggle-switch { position: relative; display: inline-block; width: 44px; height: 24px; }
            .cr-toggle-switch input { opacity: 0; width: 0; height: 0; }
            .cr-toggle-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: 0.3s; border-radius: 24px; }
            .cr-toggle-slider:before { position: absolute; content: ""; height: 18px; width: 18px; left: 3px; bottom: 3px; background-color: white; transition: 0.3s; border-radius: 50%; }
            input:checked + .cr-toggle-slider { background-color: #1DA1F2; }
            input:checked + .cr-toggle-slider:before { transform: translateX(20px); }
            .cr-empty-state { text-align: center; padding: 60px 20px; background: #f9f9f9; border-radius: 8px; border: 2px dashed #ddd; }
            .cr-info-box { background: var(--primary-50); padding: 15px; border-left: 3px solid var(--primary-500); margin-bottom: 20px; border-radius: 4px; }
            .cr-info-box h4 { margin: 0 0 10px 0; color: var(--primary-700); }
            .cr-info-box ul { margin: 0; padding-left: 20px; line-height: 1.8; }
            .cr-page-select { max-height: 200px; }
            .cr-redirect-type-toggle { display: flex; gap: 10px; margin-top: 5px; }
            .cr-redirect-type-btn { padding: 8px 15px; border: 1px solid #d1d5db; background: white; border-radius: 4px; cursor: pointer; font-size: 13px; }
            .cr-redirect-type-btn.active { background: var(--primary-500); color: white; border-color: var(--primary-500); }
        </style>';

        echo '<div class="conditional-redirects-container">';

        // Info box
        echo '<div class="cr-info-box">';
        echo '<h4 class="sb-sp-heading-sm">How Conditional Redirects Work</h4>';
        echo '<ul>';
        echo '<li><strong>Frontend Only:</strong> Redirects only affect frontend pages. WP-Admin, login page, AJAX, and REST API are never redirected</li>';
        echo '<li><strong>Multiple Conditions:</strong> Each rule can have multiple conditions (language, URL parameter, referrer, login status)</li>';
        echo '<li><strong>All Must Match:</strong> All enabled conditions in a rule must be satisfied for the redirect to trigger</li>';
        echo '<li><strong>Priority Order:</strong> Rules are checked in order of priority (lower number = higher priority)</li>';
        echo '<li><strong>First Match Wins:</strong> Once a rule matches, the redirect happens immediately</li>';
        echo '</ul>';
        echo '</div>';

        // Stats
        echo '<div class="cr-stats-bar" id="cr-stats">';
        echo '<div class="cr-stat-card"><div class="cr-stat-label">Total Rules</div><div class="cr-stat-value" id="cr-stat-total">0</div></div>';
        echo '<div class="cr-stat-card"><div class="cr-stat-label">Active</div><div class="cr-stat-value" id="cr-stat-active">0</div></div>';
        echo '<div class="cr-stat-card"><div class="cr-stat-label">Total Redirects</div><div class="cr-stat-value" id="cr-stat-hits">0</div></div>';
        echo '</div>';

        // Add redirect form
        echo '<div class="cr-add-form">';
        echo '<h3 class="sb-sp-heading">Add New Redirect Rule</h3>';

        // Basic info
        echo '<div class="cr-form-section">';
        echo '<div class="cr-form-row">';
        echo '<div class="cr-form-field">';
        echo '<label>Rule Name</label>';
        echo '<input type="text" id="cr-new-name" placeholder="e.g., Spanish users to ES site" class="sb-sp-input">';
        echo '</div>';
        echo '<div class="cr-form-field">';
        echo '<label>Priority (lower = higher priority)</label>';
        echo '<input type="number" id="cr-new-priority" value="10" min="0">';
        echo '</div>';
        echo '</div>';
        echo '</div>';

        // Conditions
        echo '<div class="cr-form-section">';
        echo '<h4 class="sb-sp-heading-sm">Conditions (all enabled conditions must match)</h4>';

        // Language condition
        echo '<div class="cr-condition-group">';
        echo '<div class="cr-condition-header">';
        echo '<input type="checkbox" id="cr-cond-language-enabled" class="sb-sp-checkbox">';
        echo '<label for="cr-cond-language-enabled" class="sb-sp-m-0">Browser Language</label>';
        echo '</div>';
        echo '<div class="cr-condition-body" id="cr-cond-language-body" style="display: none;">';
        echo '<label>Languages (comma-separated, e.g., en, es, fr, de)</label>';
        echo '<input type="text" id="cr-cond-language-codes" placeholder="en, es, fr" class="sb-sp-input">';
        echo '<p class="sb-sp-description">Redirect if user\'s browser language matches any of these codes</p>';
        echo '</div>';
        echo '</div>';

        // URL Parameter condition
        echo '<div class="cr-condition-group">';
        echo '<div class="cr-condition-header">';
        echo '<input type="checkbox" id="cr-cond-param-enabled" class="sb-sp-checkbox">';
        echo '<label for="cr-cond-param-enabled" class="sb-sp-m-0">URL Parameter</label>';
        echo '</div>';
        echo '<div class="cr-condition-body" id="cr-cond-param-body" style="display: none;">';
        echo '<div class="sb-sp-grid-2 sb-sp-gap-2">';
        echo '<div><label>Parameter Name</label><input type="text" id="cr-cond-param-name" placeholder="utm_source" class="sb-sp-input"></div>';
        echo '<div><label>Parameter Value (optional - leave empty to match any value)</label><input type="text" id="cr-cond-param-value" placeholder="facebook" class="sb-sp-input"></div>';
        echo '</div>';
        echo '<p class="sb-sp-description">Redirect if URL contains this parameter (optionally with specific value)</p>';
        echo '</div>';
        echo '</div>';

        // Referrer condition
        echo '<div class="cr-condition-group">';
        echo '<div class="cr-condition-header">';
        echo '<input type="checkbox" id="cr-cond-referrer-enabled" class="sb-sp-checkbox">';
        echo '<label for="cr-cond-referrer-enabled" class="sb-sp-m-0">Referrer</label>';
        echo '</div>';
        echo '<div class="cr-condition-body" id="cr-cond-referrer-body" style="display: none;">';
        echo '<label>Referrer Pattern (partial match, e.g., facebook.com, google.com)</label>';
        echo '<input type="text" id="cr-cond-referrer-pattern" placeholder="facebook.com" class="sb-sp-input">';
        echo '<p class="sb-sp-description">Redirect if the referrer URL contains this text</p>';
        echo '</div>';
        echo '</div>';

        // Login status condition
        echo '<div class="cr-condition-group">';
        echo '<div class="cr-condition-header">';
        echo '<input type="checkbox" id="cr-cond-login-enabled" class="sb-sp-checkbox">';
        echo '<label for="cr-cond-login-enabled" class="sb-sp-m-0">Login Status</label>';
        echo '</div>';
        echo '<div class="cr-condition-body" id="cr-cond-login-body" style="display: none;">';
        echo '<label>User Must Be</label>';
        echo '<select id="cr-cond-login-status" class="sb-sp-select">';
        echo '<option value="logged_in">Logged In</option>';
        echo '<option value="logged_out">Logged Out</option>';
        echo '</select>';
        echo '<p class="sb-sp-description">Redirect based on user authentication status</p>';
        echo '</div>';
        echo '</div>';

        echo '</div>'; // End conditions section

        // Source URL (optional)
        echo '<div class="cr-form-section">';
        echo '<h4 class="sb-sp-heading-sm">Source Page (Optional)</h4>';
        echo '<div class="cr-form-field">';
        echo '<label>Apply rule only to this page (leave empty for all frontend pages)</label>';
        echo '<input type="text" id="cr-new-source-url" placeholder="Leave empty for all frontend pages, or enter: / or /pricing/ or /blog/*" class="sb-sp-input">';
        echo '<p class="sb-sp-description"><strong>Examples:</strong> Empty = all frontend pages (not wp-admin), <code>/</code> = homepage only, <code>/pricing/</code> = specific page</p>';
        echo '</div>';
        echo '</div>';

        // Redirect target
        echo '<div class="cr-form-section">';
        echo '<h4 class="sb-sp-heading-sm">Redirect Target</h4>';

        // Redirect Action
        echo '<div class="cr-form-field sb-sp-mb-4">';
        echo '<label>Redirect Action</label>';
        echo '<select id="cr-new-redirect-action" class="sb-sp-select">';
        echo '<option value="fixed">Fixed URL - Redirect to specific URL</option>';
        echo '<option value="append">Append to Path - Add to current URL path (e.g., /es/)</option>';
        echo '<option value="parameter">Add Parameter - Add query parameter (e.g., lang=es)</option>';
        echo '</select>';
        echo '<p class="sb-sp-description" id="cr-action-description">Redirect to a fixed URL (internal or external)</p>';
        echo '</div>';

        echo '<div class="cr-form-row">';
        echo '<div class="cr-form-field">';
        echo '<label id="cr-redirect-url-label">Redirect URL / Value</label>';
        echo '<input type="text" id="cr-new-redirect-url" placeholder="https://example.com/page or /internal-page" class="sb-sp-input">';
        echo '<p class="sb-sp-description" id="cr-redirect-url-hint">Enter a full URL (https://...) or internal path (/page)</p>';
        echo '</div>';
        echo '<div class="cr-form-field">';
        echo '<label>Redirect Type</label>';
        echo '<select id="cr-new-redirect-type" class="sb-sp-select">';
        echo '<option value="301">301 Permanent</option>';
        echo '<option value="302">302 Temporary</option>';
        echo '</select>';
        echo '</div>';
        echo '</div>';

        // Alternative: Select internal page (only for fixed action)
        echo '<div class="sb-sp-mt-3" id="cr-page-select-wrapper">';
        echo '<label>Or select an internal page:</label>';
        echo '<select id="cr-new-page-select" class="sb-sp-select">';
        echo '<option value="">-- Select a page --</option>';
        echo '</select>';
        echo '</div>';

        echo '</div>';

        echo '<button type="button" class="button button-primary" id="cr-add-btn">Add Redirect Rule</button>';
        echo '</div>';

        // Rules table
        echo '<div class="cr-table-wrapper">';
        echo '<table class="cr-table">';
        echo '<thead><tr>';
        echo '<th class="cr-toggle-cell">Active</th>';
        echo '<th>Rule Name</th>';
        echo '<th>Source</th>';
        echo '<th>Conditions</th>';
        echo '<th>Action</th>';
        echo '<th>Redirect To</th>';
        echo '<th>Type</th>';
        echo '<th class="cr-hits-cell">Hits</th>';
        echo '<th class="cr-actions-cell">Actions</th>';
        echo '</tr></thead>';
        echo '<tbody id="cr-rules-list">';
        echo '<tr><td colspan="9" class="cr-empty-state">Loading rules...</td></tr>';
        echo '</tbody>';
        echo '</table>';
        echo '</div>';

        echo '</div>'; // End container

        // JavaScript
        $this->render_javascript();
    }

    /**
     * Render JavaScript for admin interface
     */
    private function render_javascript() {
        ?>
        <script>
        jQuery(document).ready(function($) {
            let rules = [];

            // Toggle condition bodies
            $('#cr-cond-language-enabled').on('change', function() {
                $('#cr-cond-language-body').toggle(this.checked);
            });
            $('#cr-cond-param-enabled').on('change', function() {
                $('#cr-cond-param-body').toggle(this.checked);
            });
            $('#cr-cond-referrer-enabled').on('change', function() {
                $('#cr-cond-referrer-body').toggle(this.checked);
            });
            $('#cr-cond-login-enabled').on('change', function() {
                $('#cr-cond-login-body').toggle(this.checked);
            });

            // Handle redirect action change - update placeholders and labels
            $('#cr-new-redirect-action').on('change', function() {
                const action = $(this).val();
                const label = $('#cr-redirect-url-label');
                const input = $('#cr-new-redirect-url');
                const hint = $('#cr-redirect-url-hint');
                const pageSelect = $('#cr-page-select-wrapper');
                const description = $('#cr-action-description');

                if (action === 'fixed') {
                    label.text('Redirect URL / Value');
                    input.attr('placeholder', 'https://example.com/page or /internal-page');
                    hint.html('Enter a full URL (https://...) or internal path (/page)');
                    pageSelect.show();
                    description.text('Redirect to a fixed URL (internal or external)');
                } else if (action === 'append') {
                    label.text('Path to Append');
                    input.attr('placeholder', '/es/ or /fr/ or /language/');
                    hint.html('<strong>Example:</strong> Enter <code>/es/</code> to change <code>/about/</code> → <code>/es/about/</code>');
                    pageSelect.hide();
                    description.text('Add this path segment to the current URL (e.g., /es/ for language subfolders)');
                } else if (action === 'parameter') {
                    label.text('Parameter to Add');
                    input.attr('placeholder', 'lang=es or source=facebook');
                    hint.html('<strong>Example:</strong> Enter <code>lang=es</code> to add <code>?lang=es</code> to current URL');
                    pageSelect.hide();
                    description.text('Add a query parameter to the current URL (preserves existing parameters)');
                }
            });

            // Load pages for dropdown
            function loadPages() {
                $.ajax({
                    url: switchboardSettings.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_conditional_redirects_get_pages',
                        nonce: switchboardSettings.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            const select = $('#cr-new-page-select');
                            select.find('option:not(:first)').remove();
                            response.data.forEach(function(page) {
                                select.append(`<option value="${page.url}">${page.title}</option>`);
                            });
                        }
                    }
                });
            }

            // When page is selected, populate URL field
            $('#cr-new-page-select').on('change', function() {
                if ($(this).val()) {
                    $('#cr-new-redirect-url').val($(this).val());
                }
            });

            // Load rules
            function loadRules() {
                $.ajax({
                    url: switchboardSettings.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_conditional_redirects_get_all',
                        nonce: switchboardSettings.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            rules = response.data;
                            renderRules();
                            updateStats();
                        }
                    }
                });
            }

            // Render rules table
            function renderRules() {
                const tbody = $('#cr-rules-list');
                tbody.empty();

                if (rules.length === 0) {
                    tbody.append('<tr><td colspan="9" class="cr-empty-state">No redirect rules yet. Add your first rule above.</td></tr>');
                    return;
                }

                rules.forEach(function(rule) {
                    let conditions = {};
                    try {
                        conditions = JSON.parse(rule.conditions);
                    } catch (e) {
                        console.error('Invalid JSON in rule conditions:', rule.id, e);
                        conditions = {};
                    }

                    const row = $('<tr></tr>').addClass(rule.is_active == '0' ? 'disabled' : '');

                    // Toggle
                    row.append(`
                        <td class="cr-toggle-cell">
                            <label class="cr-toggle-switch">
                                <input type="checkbox" ${rule.is_active == '1' ? 'checked' : ''} onchange="toggleRule(${rule.id}, this.checked)" class="sb-sp-checkbox">
                                <span class="cr-toggle-slider"></span>
                            </label>
                        </td>
                    `);

                    // Rule name with priority
                    row.append(`<td><strong>${escapeHtml(rule.rule_name)}</strong><br><small class="text-gray-500">Priority: ${rule.priority}</small></td>`);

                    // Source URL
                    const sourceText = rule.source_url && rule.source_url.trim() !== ''
                        ? escapeHtml(rule.source_url)
                        : '<em style="color: #9ca3af;">All pages</em>';
                    row.append(`<td class="sb-sp-text-xs">${sourceText}</td>`);

                    // Conditions
                    let conditionsBadges = '';
                    if (conditions.language && conditions.language.enabled) {
                        conditionsBadges += `<span class="cr-badge cr-badge-language">${escapeHtml(conditions.language.languages)}</span>`;
                    }
                    if (conditions.url_param && conditions.url_param.enabled) {
                        const paramText = conditions.url_param.param_value
                            ? `${escapeHtml(conditions.url_param.param_name)}=${escapeHtml(conditions.url_param.param_value)}`
                            : escapeHtml(conditions.url_param.param_name);
                        conditionsBadges += `<span class="cr-badge cr-badge-param">${paramText}</span>`;
                    }
                    if (conditions.referrer && conditions.referrer.enabled) {
                        conditionsBadges += `<span class="cr-badge cr-badge-referrer">${escapeHtml(conditions.referrer.referrer_pattern)}</span>`;
                    }
                    if (conditions.login_status && conditions.login_status.enabled) {
                        const loginText = conditions.login_status.status === 'logged_in' ? 'Logged In' : 'Logged Out';
                        conditionsBadges += `<span class="cr-badge cr-badge-login">${loginText}</span>`;
                    }
                    row.append(`<td>${conditionsBadges || '<em style="color: #9ca3af;">No conditions</em>'}</td>`);

                    // Redirect Action
                    const actionText = rule.redirect_action === 'append' ? 'Append' :
                                     rule.redirect_action === 'parameter' ? 'Parameter' :
                                     'Fixed';
                    row.append(`<td class="sb-sp-text-xs">${actionText}</td>`);

                    // Redirect URL
                    row.append(`<td style="word-break: break-all; font-size: 12px;">${escapeHtml(rule.redirect_url)}</td>`);

                    // Type
                    row.append(`<td><span class="cr-type-badge cr-type-${rule.redirect_type}">${rule.redirect_type}</span></td>`);

                    // Hits
                    row.append(`<td class="cr-hits-cell">${parseInt(rule.hit_count).toLocaleString()}</td>`);

                    // Actions
                    row.append(`
                        <td class="cr-actions-cell">
                            <button class="cr-action-btn delete" onclick="deleteRule(${rule.id})">Delete</button>
                        </td>
                    `);

                    tbody.append(row);
                });
            }

            // Update stats
            function updateStats() {
                const total = rules.length;
                const active = rules.filter(r => r.is_active == '1').length;
                const hits = rules.reduce((sum, r) => sum + parseInt(r.hit_count), 0);

                $('#cr-stat-total').text(total);
                $('#cr-stat-active').text(active);
                $('#cr-stat-hits').text(hits.toLocaleString());
            }

            // Add rule
            $('#cr-add-btn').on('click', function() {
                const name = $('#cr-new-name').val().trim();
                const priority = $('#cr-new-priority').val();
                const sourceUrl = $('#cr-new-source-url').val().trim();
                const redirectAction = $('#cr-new-redirect-action').val();
                const redirectUrl = $('#cr-new-redirect-url').val().trim();
                const redirectType = $('#cr-new-redirect-type').val();

                if (!name || !redirectUrl) {
                    alert('Please enter a rule name and redirect URL/value');
                    return;
                }

                // Build conditions object
                const conditions = {};

                if ($('#cr-cond-language-enabled').is(':checked')) {
                    conditions.language = {
                        enabled: true,
                        languages: $('#cr-cond-language-codes').val().trim()
                    };
                }

                if ($('#cr-cond-param-enabled').is(':checked')) {
                    conditions.url_param = {
                        enabled: true,
                        param_name: $('#cr-cond-param-name').val().trim(),
                        param_value: $('#cr-cond-param-value').val().trim()
                    };
                }

                if ($('#cr-cond-referrer-enabled').is(':checked')) {
                    conditions.referrer = {
                        enabled: true,
                        referrer_pattern: $('#cr-cond-referrer-pattern').val().trim()
                    };
                }

                if ($('#cr-cond-login-enabled').is(':checked')) {
                    conditions.login_status = {
                        enabled: true,
                        status: $('#cr-cond-login-status').val()
                    };
                }

                // Check if at least one condition is enabled
                const hasConditions = Object.keys(conditions).length > 0;
                if (!hasConditions) {
                    if (!confirm('No conditions are enabled. This rule will match ALL visitors. Continue?')) {
                        return;
                    }
                }

                $.ajax({
                    url: switchboardSettings.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_conditional_redirects_add',
                        nonce: switchboardSettings.nonce,
                        rule_name: name,
                        priority: priority,
                        conditions: JSON.stringify(conditions),
                        source_url: sourceUrl,
                        redirect_action: redirectAction,
                        redirect_url: redirectUrl,
                        redirect_type: redirectType
                    },
                    success: function(response) {
                        if (response.success) {
                            // Clear form
                            $('#cr-new-name, #cr-new-source-url, #cr-new-redirect-url, #cr-cond-language-codes, #cr-cond-param-name, #cr-cond-param-value, #cr-cond-referrer-pattern').val('');
                            $('#cr-new-priority').val('10');
                            $('#cr-new-redirect-action').val('fixed').trigger('change');
                            $('#cr-cond-language-enabled, #cr-cond-param-enabled, #cr-cond-referrer-enabled, #cr-cond-login-enabled').prop('checked', false).trigger('change');
                            $('#cr-new-page-select').val('');
                            loadRules();
                        } else {
                            alert('Error: ' + response.data);
                        }
                    }
                });
            });

            // Toggle rule
            window.toggleRule = function(id, isActive) {
                $.ajax({
                    url: switchboardSettings.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_conditional_redirects_toggle',
                        nonce: switchboardSettings.nonce,
                        id: id,
                        is_active: isActive ? 1 : 0
                    },
                    success: function(response) {
                        if (response.success) {
                            loadRules();
                        }
                    }
                });
            };

            // Delete rule
            window.deleteRule = function(id) {
                if (!confirm('Are you sure you want to delete this redirect rule?')) {
                    return;
                }

                $.ajax({
                    url: switchboardSettings.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_conditional_redirects_delete',
                        nonce: switchboardSettings.nonce,
                        id: id
                    },
                    success: function(response) {
                        if (response.success) {
                            loadRules();
                        } else {
                            alert('Error: ' + response.data);
                        }
                    }
                });
            };

            // Helper function
            function escapeHtml(text) {
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            }

            // Initial load
            loadPages();
            loadRules();
        });
        </script>
        <?php
    }

    /**
     * OLD AJAX HANDLER - NO LONGER USED (kept ajax_toggle for quick enable/disable)
     * AJAX: Get all redirect rules
     */
    private function OLD_ajax_get_all_DEPRECATED() {
        check_ajax_referer('switchboard_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }

        global $wpdb;

        // Direct query - no placeholders needed for static ORDER BY
        $rules = $wpdb->get_results(
            "SELECT * FROM {$this->table_name} ORDER BY priority ASC, id ASC",
            ARRAY_A
        );

        if ($rules === null) {
            wp_send_json_error('Database error');
            return;
        }

        wp_send_json_success($rules ? $rules : []);
    }

    /**
     * OLD AJAX HANDLER - NO LONGER USED (replaced with admin_post_cr_save)
     * AJAX: Add new redirect rule
     */
    private function OLD_ajax_add_DEPRECATED() {
        check_ajax_referer('switchboard_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }

        // Validate POST data exists
        if (!isset($_POST['rule_name'], $_POST['priority'], $_POST['redirect_url'], $_POST['redirect_type'])) {
            wp_send_json_error('Missing required fields');
            return;
        }

        $rule_name = sanitize_text_field(wp_unslash($_POST['rule_name']));
        $priority = intval($_POST['priority']);

        // Validate and sanitize JSON conditions
        $conditions_raw = isset($_POST['conditions']) ? wp_unslash($_POST['conditions']) : '{}';
        $conditions_decoded = json_decode($conditions_raw, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            wp_send_json_error('Invalid conditions format');
            return;
        }

        $conditions = wp_json_encode($conditions_decoded); // Re-encode to ensure valid JSON

        // Get new fields
        $source_url = isset($_POST['source_url']) ? sanitize_text_field(wp_unslash($_POST['source_url'])) : '';
        $redirect_action = isset($_POST['redirect_action']) && in_array($_POST['redirect_action'], ['fixed', 'append', 'parameter'], true)
            ? $_POST['redirect_action']
            : 'fixed';

        // For append/parameter actions, don't use esc_url_raw as they might be path segments or parameters
        $redirect_url = wp_unslash($_POST['redirect_url']);
        if ($redirect_action === 'fixed') {
            $redirect_url = esc_url_raw($redirect_url);
        } else {
            $redirect_url = sanitize_text_field($redirect_url);
        }

        $redirect_type = in_array($_POST['redirect_type'], ['301', '302'], true) ? $_POST['redirect_type'] : '301';

        // Validate required fields
        if (empty($rule_name)) {
            wp_send_json_error('Rule name is required');
            return;
        }

        // Validate URL format
        if (empty($redirect_url) || !$this->is_valid_redirect_url($redirect_url)) {
            wp_send_json_error('Valid redirect URL is required');
            return;
        }

        global $wpdb;
        $result = $wpdb->insert(
            $this->table_name,
            [
                'rule_name' => $rule_name,
                'priority' => $priority,
                'conditions' => $conditions,
                'source_url' => $source_url,
                'redirect_action' => $redirect_action,
                'redirect_url' => $redirect_url,
                'redirect_type' => $redirect_type,
                'is_active' => 1,
                'hit_count' => 0,
            ],
            ['%s', '%d', '%s', '%s', '%s', '%s', '%s', '%d', '%d']
        );

        if ($result) {
            // Clear cache immediately so changes are reflected
            $this->clear_rules_cache();
            wp_send_json_success('Redirect rule added successfully');
        } else {
            // SECURITY FIX: Don't expose database errors to users
            error_log('Conditional Redirects Database Error (add): ' . $wpdb->last_error);
            wp_send_json_error('Failed to add redirect rule');
        }
    }

    /**
     * AJAX: Toggle rule active status
     */
    public function ajax_toggle() {
        check_ajax_referer('switchboard_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }

        // Validate POST data exists
        if (!isset($_POST['id'], $_POST['is_active'])) {
            wp_send_json_error('Missing required fields');
            return;
        }

        $id = intval($_POST['id']);
        $is_active = intval($_POST['is_active']);

        if ($id <= 0) {
            wp_send_json_error('Invalid rule ID');
            return;
        }

        global $wpdb;
        $result = $wpdb->update(
            $this->table_name,
            ['is_active' => $is_active],
            ['id' => $id],
            ['%d'],
            ['%d']
        );

        if ($result !== false) {
            // Clear cache immediately so changes are reflected
            $this->clear_rules_cache();
            wp_send_json_success();
        } else {
            // SECURITY FIX: Don't expose database errors to users
            error_log('Conditional Redirects Database Error (update): ' . $wpdb->last_error);
            wp_send_json_error('Failed to update rule');
        }
    }

    /**
     * OLD AJAX HANDLER - NO LONGER USED (replaced with handle_delete)
     * AJAX: Delete rule
     */
    private function OLD_ajax_delete_DEPRECATED() {
        check_ajax_referer('switchboard_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }

        // Validate POST data exists
        if (!isset($_POST['id'])) {
            wp_send_json_error('Missing required field');
            return;
        }

        $id = intval($_POST['id']);

        if ($id <= 0) {
            wp_send_json_error('Invalid rule ID');
            return;
        }

        global $wpdb;
        $result = $wpdb->delete(
            $this->table_name,
            ['id' => $id],
            ['%d']
        );

        if ($result) {
            // Clear cache immediately so changes are reflected
            $this->clear_rules_cache();
            wp_send_json_success();
        } else {
            // SECURITY FIX: Don't expose database errors to users
            error_log('Conditional Redirects Database Error (delete): ' . $wpdb->last_error);
            wp_send_json_error('Failed to delete rule');
        }
    }

    /**
     * OLD AJAX HANDLER - NO LONGER USED
     * AJAX: Get pages and posts for dropdown
     */
    private function OLD_ajax_get_pages_DEPRECATED() {
        check_ajax_referer('switchboard_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }

        $result = [];

        // Add homepage
        $result[] = [
            'title' => 'Homepage',
            'url' => home_url('/')
        ];

        // Get all pages and posts
        $posts = get_posts([
            'post_type' => ['page', 'post'],
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ]);

        foreach ($posts as $post) {
            // Skip posts with empty titles
            $title = trim($post->post_title);
            if (empty($title)) {
                $title = '(No Title - ID: ' . $post->ID . ')';
            }

            $type_label = $post->post_type === 'post' ? ' (Post)' : ' (Page)';
            $result[] = [
                'title' => esc_html($title . $type_label), // Escape HTML for safety
                'url' => esc_url(get_permalink($post->ID))
            ];
        }

        wp_send_json_success($result);
    }

    /**
     * Validate if URL is acceptable for redirect
     *
     * @param string $url URL to validate
     * @return bool True if valid, false otherwise
     */
    private function is_valid_redirect_url($url) {
        if (empty($url)) {
            return false;
        }

        // Check if it's a valid URL format
        $parsed = parse_url($url);
        if ($parsed === false) {
            return false;
        }

        // Allow internal paths (starting with /)
        if (isset($parsed['path']) && !isset($parsed['host']) && strpos($url, '/') === 0) {
            return true;
        }

        // For full URLs, require host
        if (!isset($parsed['host'])) {
            return false;
        }

        // Validate scheme
        if (isset($parsed['scheme']) && !in_array($parsed['scheme'], ['http', 'https'], true)) {
            return false;
        }

        return true;
    }

    /**
     * Detect if connection is using SSL (works behind proxies)
     *
     * @return bool True if HTTPS, false otherwise
     */
    private function is_https() {
        // Standard WordPress check
        if (is_ssl()) {
            return true;
        }

        // Check for reverse proxy headers
        if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
            strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') {
            return true;
        }

        if (isset($_SERVER['HTTP_X_FORWARDED_SSL']) &&
            strtolower($_SERVER['HTTP_X_FORWARDED_SSL']) === 'on') {
            return true;
        }

        return false;
    }

    /**
     * Check if current URL matches the source URL pattern
     *
     * @param string $current_uri Current REQUEST_URI
     * @param string $source_url Source URL pattern from rule
     * @return bool True if matches
     */
    private function check_source_url($current_uri, $source_url) {
        if (empty($source_url)) {
            return true; // Empty source URL means match all pages
        }

        $source_url = trim($source_url);
        $current_uri = trim($current_uri);

        // Remove query string from current URI for comparison
        $current_path = strtok($current_uri, '?');

        // Exact match
        if ($current_path === $source_url) {
            return true;
        }

        // Match with trailing slash normalization
        if (rtrim($current_path, '/') === rtrim($source_url, '/')) {
            return true;
        }

        // Wildcard support (e.g., /blog/*)
        if (strpos($source_url, '*') !== false) {
            // Limit source_url length to prevent ReDoS
            if (strlen($source_url) > 500) {
                return false;
            }
            // Use non-greedy matching and anchors to prevent catastrophic backtracking
            $pattern = str_replace('\*', '[^?#]*', preg_quote($source_url, '/'));
            if (preg_match('/^' . $pattern . '$/', $current_path)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Build redirect URL based on action type
     *
     * @param string $current_url Current full URL
     * @param string $action Redirect action (fixed, append, parameter)
     * @param string $value Redirect value
     * @return string|false Redirect URL or false on error
     */
    private function build_redirect_url($current_url, $action, $value) {
        if (empty($value)) {
            return false;
        }

        $value = trim($value);

        switch ($action) {
            case 'fixed':
                // Fixed URL - use as-is (can be full URL or path)
                if (strpos($value, 'http://') === 0 || strpos($value, 'https://') === 0) {
                    return $value; // External URL
                } elseif (strpos($value, '/') === 0) {
                    // Internal path - prepend site URL
                    return home_url($value);
                }
                return $value;

            case 'append':
                // Append to path - add segment to current URL path
                $parsed = parse_url($current_url);
                if ($parsed === false || !isset($parsed['scheme'], $parsed['host'])) {
                    return false;
                }

                $new_path = isset($parsed['path']) ? $parsed['path'] : '/';

                // Ensure value starts and ends with /
                $append_value = '/' . trim($value, '/') . '/';

                // Combine path with append value
                $new_path = rtrim($new_path, '/') . $append_value;

                // Rebuild URL
                $redirect = $parsed['scheme'] . '://' . $parsed['host'];
                if (isset($parsed['port']) && $parsed['port'] != 80 && $parsed['port'] != 443) {
                    $redirect .= ':' . $parsed['port'];
                }
                $redirect .= $new_path;

                // Preserve query string
                if (isset($parsed['query'])) {
                    $redirect .= '?' . $parsed['query'];
                }

                return $redirect;

            case 'parameter':
                // Add parameter - add query parameter to current URL
                $parsed = parse_url($current_url);
                if ($parsed === false || !isset($parsed['scheme'], $parsed['host'])) {
                    return false;
                }

                // Parse the parameter (format: key=value)
                if (strpos($value, '=') !== false) {
                    list($param_key, $param_value) = explode('=', $value, 2);
                } else {
                    $param_key = $value;
                    $param_value = '1';
                }

                $param_key = trim($param_key);
                $param_value = trim($param_value);

                // Parse existing query string
                $query_params = [];
                if (isset($parsed['query'])) {
                    parse_str($parsed['query'], $query_params);
                }

                // Add new parameter
                $query_params[$param_key] = $param_value;

                // Rebuild URL
                $redirect = $parsed['scheme'] . '://' . $parsed['host'];
                if (isset($parsed['port']) && $parsed['port'] != 80 && $parsed['port'] != 443) {
                    $redirect .= ':' . $parsed['port'];
                }
                if (isset($parsed['path'])) {
                    $redirect .= $parsed['path'];
                }
                $redirect .= '?' . http_build_query($query_params);

                return $redirect;

            default:
                return false;
        }
    }

    /**
     * Check conditions and redirect if matched
     * IMPORTANT: Only runs on frontend pages - never in wp-admin, AJAX, or REST API
     */
    public function check_and_redirect() {
        // Get current URL first for early detection - sanitize server vars
        $host = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : '';
        $uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';

        // FIRST CHECK: Skip for wp-admin URLs (check URI before anything else)
        if (strpos($uri, '/wp-admin') !== false ||
            strpos($uri, '/wp-login.php') !== false ||
            strpos($uri, '/wp-cron.php') !== false) {
            return;
        }

        // SECOND CHECK: Skip if is_admin() (WordPress admin area detection)
        if (is_admin()) {
            return;
        }

        // THIRD CHECK: Skip for AJAX and REST API requests
        if ((defined('DOING_AJAX') && DOING_AJAX) ||
            (defined('REST_REQUEST') && REST_REQUEST) ||
            (defined('XMLRPC_REQUEST') && XMLRPC_REQUEST)) {
            return;
        }

        // FOURTH CHECK: Skip if no host (can't determine current URL)
        if (empty($host)) {
            return;
        }

        $current_url = ($this->is_https() ? 'https://' : 'http://') . $host . $uri;

        // Try to get cached rules first
        $rules = get_transient('switchboard_conditional_redirect_rules');

        if ($rules === false) {
            global $wpdb;

            // Get all active rules ordered by priority
            // Using prepare with placeholder for is_active value
            $rules = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$this->table_name} WHERE is_active = %d ORDER BY priority ASC, id ASC",
                    1
                ),
                ARRAY_A
            );

            // Cache for 5 minutes
            if ($rules !== null) {
                set_transient('switchboard_conditional_redirect_rules', $rules ? $rules : [], 300);
            }
        }

        if (empty($rules)) {
            return;
        }

        foreach ($rules as $rule) {
            // Check source URL first (if specified)
            if (!empty($rule['source_url'])) {
                if (!$this->check_source_url($uri, $rule['source_url'])) {
                    continue; // Source URL doesn't match, skip this rule
                }
            }

            // Validate and decode conditions
            $conditions = json_decode($rule['conditions'], true);

            // Skip if JSON is invalid
            if (json_last_error() !== JSON_ERROR_NONE) {
                continue;
            }

            // Check if all enabled conditions match
            if ($this->check_conditions($conditions)) {
                $redirect_action = !empty($rule['redirect_action']) ? $rule['redirect_action'] : 'fixed';
                $redirect_value = $rule['redirect_url'];

                // For "parameter" action with URL param condition, remove the triggering param to prevent loops
                // e.g., /start/?checkout_id=xyz with "parameter" action adding coupon=save10
                // would cause infinite loop since checkout_id stays in URL
                $url_for_redirect = $current_url;
                if ($redirect_action === 'parameter' && isset($conditions['url_param']) && $conditions['url_param']['enabled']) {
                    $trigger_param = sanitize_key($conditions['url_param']['param_name']);
                    if (!empty($trigger_param)) {
                        $url_for_redirect = $this->remove_query_param($current_url, $trigger_param);
                    }
                }

                // Build redirect URL based on action
                $redirect_url = $this->build_redirect_url($url_for_redirect, $redirect_action, $redirect_value);

                if ($redirect_url === false) {
                    continue; // Invalid redirect URL
                }

                // BUG FIX: Validate URL before loop detection to avoid false positives
                // SECURITY FIX: Validate redirect URL before redirecting
                // Only allow http/https protocols
                if (!preg_match('/^https?:\/\//i', $redirect_url)) {
                    // If it's a relative URL, make it absolute
                    $redirect_url = home_url($redirect_url);
                }

                // Validate that it's a safe URL (prevents javascript:, data:, etc.)
                $validated_url = esc_url_raw($redirect_url, array('http', 'https'));
                if (empty($validated_url)) {
                    continue; // Skip invalid URLs
                }

                // Prevent redirect loops - don't redirect to the same URL
                $current_normalized = $this->normalize_url($current_url);
                $redirect_normalized = $this->normalize_url($validated_url);

                // Skip if normalization failed or URLs match
                if ($current_normalized === false || $redirect_normalized === false ||
                    $current_normalized === $redirect_normalized) {
                    continue;
                }

                // Increment hit count
                global $wpdb;
                $wpdb->query(
                    $wpdb->prepare(
                        "UPDATE {$this->table_name} SET hit_count = hit_count + 1 WHERE id = %d",
                        $rule['id']
                    )
                );

                // Perform redirect using wp_safe_redirect for internal URLs
                $redirect_type = $rule['redirect_type'] == '302' ? 302 : 301;

                // Check if it's an internal URL
                $site_host = parse_url(home_url(), PHP_URL_HOST);
                $redirect_host = parse_url($validated_url, PHP_URL_HOST);

                if ($site_host === $redirect_host) {
                    wp_safe_redirect($validated_url, $redirect_type);
                } else {
                    // External redirect - use wp_redirect but with validated URL
                    wp_redirect($validated_url, $redirect_type);
                }
                exit;
            }
        }
    }

    /**
     * Normalize URL for comparison (preserves query strings for accurate loop detection)
     *
     * @param string $url URL to normalize
     * @return string|false Normalized URL or false on failure
     */
    private function normalize_url($url) {
        if (empty($url)) {
            return false;
        }

        $parsed = parse_url($url);

        // parse_url returns false on malformed URLs
        if ($parsed === false || !isset($parsed['host'])) {
            return false;
        }

        $normalized = ($parsed['scheme'] ?? 'http') . '://';
        $normalized .= $parsed['host'];
        $normalized .= isset($parsed['path']) ? rtrim($parsed['path'], '/') : '';

        // Include sorted query string for accurate comparison
        // This allows redirects between URLs with different query params (e.g., ?checkout_id=xyz -> ?coupon=save10)
        if (isset($parsed['query']) && !empty($parsed['query'])) {
            parse_str($parsed['query'], $query_params);
            ksort($query_params); // Sort for consistent comparison
            $normalized .= '?' . http_build_query($query_params);
        }

        return strtolower($normalized);
    }

    /**
     * Remove a query parameter from a URL
     *
     * @param string $url URL to modify
     * @param string $param_to_remove Parameter name to remove
     * @return string URL without the specified parameter
     */
    private function remove_query_param($url, $param_to_remove) {
        $parsed = parse_url($url);

        if ($parsed === false || !isset($parsed['query'])) {
            return $url; // No query string, return as-is
        }

        parse_str($parsed['query'], $query_params);

        // Remove the parameter
        unset($query_params[$param_to_remove]);

        // Rebuild URL
        $rebuilt = '';
        if (isset($parsed['scheme'])) {
            $rebuilt .= $parsed['scheme'] . '://';
        }
        if (isset($parsed['host'])) {
            $rebuilt .= $parsed['host'];
        }
        if (isset($parsed['port']) && $parsed['port'] != 80 && $parsed['port'] != 443) {
            $rebuilt .= ':' . $parsed['port'];
        }
        if (isset($parsed['path'])) {
            $rebuilt .= $parsed['path'];
        }
        if (!empty($query_params)) {
            $rebuilt .= '?' . http_build_query($query_params);
        }

        return $rebuilt;
    }

    /**
     * Check if conditions match
     */
    private function check_conditions($conditions) {
        // If conditions is not an array or is empty array, match all
        if (!is_array($conditions) || count($conditions) === 0) {
            return true; // No conditions means always match
        }

        // Check browser language
        if (isset($conditions['language']) && $conditions['language']['enabled']) {
            if (!$this->check_language($conditions['language']['languages'])) {
                return false;
            }
        }

        // Check URL parameter
        if (isset($conditions['url_param']) && $conditions['url_param']['enabled']) {
            if (!$this->check_url_param($conditions['url_param']['param_name'], $conditions['url_param']['param_value'])) {
                return false;
            }
        }

        // Check referrer
        if (isset($conditions['referrer']) && $conditions['referrer']['enabled']) {
            if (!$this->check_referrer($conditions['referrer']['referrer_pattern'])) {
                return false;
            }
        }

        // Check login status
        if (isset($conditions['login_status']) && $conditions['login_status']['enabled']) {
            if (!$this->check_login_status($conditions['login_status']['status'])) {
                return false;
            }
        }

        // All conditions matched
        return true;
    }

    /**
     * Check browser language
     */
    private function check_language($languages) {
        if (empty($languages) || !is_string($languages)) {
            return false;
        }

        // Get browser language from Accept-Language header
        $accept_language = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? sanitize_text_field($_SERVER['HTTP_ACCEPT_LANGUAGE']) : '';

        if (empty($accept_language)) {
            return false;
        }

        // Parse language codes (e.g., "en, es, fr") and filter empty values
        $target_languages = array_filter(array_map('trim', explode(',', strtolower($languages))));

        if (empty($target_languages)) {
            return false;
        }

        // Parse Accept-Language header (e.g., "en-US,en;q=0.9,es;q=0.8")
        // Extract 2-letter language codes
        preg_match_all('/([a-z]{2})(?:-[a-zA-Z]{2})?/i', strtolower($accept_language), $matches);
        $browser_languages = isset($matches[1]) ? array_unique($matches[1]) : [];

        if (empty($browser_languages)) {
            return false;
        }

        // Check if any browser language matches target languages
        foreach ($browser_languages as $lang) {
            if (in_array($lang, $target_languages, true)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check URL parameter
     */
    private function check_url_param($param_name, $param_value) {
        if (empty($param_name)) {
            return false;
        }

        // Sanitize parameter name
        $param_name = sanitize_key($param_name);

        // Check if parameter exists
        if (!isset($_GET[$param_name])) {
            return false;
        }

        // Sanitize the GET parameter value
        $get_value = sanitize_text_field(wp_unslash($_GET[$param_name]));

        // If no specific value required (empty string or null), just check existence
        // Use strlen check to allow "0" as a valid value
        if ($param_value === null || $param_value === '' || strlen(trim($param_value)) === 0) {
            return strlen($get_value) > 0;
        }

        // Check if parameter value matches (case-insensitive)
        return strtolower($get_value) === strtolower(trim($param_value));
    }

    /**
     * Check referrer
     */
    private function check_referrer($pattern) {
        if (empty($pattern)) {
            return false;
        }

        // Sanitize and validate referrer
        $referrer = isset($_SERVER['HTTP_REFERER']) ? esc_url_raw($_SERVER['HTTP_REFERER']) : '';

        if (empty($referrer)) {
            return false;
        }

        // Parse referrer for better comparison
        $referrer_host = parse_url($referrer, PHP_URL_HOST);
        $site_host = parse_url(home_url(), PHP_URL_HOST);

        // Check if parsing was successful
        if ($referrer_host === false || $referrer_host === null) {
            return false;
        }

        // If referrer pattern is not the site's own domain and referrer is from own site, don't match
        // This prevents unintended redirects from internal navigation
        $pattern_lower = strtolower(trim($pattern));
        if ($site_host && $referrer_host === $site_host && stripos($pattern_lower, $site_host) === false) {
            return false;
        }

        // Check if referrer contains the pattern (case-insensitive)
        return stripos($referrer, $pattern) !== false;
    }

    /**
     * Check login status
     */
    private function check_login_status($status) {
        $is_logged_in = is_user_logged_in();

        if ($status === 'logged_in') {
            return $is_logged_in;
        } elseif ($status === 'logged_out') {
            return !$is_logged_in;
        }

        return false;
    }
}

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