<?php
/**
 * Name: Link Shortener
 * Description: Create and manage short links with analytics tracking, password protection, expiration dates, and seamless editor integration for both Classic and Gutenberg
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Shareable Marketing Links",
 *     "description": "Create memorable short URLs for social media campaigns and track click-through rates."
 *   },
 *   {
 *     "title": "Post & Page Short URLs",
 *     "description": "Generate short links directly from post editor for easy sharing and promotional materials."
 *   },
 *   {
 *     "title": "Protected Resource Links",
 *     "description": "Share password-protected download links with expiration dates for temporary access."
 *   }
 * ]
 * Added: 2025-01-21
 * Tags: links, shortener, analytics, redirect, tracking
 * WhereToFind: {
 *   "location": "Switchboard → Short Links",
 *   "url": "admin.php?page=switchboard-short-links",
 *   "instructions": "Create and manage short links. Access detailed analytics and export data. Generate links directly from post/page editor.",
 *   "newTab": false
 * }
 */

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

// Load WP_List_Table if not already loaded
if (!class_exists('WP_List_Table')) {
    require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}

/**
 * Short Links List Table
 */
class Switchboard_Short_Links_List_Table extends WP_List_Table {

    private $table_name;

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

        parent::__construct(array(
            'singular' => 'short_link',
            'plural'   => 'short_links',
            'ajax'     => false
        ));
    }

    public function get_columns() {
        return array(
            'cb'          => '<input type="checkbox" / class="sb-module-checkbox">',
            'short_code'  => __('Short Link', 'wpswitchboard'),
            'original_url' => __('Original URL', 'wpswitchboard'),
            'clicks'      => __('Clicks', 'wpswitchboard'),
            'toggle'      => __('Status', 'wpswitchboard'),
            'expires'     => __('Expires', 'wpswitchboard'),
            'created'     => __('Created', 'wpswitchboard'),
            'actions'     => __('Actions', 'wpswitchboard')
        );
    }

    public function get_sortable_columns() {
        return array(
            'short_code'  => array('short_code', false),
            'clicks'      => array('click_count', true),
            'toggle'      => array('is_active', false),
            'expires'     => array('expires_at', false),
            'created'     => array('created_at', false)
        );
    }

    public function column_cb($item) {
        return sprintf('<input type="checkbox" name="link_ids[]" value="%s" / class="sb-module-checkbox">', $item->id);
    }

    public function column_short_code($item) {
        $slug = get_option('switchboard_link_shortener_slug', 'go');
        $short_url = home_url('/' . $slug . '/' . $item->short_code);
        $short_path = '/' . $slug . '/' . $item->short_code;

        return sprintf(
            '<div style="display: flex; align-items: center; gap: 8px;">
                <code class="sb-module-code">%s</code>
                <a href="%s" target="_blank" title="%s" style="color: #64748b;">
                    <span class="dashicons dashicons-external"></span>
                </a>
            </div>',
            esc_html($short_path),
            esc_url($short_url),
            esc_attr__('Visit and test link', 'wpswitchboard')
        );
    }

    public function column_original_url($item) {
        return sprintf(
            '<code class="sb-module-code">%s</code>',
            esc_html($item->original_url)
        );
    }

    public function column_clicks($item) {
        return '<span style="font-weight: 600;">' . number_format($item->click_count ?: 0) . '</span>';
    }

    public function column_toggle($item) {
        $is_active = $item->is_active == 1;
        $is_expired = $item->expires_at && strtotime($item->expires_at) < time();

        $disabled = $is_expired ? 'disabled' : '';
        $title = $is_expired ? 'Link has expired' : 'Toggle active status';

        return sprintf(
            '<label class="sb-module-toggle" title="%s">
                <input type="checkbox" class="toggle-link-status" data-id="%s" %s %s>
                <span class="sb-module-toggle-slider"></span>
            </label>',
            esc_attr($title),
            $item->id,
            checked($is_active, true, false),
            $disabled
        );
    }

    public function column_expires($item) {
        if (!$item->expires_at) {
            return '<span class="sb-module-text-muted">' . esc_html__('Never', 'wpswitchboard') . '</span>';
        }

        $timestamp = strtotime($item->expires_at);
        $is_expired = $timestamp < time();

        if ($is_expired) {
            return '<span class="sb-module-text-muted">' . esc_html__('Expired', 'wpswitchboard') . '</span>';
        } else {
            $diff = human_time_diff($timestamp, time());
            return '<span class="sb-module-text-muted">' . esc_html($diff) . '</span>';
        }
    }

    public function column_created($item) {
        return '<span class="sb-module-text-muted">' . date('n/j/Y', strtotime($item->created_at)) . '</span>';
    }

    public function column_actions($item) {
        return sprintf(
            '<div style="display: flex; gap: 8px; align-items: center;">
                <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm edit-link" data-id="%s">%s</button>
                <button type="button" class="sb-module-button sb-module-button-danger sb-module-button-sm delete-link" data-id="%s">%s</button>
            </div>',
            esc_attr($item->id),
            esc_html__('Edit', 'wpswitchboard'),
            esc_attr($item->id),
            esc_html__('Delete', 'wpswitchboard')
        );
    }

    public function get_bulk_actions() {
        return array(
            'activate'   => 'Activate',
            'deactivate' => 'Deactivate',
            'delete'     => 'Delete'
        );
    }

    public function prepare_items() {
        global $wpdb;

        // Set column headers
        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = array($columns, $hidden, $sortable);

        $per_page = 20;
        $current_page = $this->get_pagenum();

        // Handle sorting - SECURITY FIX: Whitelist to prevent SQL injection
        $orderby_input = (!empty($_GET['orderby'])) ? sanitize_text_field($_GET['orderby']) : 'created_at';
        $order_input = (!empty($_GET['order'])) ? sanitize_text_field($_GET['order']) : 'DESC';

        // SECURITY FIX: Whitelist allowed columns
        $allowed_orderby = array('short_code', 'click_count', 'is_active', 'expires_at', 'created_at');
        $orderby = in_array($orderby_input, $allowed_orderby, true) ? $orderby_input : 'created_at';

        // SECURITY FIX: Validate order direction
        $order = strtoupper($order_input) === 'ASC' ? 'ASC' : 'DESC';

        // Handle search
        $search = isset($_REQUEST['s']) ? sanitize_text_field($_REQUEST['s']) : '';
        $where = '';
        if ($search) {
            $where = $wpdb->prepare(
                " WHERE short_code LIKE %s OR original_url LIKE %s",
                '%' . $wpdb->esc_like($search) . '%',
                '%' . $wpdb->esc_like($search) . '%'
            );
        }

        // Get total count
        $total_items = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name}{$where}");

        // Get links - SECURITY FIX: Safe because $orderby and $order are whitelisted
        $offset = ($current_page - 1) * $per_page;
        $this->items = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$this->table_name}{$where} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d",
            $per_page,
            $offset
        ));

        // Set pagination
        $this->set_pagination_args(array(
            'total_items' => $total_items,
            'per_page'    => $per_page,
            'total_pages' => ceil($total_items / $per_page)
        ));
    }
}

/**
 * Link Shortener Main Class
 */
class SwitchboardLinkShortener {

    private static $switchboard_instance = null;
    private $links_table;
    private $analytics_table;

    public static function get_instance() {
        if (null === self::$switchboard_instance) {
            self::$switchboard_instance = new self();
        }
        return self::$switchboard_instance;
    }

    private function __construct() {
        global $wpdb;
        $this->links_table = $wpdb->prefix . 'switchboard_short_links';
        $this->analytics_table = $wpdb->prefix . 'switchboard_short_links_analytics';

        // Create tables if they don't exist
        $this->maybe_create_tables();

        // Flush rewrite rules on first activation
        // Core hooks - register rewrite rules early
        // If init has already fired, call it directly
        if (did_action('init')) {
            $this->register_rewrite_rules();
        } else {
            add_action('init', array($this, 'register_rewrite_rules'), 1); // Priority 1 - very early
        }

        $this->maybe_flush_rewrite_rules();

        add_action('template_redirect', array($this, 'handle_short_link_redirect'));
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'handle_csv_export'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));

        // Editor integration
        add_action('post_submitbox_misc_actions', array($this, 'add_classic_editor_box'));
        add_action('enqueue_block_editor_assets', array($this, 'enqueue_gutenberg_assets'));
        add_action('init', array($this, 'register_post_meta'), 11);

        // AJAX handlers
        add_action('wp_ajax_switchboard_create_short_link', array($this, 'ajax_create_link'));
        add_action('wp_ajax_switchboard_update_short_link', array($this, 'ajax_update_link'));
        add_action('wp_ajax_switchboard_get_short_link', array($this, 'ajax_get_link'));
        add_action('wp_ajax_switchboard_get_all_short_links', array($this, 'ajax_get_all_links'));
        add_action('wp_ajax_switchboard_delete_short_link', array($this, 'ajax_delete_link'));
        add_action('wp_ajax_switchboard_toggle_link_status', array($this, 'ajax_toggle_status'));
        add_action('wp_ajax_switchboard_generate_post_short_link', array($this, 'ajax_generate_post_link'));
        add_action('wp_ajax_switchboard_get_link_analytics', array($this, 'ajax_get_analytics'));
        add_action('wp_ajax_switchboard_get_dashboard_stats', array($this, 'ajax_get_dashboard_stats'));
        add_action('wp_ajax_switchboard_bulk_action_short_links', array($this, 'ajax_bulk_action'));

        // Flush rewrite rules on slug change
        add_action('update_option_switchboard_link_shortener_slug', array($this, 'flush_rewrite_rules_on_slug_change'), 10, 2);

        // Debug: Uncomment to show debug info
        // add_action('admin_notices', array($this, 'show_debug_info'));

        // Handle manual flush
        add_action('admin_init', array($this, 'handle_manual_flush'));
    }

    /**
     * Flush rewrite rules on first activation or when rules are missing
     */
    private function maybe_flush_rewrite_rules() {
        // Use wp_loaded instead of init - this fires after all plugins and themes are loaded
        add_action('wp_loaded', function() {
            $slug = get_option('switchboard_link_shortener_slug', 'go');
            $rewrite_rules = get_option('rewrite_rules');
            $expected_pattern = '^' . $slug . '/([^/]+)/?$';
            $flushed_flag = get_option('switchboard_link_shortener_rewrite_flushed');

            // Check if our rewrite rule exists in the saved rules
            $rule_exists = isset($rewrite_rules[$expected_pattern]);

            // If rule doesn't exist OR flag isn't set, flush the rules
            if (!$rule_exists || !$flushed_flag) {
                flush_rewrite_rules(false); // false = soft flush, regenerates rules from scratch
                update_option('switchboard_link_shortener_rewrite_flushed', 1);
            }
        }, 10);
    }

    /**
     * Show debug info in admin (temporary for debugging)
     */
    public function show_debug_info() {
        // Only show on short links page
        if (!isset($_GET['page']) || $_GET['page'] !== 'switchboard-short-links') {
            return;
        }

        $slug = get_option('switchboard_link_shortener_slug', 'go');
        $rewrite_rules = get_option('rewrite_rules');
        $rewrite_flushed = get_option('switchboard_link_shortener_rewrite_flushed');

        global $wpdb;
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$this->links_table}'");
        $link_count = 0;
        if ($table_exists) {
            $link_count = $wpdb->get_var("SELECT COUNT(*) FROM {$this->links_table}");
        }

        $rule_exists = false;
        $expected_pattern = '^' . $slug . '/([^/]+)/?$';
        if ($rewrite_rules && isset($rewrite_rules[$expected_pattern])) {
            $rule_exists = true;
        }

        echo '<div class="notice notice-info sb-sp-group">';
        echo '<h3 class="sb-sp-heading">Link Shortener Debug Info</h3>';
        echo '<ul style="list-style:disc;margin-left:20px;">';
        echo '<li><strong>URL Slug:</strong> <code>' . esc_html($slug) . '</code></li>';
        echo '<li><strong>Expected Pattern:</strong> <code>' . esc_html($expected_pattern) . '</code></li>';
        echo '<li><strong>Rewrite Rule Registered:</strong> ' . ($rule_exists ? ' Yes' : ' No - <strong>Need to flush!</strong>') . '</li>';
        echo '<li><strong>Rewrite Flushed Option:</strong> ' . ($rewrite_flushed ? 'Yes' : 'No') . '</li>';
        echo '<li><strong>Database Table:</strong> ' . ($table_exists ? ' Exists' : ' Missing') . '</li>';
        echo '<li><strong>Total Links:</strong> ' . esc_html($link_count) . '</li>';
        echo '<li><strong>Test URL:</strong> <code>' . home_url('/' . $slug . '/test123') . '</code></li>';
        echo '</ul>';

        if (!$rule_exists) {
            echo '<p class="sb-sp-alert sb-sp-alert-success">';
            echo '<strong> Auto-fix in progress!</strong><br>';
            echo 'The rewrite rules will be automatically flushed on next page load.<br>';
            echo '<a href="' . admin_url('admin.php?page=switchboard-short-links') . '" class="button button-primary sb-sp-mt">Refresh Page to Complete Fix</a>';
            echo '</p>';
            echo '<p class="sb-sp-group">';
            echo '<strong>Manual fix options:</strong><br>';
            echo 'Go to <a href="' . admin_url('options-permalink.php') . '">Settings → Permalinks</a> and click "Save Changes"<br>';
            echo '<strong>OR</strong> <a href="' . wp_nonce_url(admin_url('admin.php?page=switchboard-short-links&flush_rewrite=1'), 'flush_rewrite_rules') . '" class="button button-small">Force Flush Now</a>';
            echo '</p>';
        } else {
            echo '<p class="sb-sp-alert sb-sp-alert-success">';
            echo '<strong> All systems operational!</strong> Short links should be working correctly.';
            echo '</p>';
        }

        echo '</div>';
    }

    /**
     * Handle manual rewrite flush from admin
     */
    public function handle_manual_flush() {
        if (isset($_GET['flush_rewrite']) && $_GET['flush_rewrite'] == '1' && isset($_GET['_wpnonce'])) {
            if (wp_verify_nonce($_GET['_wpnonce'], 'flush_rewrite_rules') && current_user_can('manage_options')) {
                delete_option('switchboard_link_shortener_rewrite_flushed');
                flush_rewrite_rules();
                wp_redirect(admin_url('admin.php?page=switchboard-short-links&flushed=1'));
                exit;
            }
        }

        // Show success notice
        if (isset($_GET['flushed']) && $_GET['flushed'] == '1') {
            add_action('admin_notices', function() {
                echo '<div class="notice notice-success is-dismissible"><p><strong> Rewrite rules flushed successfully!</strong> Try your short link now.</p></div>';
            });
        }
    }

    /**
     * Register post meta for storing short link
     */
    public function register_post_meta() {
        register_post_meta('', '_switchboard_short_link_id', array(
            'show_in_rest' => true,
            'single' => true,
            'type' => 'integer',
            'auth_callback' => function() {
                return current_user_can('edit_posts');
            }
        ));

        register_post_meta('', '_switchboard_short_link_code', array(
            'show_in_rest' => true,
            'single' => true,
            'type' => 'string',
            'auth_callback' => function() {
                return current_user_can('edit_posts');
            }
        ));
    }

    /**
     * Check and create tables if they don't exist
     */
    private function maybe_create_tables() {
        global $wpdb;
        $links_exists = $wpdb->get_var("SHOW TABLES LIKE '{$this->links_table}'");
        $analytics_exists = $wpdb->get_var("SHOW TABLES LIKE '{$this->analytics_table}'");

        if ($links_exists != $this->links_table || $analytics_exists != $this->analytics_table) {
            $this->create_tables();
        }
    }

    /**
     * Create custom tables
     */
    public function create_tables() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();

        // Short links table
        $links_sql = "CREATE TABLE IF NOT EXISTS {$this->links_table} (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            short_code varchar(255) NOT NULL,
            original_url text NOT NULL,
            password varchar(255) DEFAULT NULL,
            expires_at datetime DEFAULT NULL,
            expire_redirect_url text DEFAULT NULL,
            click_count bigint(20) UNSIGNED DEFAULT 0,
            is_active tinyint(1) DEFAULT 1,
            post_id bigint(20) UNSIGNED DEFAULT NULL,
            created_by bigint(20) UNSIGNED DEFAULT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY short_code (short_code),
            KEY post_id (post_id),
            KEY is_active (is_active),
            KEY expires_at (expires_at)
        ) $charset_collate;";

        // Analytics table
        $analytics_sql = "CREATE TABLE IF NOT EXISTS {$this->analytics_table} (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            link_id bigint(20) UNSIGNED NOT NULL,
            clicked_at datetime DEFAULT CURRENT_TIMESTAMP,
            ip_address varchar(45) DEFAULT NULL,
            user_agent text DEFAULT NULL,
            referer text DEFAULT NULL,
            PRIMARY KEY (id),
            KEY link_id (link_id),
            KEY clicked_at (clicked_at)
        ) $charset_collate;";

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

    /**
     * Register rewrite rules
     */
    public function register_rewrite_rules() {
        $slug = get_option('switchboard_link_shortener_slug', 'go');
        $pattern = '^' . $slug . '/([^/]+)/?$';
        $query = 'index.php?switchboard_short_link=$matches[1]';

        add_rewrite_rule($pattern, $query, 'top');
        add_rewrite_tag('%switchboard_short_link%', '([^&]+)');
    }

    /**
     * Flush rewrite rules when slug changes
     */
    public function flush_rewrite_rules_on_slug_change($old_value, $new_value) {
        if ($old_value !== $new_value) {
            flush_rewrite_rules();
        }
    }

    /**
     * Handle short link redirect
     */
    public function handle_short_link_redirect() {
        $short_code = get_query_var('switchboard_short_link');

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

        global $wpdb;

        // Get link from database
        $link = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$this->links_table} WHERE short_code = %s",
            $short_code
        ));

        if (!$link) {
            wp_die('Short link not found.', '404 - Not Found', array('response' => 404));
            exit;
        }

        // Check if link is active
        if ($link->is_active != 1) {
            wp_die('This short link has been disabled.', 'Link Disabled', array('response' => 403));
            exit;
        }

        // Check expiration
        if ($link->expires_at && strtotime($link->expires_at) < time()) {
            $redirect_url = $link->expire_redirect_url;

            // Use global setting if link-specific redirect not set
            if (empty($redirect_url)) {
                $redirect_url = get_option('switchboard_link_shortener_global_expire_redirect', home_url());
            }

            // SECURITY FIX: Validate redirect URL
            $redirect_url = esc_url_raw($redirect_url, array('http', 'https'));
            if (empty($redirect_url)) {
                $redirect_url = home_url();
            }

            // Track expired click
            $this->track_click($link->id);

            wp_redirect($redirect_url, 302);
            exit;
        }

        // Check password protection
        if (!empty($link->password)) {
            $this->handle_password_protection($link);
            return;
        }

        // Track click
        $this->track_click($link->id);

        // Increment counter
        $wpdb->query($wpdb->prepare(
            "UPDATE {$this->links_table} SET click_count = click_count + 1 WHERE id = %d",
            $link->id
        ));

        // SECURITY FIX: Validate original_url before redirecting
        $original_url = esc_url_raw($link->original_url, array('http', 'https'));
        if (empty($original_url)) {
            wp_die('Invalid redirect URL.', 'Error', array('response' => 500));
        }

        // Redirect
        wp_redirect($original_url, 301);
        exit;
    }

    /**
     * Handle password protection
     */
    private function handle_password_protection($link) {
        // SECURITY FIX: Use WordPress sessions/transients instead of PHP sessions
        // PHP sessions have security issues and don't work well with caching
        // We'll use a cookie-based approach with transients

        $cookie_name = 'sbsl_auth_' . $link->id;
        $cookie_value = isset($_COOKIE[$cookie_name]) ? sanitize_text_field($_COOKIE[$cookie_name]) : '';

        // Check if password already verified via cookie
        if (!empty($cookie_value)) {
            $stored_hash = get_transient('sbsl_auth_' . $link->id . '_' . $cookie_value);
            if ($stored_hash === 'verified') {
                global $wpdb;

                // Track click
                $this->track_click($link->id);

                // Increment counter
                $wpdb->query($wpdb->prepare(
                    "UPDATE {$this->links_table} SET click_count = click_count + 1 WHERE id = %d",
                    $link->id
                ));

                // SECURITY FIX: Validate URL before redirect
                $original_url = esc_url_raw($link->original_url, array('http', 'https'));
                if (empty($original_url)) {
                    wp_die('Invalid redirect URL.', 'Error', array('response' => 500));
                }

                wp_redirect($original_url, 301);
                exit;
            }
        }

        // Check submitted password
        if (isset($_POST['short_link_password']) && isset($_POST['_wpnonce'])) {
            if (wp_verify_nonce($_POST['_wpnonce'], 'verify_short_link_' . $link->id)) {
                $submitted_password = sanitize_text_field($_POST['short_link_password']);

                if (wp_check_password($submitted_password, $link->password)) {
                    // Generate random token for cookie
                    $token = wp_generate_password(32, false);

                    // Store verification in transient (1 hour)
                    set_transient('sbsl_auth_' . $link->id . '_' . $token, 'verified', HOUR_IN_SECONDS);

                    // Set cookie (1 hour)
                    setcookie($cookie_name, $token, time() + HOUR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);

                    global $wpdb;

                    // Track click
                    $this->track_click($link->id);

                    // Increment counter
                    $wpdb->query($wpdb->prepare(
                        "UPDATE {$this->links_table} SET click_count = click_count + 1 WHERE id = %d",
                        $link->id
                    ));

                    // SECURITY FIX: Validate URL before redirect
                    $original_url = esc_url_raw($link->original_url, array('http', 'https'));
                    if (empty($original_url)) {
                        wp_die('Invalid redirect URL.', 'Error', array('response' => 500));
                    }

                    wp_redirect($original_url, 301);
                    exit;
                } else {
                    $error_message = 'Incorrect password. Please try again.';
                }
            }
        }

        // Show password form
        $this->show_password_form($link, isset($error_message) ? $error_message : '');
        exit;
    }

    /**
     * Show password form
     */
    private function show_password_form($link, $error = '') {
        $slug = get_option('switchboard_link_shortener_slug', 'go');
        $short_url = home_url('/' . $slug . '/' . $link->short_code);

        wp_head();
        ?>
        <!DOCTYPE html>
        <html <?php language_attributes(); ?>>
        <head>
            <meta charset="<?php bloginfo('charset'); ?>">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>Password Protected Link</title>
            <style>
                * { margin: 0; padding: 0; box-sizing: border-box; }
                body {
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, sans-serif;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    min-height: 100vh;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding: 20px;
                }
                .password-container {
                    background: white;
                    border-radius: 12px;
                    box-shadow: 0 20px 60px rgba(0,0,0,0.3);
                    padding: 40px;
                    max-width: 450px;
                    width: 100%;
                    text-align: center;
                }
                .lock-icon {
                    font-size: 48px;
                    margin-bottom: 20px;
                }
                h1 {
                    font-size: 24px;
                    color: #1f2937;
                    margin-bottom: 12px;
                }
                p {
                    color: #6b7280;
                    margin-bottom: 30px;
                    line-height: 1.6;
                }
                .error-message {
                    background: #fef2f2;
                    border: 1px solid #fecaca;
                    color: #dc2626;
                    padding: 12px;
                    border-radius: 6px;
                    margin-bottom: 20px;
                    font-size: 14px;
                }
                input[type="password"] {
                    width: 100%;
                    padding: 14px 16px;
                    border: 2px solid #e5e7eb;
                    border-radius: 8px;
                    font-size: 16px;
                    margin-bottom: 16px;
                    transition: border-color 0.2s;
                }
                input[type="password"]:focus {
                    outline: none;
                    border-color: var(--primary-500);
                }
                button {
                    width: 100%;
                    padding: 14px 16px;
                    background: var(--primary-500);
                    color: white;
                    border: none;
                    border-radius: 8px;
                    font-size: 16px;
                    font-weight: 600;
                    cursor: pointer;
                    transition: background 0.2s;
                }
                button:hover {
                    background: var(--primary-600);
                }
                .short-link {
                    margin-top: 24px;
                    padding-top: 24px;
                    border-top: 1px solid #e5e7eb;
                    font-size: 13px;
                    color: #9ca3af;
                    word-break: break-all;
                }
            </style>
        </head>
        <body>
            <div class="password-container">
                <div class="lock-icon"><span class="dashicons dashicons-lock" style="font-size: 48px; width: 48px; height: 48px;"></span></div>
                <h1>Password Required</h1>
                <p>This short link is password protected. Please enter the password to continue.</p>

                <?php if ($error): ?>
                    <div class="error-message"><?php echo esc_html($error); ?></div>
                <?php endif; ?>

                <form method="post">
                    <?php wp_nonce_field('verify_short_link_' . $link->id); ?>
                    <input
                        type="password"
                        name="short_link_password"
                        placeholder="Enter password"
                        required
                        autofocus
                     class="sb-module-input">
                    <button type="submit">Unlock Link</button>
                </form>

                <div class="short-link">
                    <?php echo esc_html($short_url); ?>
                </div>
            </div>
        </body>
        </html>
        <?php
        wp_footer();
    }

    /**
     * Track click analytics
     */
    private function track_click($link_id) {
        global $wpdb;

        $ip_address = $this->get_client_ip();
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : '';
        $referer = isset($_SERVER['HTTP_REFERER']) ? esc_url_raw($_SERVER['HTTP_REFERER']) : '';

        $wpdb->insert(
            $this->analytics_table,
            array(
                'link_id' => $link_id,
                'ip_address' => $ip_address,
                'user_agent' => $user_agent,
                'referer' => $referer
            ),
            array('%d', '%s', '%s', '%s')
        );
    }

    /**
     * Get client IP address
     */
    private function get_client_ip() {
        $ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');

        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip);
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                        return $ip;
                    }
                }
            }
        }

        return isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field($_SERVER['REMOTE_ADDR']) : '';
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_submenu_page(
            'switchboard',
            'Short Links',
            'Short Links',
            'manage_options',
            'switchboard-short-links',
            array($this, 'render_admin_page')
        );
    }

    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets($hook) {
        // Check if we're on the short links page (check both hook and GET parameter)
        $is_short_links_page = (
            (isset($_GET['page']) && $_GET['page'] === 'switchboard-short-links') ||
            strpos($hook, 'switchboard-short-links') !== false ||
            $hook === 'post.php' ||
            $hook === 'post-new.php'
        );

        if (!$is_short_links_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
            );
        }

        // Ensure jQuery is loaded
        wp_enqueue_script('jquery');
    }

    /**
     * Render admin page
     */
    public function render_admin_page() {
        $current_view = isset($_GET['view']) ? sanitize_text_field($_GET['view']) : 'dashboard';

        // Handle bulk actions
        if (isset($_POST['action']) && isset($_POST['link_ids']) && !empty($_POST['link_ids'])) {
            check_admin_referer('bulk-short_links');
            $this->handle_bulk_action($_POST['action'], $_POST['link_ids']);
        }

        // Handle single delete action
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['link_id'])) {
            if (check_admin_referer('delete_link_' . intval($_GET['link_id']))) {
                $this->delete_link(intval($_GET['link_id']));
                echo '<div class="notice notice-success"><p>Short link deleted successfully.</p></div>';
            }
        }

        ?>
        <div class="wrap sb-module-wrap">
            <!-- Header -->
            <div class="sb-module-header">
                <div class="sb-module-header-left">
                    <svg class="sb-module-title-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path>
                    </svg>
                    <div>
                        <h1 class="sb-module-title">
                            <?php esc_html_e('Short Links', 'wpswitchboard'); ?>
                            <span class="switchboard-badge">SWITCHBOARD</span>
                        </h1>
                        <p class="sb-module-subtitle"><?php esc_html_e('Create and manage short links with analytics, passwords, and expiration dates', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-header-right">
                    <a href="https://docs.wpswitchboard.com/modules/utilities/link-shortener" target="_blank" class="sb-module-help-link">
                        <span class="sb-module-help-link-icon dashicons dashicons-editor-help"></span>
                        Help
                    </a>
                    <?php if ($current_view === 'settings'): ?>
                        <a href="<?php echo admin_url('admin.php?page=switchboard-short-links'); ?>" class="sb-module-button sb-module-button-secondary">
                            <?php esc_html_e('Go Back', 'wpswitchboard'); ?>
                        </a>
                    <?php else: ?>
                        <a href="<?php echo admin_url('admin.php?page=switchboard-short-links&view=settings'); ?>" class="sb-module-button sb-module-button-secondary">
                            <?php esc_html_e('Settings', 'wpswitchboard'); ?>
                        </a>
                        <button type="button" id="add-new-link-btn" class="sb-module-button sb-module-button-primary">
                            <?php esc_html_e('Add New Link', 'wpswitchboard'); ?>
                        </button>
                    <?php endif; ?>
                </div>
            </div>

            <?php
            switch ($current_view) {
                case 'all-links':
                    $this->render_all_links_view();
                    break;
                case 'settings':
                    $this->render_settings_view();
                    break;
                default:
                    $this->render_dashboard_view();
                    break;
            }
            ?>
        </div>

        <?php $this->render_modals(); ?>
        <?php $this->render_scripts(); ?>
        <?php
    }

    /**
     * Render dashboard view
     */
    private function render_dashboard_view() {
        global $wpdb;

        // Get stats
        $total_links = $wpdb->get_var("SELECT COUNT(*) FROM {$this->links_table}");
        $active_links = $wpdb->get_var("SELECT COUNT(*) FROM {$this->links_table} WHERE is_active = 1");
        $total_clicks = $wpdb->get_var("SELECT SUM(click_count) FROM {$this->links_table}");
        $clicks_today = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$this->analytics_table} WHERE DATE(clicked_at) = %s",
            current_time('Y-m-d')
        ));

        // Get top links
        $top_links = $wpdb->get_results("SELECT * FROM {$this->links_table} WHERE click_count > 0 ORDER BY click_count DESC LIMIT 5");

        // Get recent links
        $recent_links = $wpdb->get_results("SELECT * FROM {$this->links_table} ORDER BY created_at DESC LIMIT 5");

        ?>
        <div class="sb-module-container">
            <!-- Stats Cards -->
            <div class="sb-module-stats">
                <div class="sb-module-stat-card">
                    <div class="sb-module-stat-label"><?php esc_html_e('Total Links', 'wpswitchboard'); ?></div>
                    <div class="sb-module-stat-content">
                        <div class="sb-module-stat-value"><?php echo number_format($total_links); ?></div>
                    </div>
                </div>

                <div class="sb-module-stat-card">
                    <div class="sb-module-stat-label"><?php esc_html_e('Active Links', 'wpswitchboard'); ?></div>
                    <div class="sb-module-stat-content">
                        <div class="sb-module-stat-value"><?php echo number_format($active_links); ?></div>
                    </div>
                </div>

                <div class="sb-module-stat-card">
                    <div class="sb-module-stat-label"><?php esc_html_e('Total Clicks', 'wpswitchboard'); ?></div>
                    <div class="sb-module-stat-content">
                        <div class="sb-module-stat-value"><?php echo number_format($total_clicks ?: 0); ?></div>
                    </div>
                </div>

                <div class="sb-module-stat-card">
                    <div class="sb-module-stat-label"><?php esc_html_e('Clicks Today', 'wpswitchboard'); ?></div>
                    <div class="sb-module-stat-content">
                        <div class="sb-module-stat-value"><?php echo number_format($clicks_today ?: 0); ?></div>
                    </div>
                </div>
            </div>

            <!-- Two Column Layout -->
            <div class="sb-module-layout-2col">
                <!-- Top Links -->
                <div class="sb-module-card">
                    <div class="sb-module-card-header">
                        <div class="sb-module-card-header-left">
                            <h2 class="sb-module-card-title"><?php esc_html_e('Top Performing Links', 'wpswitchboard'); ?></h2>
                            <p class="sb-module-card-desc"><?php esc_html_e('Links with the most clicks', 'wpswitchboard'); ?></p>
                        </div>
                    </div>
                    <div class="sb-module-card-body sb-module-table-wrapper">
                        <?php if (!empty($top_links)): ?>
                            <table class="sb-module-table">
                                <thead>
                                    <tr>
                                        <th><?php esc_html_e('Short Code', 'wpswitchboard'); ?></th>
                                        <th><?php esc_html_e('Clicks', 'wpswitchboard'); ?></th>
                                        <th><?php esc_html_e('Created', 'wpswitchboard'); ?></th>
                                        <th><?php esc_html_e('Action', 'wpswitchboard'); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($top_links as $link):
                                        $slug = get_option('switchboard_link_shortener_slug', 'go');
                                        $short_url = home_url('/' . $slug . '/' . $link->short_code);
                                    ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo esc_html($link->short_code); ?></strong><br>
                                                <span class="sb-module-text-muted sb-module-text-sm"><?php echo esc_html(substr($link->original_url, 0, 50)) . (strlen($link->original_url) > 50 ? '...' : ''); ?></span>
                                            </td>
                                            <td><strong class="sb-module-text-semibold" style="color:var(--primary-500);"><?php echo number_format($link->click_count); ?></strong></td>
                                            <td><?php echo human_time_diff(strtotime($link->created_at), time()) . ' ago'; ?></td>
                                            <td>
                                                <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm copy-link-btn" data-url="<?php echo esc_attr($short_url); ?>">
                                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width: 16px; height: 16px; display: inline-flex;">
                                                        <path stroke-linecap="round" stroke-linejoin="round" d="M15.666 3.888A2.25 2.25 0 0 0 13.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 0 1-.75.75H9a.75.75 0 0 1-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 0 1-2.25 2.25H6.75A2.25 2.25 0 0 1 4.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 0 1 1.927-.184" />
                                                    </svg>
                                                    <?php esc_html_e('Copy', 'wpswitchboard'); ?>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php else: ?>
                            <div class="sb-module-empty">
                                <div class="sb-module-empty-icon"></div>
                                <h2 class="sb-module-empty-title"><?php esc_html_e('No Links Yet', 'wpswitchboard'); ?></h2>
                                <p class="sb-module-empty-desc"><?php esc_html_e('No links with clicks yet. Create your first short link!', 'wpswitchboard'); ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Recent Links -->
                <div class="sb-module-card">
                    <div class="sb-module-card-header">
                        <div class="sb-module-card-header-left">
                            <h2 class="sb-module-card-title"><?php esc_html_e('Recently Created Links', 'wpswitchboard'); ?></h2>
                            <p class="sb-module-card-desc"><?php esc_html_e('Latest short links added', 'wpswitchboard'); ?></p>
                        </div>
                    </div>
                    <div class="sb-module-card-body sb-module-table-wrapper">
                        <?php if (!empty($recent_links)): ?>
                            <table class="sb-module-table">
                                <thead>
                                    <tr>
                                        <th><?php esc_html_e('Short Code', 'wpswitchboard'); ?></th>
                                        <th><?php esc_html_e('Clicks', 'wpswitchboard'); ?></th>
                                        <th><?php esc_html_e('Created', 'wpswitchboard'); ?></th>
                                        <th><?php esc_html_e('Action', 'wpswitchboard'); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recent_links as $link):
                                        $slug = get_option('switchboard_link_shortener_slug', 'go');
                                        $short_url = home_url('/' . $slug . '/' . $link->short_code);
                                    ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo esc_html($link->short_code); ?></strong><br>
                                                <span class="sb-module-text-muted sb-module-text-sm"><?php echo esc_html(substr($link->original_url, 0, 50)) . (strlen($link->original_url) > 50 ? '...' : ''); ?></span>
                                            </td>
                                            <td><strong class="sb-module-text-semibold" style="color:var(--primary-500);"><?php echo number_format($link->click_count); ?></strong></td>
                                            <td><?php echo human_time_diff(strtotime($link->created_at), time()) . ' ago'; ?></td>
                                            <td>
                                                <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm copy-link-btn" data-url="<?php echo esc_attr($short_url); ?>">
                                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width: 16px; height: 16px; display: inline-flex;">
                                                        <path stroke-linecap="round" stroke-linejoin="round" d="M15.666 3.888A2.25 2.25 0 0 0 13.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 0 1-.75.75H9a.75.75 0 0 1-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 0 1-2.25 2.25H6.75A2.25 2.25 0 0 1 4.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 0 1 1.927-.184" />
                                                    </svg>
                                                    <?php esc_html_e('Copy', 'wpswitchboard'); ?>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php else: ?>
                            <div class="sb-module-empty">
                                <div class="sb-module-empty-icon"></div>
                                <h2 class="sb-module-empty-title"><?php esc_html_e('No Links Yet', 'wpswitchboard'); ?></h2>
                                <p class="sb-module-empty-desc"><?php esc_html_e('No links created yet. Create your first short link!', 'wpswitchboard'); ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- All Short Links Table -->
            <div class="sb-module-card" style="margin-top: 24px; margin-bottom: 50px;">
                <div class="sb-module-card-header">
                    <div class="sb-module-card-header-left">
                        <h2 class="sb-module-card-title"><?php esc_html_e('All Short Links', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Complete list of all short links with search and filtering', 'wpswitchboard'); ?></p>
                    </div>
                    <div class="sb-module-card-header-right">
                        <select name="action" id="bulk-action-selector-top" class="sb-module-select" style="min-width: 150px;">
                            <option value="-1"><?php esc_html_e('Bulk Actions', 'wpswitchboard'); ?></option>
                            <option value="delete"><?php esc_html_e('Delete', 'wpswitchboard'); ?></option>
                            <option value="activate"><?php esc_html_e('Activate', 'wpswitchboard'); ?></option>
                            <option value="deactivate"><?php esc_html_e('Deactivate', 'wpswitchboard'); ?></option>
                        </select>
                        <button type="button" id="doaction-links" class="sb-module-button sb-module-button-secondary sb-module-button-sm"><?php esc_html_e('Apply', 'wpswitchboard'); ?></button>
                    </div>
                </div>
                <div class="sb-module-card-body" style="padding: 0;">
                    <div class="sb-module-table-wrapper">
                        <table class="sb-module-table" id="short-links-table">
                            <thead>
                                <tr>
                                    <th style="width: 40px;">
                                        <input type="checkbox" id="cb-select-all-links" class="sb-module-checkbox">
                                    </th>
                                    <th class="sortable" data-column="short_code" style="width: 20%;">
                                        <?php esc_html_e('Short Link', 'wpswitchboard'); ?> <span class="sort-indicator"></span>
                                    </th>
                                    <th class="sortable" data-column="original_url" style="width: 25%;">
                                        <?php esc_html_e('Original URL', 'wpswitchboard'); ?> <span class="sort-indicator"></span>
                                    </th>
                                    <th class="sortable" data-column="click_count" style="width: 8%;">
                                        <?php esc_html_e('Clicks', 'wpswitchboard'); ?> <span class="sort-indicator"></span>
                                    </th>
                                    <th style="width: 10%;"><?php esc_html_e('Status', 'wpswitchboard'); ?></th>
                                    <th class="sortable" data-column="expires_at" style="width: 10%;">
                                        <?php esc_html_e('Expires', 'wpswitchboard'); ?> <span class="sort-indicator"></span>
                                    </th>
                                    <th class="sortable" data-column="created_at" style="width: 12%;">
                                        <?php esc_html_e('Created', 'wpswitchboard'); ?> <span class="sort-indicator"></span>
                                    </th>
                                    <th style="width: 15%;"><?php esc_html_e('Actions', 'wpswitchboard'); ?></th>
                                </tr>
                            </thead>
                            <tbody id="short-links-tbody">
                                <tr>
                                    <td colspan="8" class="sb-module-empty">
                                        <div class="sb-module-empty-icon"><span class="dashicons dashicons-clock"></span></div>
                                        <p class="sb-module-empty-desc"><?php esc_html_e('Loading links...', 'wpswitchboard'); ?></p>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render all links view
     */
    private function render_all_links_view() {
        global $wpdb;
        
        // Get pagination and sorting
        $per_page = 20;
        $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        $orderby = isset($_GET['orderby']) ? sanitize_text_field($_GET['orderby']) : 'created_at';
        $order = isset($_GET['order']) && strtoupper($_GET['order']) === 'ASC' ? 'ASC' : 'DESC';
        $search = isset($_REQUEST['s']) ? sanitize_text_field($_REQUEST['s']) : '';
        
        // Build WHERE clause
        $where = '';
        if ($search) {
            $where = $wpdb->prepare(
                " WHERE short_code LIKE %s OR original_url LIKE %s",
                '%' . $wpdb->esc_like($search) . '%',
                '%' . $wpdb->esc_like($search) . '%'
            );
        }
        
        // Get total count
        $total_items = $wpdb->get_var("SELECT COUNT(*) FROM {$this->links_table}{$where}");
        $total_pages = ceil($total_items / $per_page);
        
        // Get links
        $offset = ($current_page - 1) * $per_page;
        $links = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$this->links_table}{$where} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d",
            $per_page,
            $offset
        ));
        
        $slug = get_option('switchboard_link_shortener_slug', 'go');
        ?>
        <div class="sb-module-container">
            <div class="sb-module-card">
                <div class="sb-module-card-header">
                    <div class="sb-module-card-header-left">
                        <h2 class="sb-module-card-title"><?php esc_html_e('All Short Links', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Manage all your short links with advanced search and sorting', 'wpswitchboard'); ?></p>
                    </div>
                    <div class="sb-module-card-header-right">
                        <form method="get" action="" style="display: flex; gap: 8px; align-items: center;">
                            <input type="hidden" name="page" value="switchboard-short-links">
                            <input type="hidden" name="view" value="all-links">
                            <input type="search" name="s" id="short-links-search" class="sb-module-search-input" placeholder="<?php esc_attr_e('Search links...', 'wpswitchboard'); ?>" style="min-width: 250px;" value="<?php echo esc_attr($search); ?>">
                            <button type="submit" class="sb-module-button sb-module-button-primary sb-module-button-sm">
                                <?php esc_html_e('Search', 'wpswitchboard'); ?>
                            </button>
                            <?php if (!empty($search)): ?>
                                <a href="<?php echo esc_url(remove_query_arg('s')); ?>" class="sb-module-button sb-module-button-secondary sb-module-button-sm">
                                    <?php esc_html_e('Clear', 'wpswitchboard'); ?>
                                </a>
                            <?php endif; ?>
                        </form>
                        <select name="action" id="bulk-action-selector-top" class="sb-module-select" style="min-width: 150px;">
                            <option value="-1"><?php esc_html_e('Bulk Actions', 'wpswitchboard'); ?></option>
                            <option value="activate"><?php esc_html_e('Activate', 'wpswitchboard'); ?></option>
                            <option value="deactivate"><?php esc_html_e('Deactivate', 'wpswitchboard'); ?></option>
                            <option value="delete"><?php esc_html_e('Delete', 'wpswitchboard'); ?></option>
                        </select>
                        <button type="button" id="doaction" class="sb-module-button sb-module-button-secondary sb-module-button-sm"><?php esc_html_e('Apply', 'wpswitchboard'); ?></button>
                    </div>
                </div>
                <div class="sb-module-card-body" style="padding: 0;">
                    <div class="sb-module-table-wrapper">
                        <form method="get" id="short-links-form">
                            <input type="hidden" name="page" value="switchboard-short-links">
                            <input type="hidden" name="view" value="all-links">
                            <?php if (!empty($search)): ?>
                                <input type="hidden" name="s" value="<?php echo esc_attr($search); ?>">
                            <?php endif; ?>
                            <table class="sb-module-table" id="short-links-table">
                                <thead>
                                    <tr>
                                        <th style="width: 40px;">
                                            <input type="checkbox" id="cb-select-all" class="sb-module-checkbox">
                                        </th>
                                        <th class="sortable" data-column="short_code" style="width: 25%;">
                                            <?php esc_html_e('Short Link', 'wpswitchboard'); ?> <span class="sort-indicator"></span>
                                        </th>
                                        <th class="sortable" data-column="original_url" style="width: 25%;">
                                            <?php esc_html_e('Original URL', 'wpswitchboard'); ?> <span class="sort-indicator"></span>
                                        </th>
                                        <th class="sortable" data-column="click_count" style="width: 8%;">
                                            <?php esc_html_e('Clicks', 'wpswitchboard'); ?> <span class="sort-indicator"></span>
                                        </th>
                                        <th style="width: 10%;"><?php esc_html_e('Status', 'wpswitchboard'); ?></th>
                                        <th class="sortable" data-column="expires_at" style="width: 10%;">
                                            <?php esc_html_e('Expires', 'wpswitchboard'); ?> <span class="sort-indicator"></span>
                                        </th>
                                        <th class="sortable" data-column="created_at" style="width: 12%;">
                                            <?php esc_html_e('Created', 'wpswitchboard'); ?> <span class="sort-indicator"></span>
                                        </th>
                                        <th style="width: 10%;"><?php esc_html_e('Actions', 'wpswitchboard'); ?></th>
                                    </tr>
                                </thead>
                                <tbody id="short-links-tbody">
                                    <?php if (!empty($links)): ?>
                                        <?php foreach ($links as $link):
                                            $short_url = home_url('/' . $slug . '/' . $link->short_code);
                                            $is_expired = $link->expires_at && strtotime($link->expires_at) < time();
                                        ?>
                                            <tr class="<?php echo $is_expired ? 'sb-module-row-expired' : ''; ?>">
                                                <td style="width: 40px;">
                                                    <input type="checkbox" name="link_ids[]" value="<?php echo esc_attr($link->id); ?>" class="sb-module-checkbox link-checkbox">
                                                </td>
                                                <td>
                                                    <div style="display: flex; align-items: center; gap: 8px;">
                                                        <code class="sb-module-code"><?php echo esc_html('/' . $slug . '/' . $link->short_code); ?></code>
                                                        <a href="<?php echo esc_url($short_url); ?>" target="_blank" title="<?php esc_attr_e('Visit and test link', 'wpswitchboard'); ?>" style="color: #64748b;">
                                                            <span class="dashicons dashicons-external"></span>
                                                        </a>
                                                    </div>
                                                </td>
                                                <td>
                                                    <code class="sb-module-code"><?php echo esc_html($link->original_url); ?></code>
                                                </td>
                                                <td style="font-weight: 600;"><?php echo number_format($link->click_count); ?></td>
                                                <td>
                                                    <label class="sb-module-toggle<?php echo $is_expired ? ' sb-module-toggle-expired' : ''; ?>"<?php echo $is_expired ? ' title="' . esc_attr__('Link has expired', 'wpswitchboard') . '"' : ''; ?>>
                                                        <input type="checkbox" class="toggle-link-status" data-id="<?php echo esc_attr($link->id); ?>" <?php checked($link->is_active, 1); ?><?php echo $is_expired ? ' disabled' : ''; ?>>
                                                        <span class="sb-module-toggle-slider"></span>
                                                    </label>
                                                </td>
                                                <td>
                                                    <?php if (!$link->expires_at): ?>
                                                        <span class="sb-module-text-muted"><?php esc_html_e('Never', 'wpswitchboard'); ?></span>
                                                    <?php elseif ($is_expired): ?>
                                                        <span class="sb-module-text-muted" title="<?php echo esc_attr(sprintf(__('Expired on %s', 'wpswitchboard'), date('n/j/Y', strtotime($link->expires_at)))); ?>" style="cursor: help;"><?php esc_html_e('Expired', 'wpswitchboard'); ?></span>
                                                    <?php else: ?>
                                                        <span class="sb-module-text-muted" title="<?php echo esc_attr(sprintf(__('Expires on %s', 'wpswitchboard'), date('n/j/Y', strtotime($link->expires_at)))); ?>" style="cursor: help;"><?php echo esc_html(human_time_diff(strtotime($link->expires_at), time())); ?></span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="sb-module-text-muted"><?php echo esc_html(date('n/j/Y', strtotime($link->created_at))); ?></td>
                                                <td>
                                                    <div style="display: flex; gap: 8px; align-items: center;">
                                                        <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm edit-link" data-id="<?php echo esc_attr($link->id); ?>"><?php esc_html_e('Edit', 'wpswitchboard'); ?></button>
                                                        <button type="button" class="sb-module-button sb-module-button-danger sb-module-button-sm delete-link" data-id="<?php echo esc_attr($link->id); ?>" data-url="<?php echo esc_attr(wp_nonce_url(admin_url('admin.php?page=switchboard-short-links&action=delete&link_id=' . $link->id), 'delete_link_' . $link->id)); ?>"><?php esc_html_e('Delete', 'wpswitchboard'); ?></button>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="8" class="sb-module-empty">
                                                <div class="sb-module-empty-icon"></div>
                                                <p class="sb-module-empty-desc"><?php esc_html_e('No short links found', 'wpswitchboard'); ?></p>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </form>
                    </div>
                </div>
                <?php if (!empty($links)): ?>
                    <div class="sb-module-card-footer">
                        <span style="color: #64748b; font-size: 14px; font-weight: 500; display: flex; align-items: center;">
                            <?php
                            $start = ($current_page - 1) * $per_page + 1;
                            $end = min($current_page * $per_page, $total_items);
                            printf(
                                esc_html__('Showing %1$d-%2$d of %3$d links', 'wpswitchboard'),
                                $start,
                                $end,
                                $total_items
                            );
                            ?>
                        </span>
                        <div style="display: flex; gap: 8px; align-items: center;">
                            <?php
                            $base_url = remove_query_arg(['paged', 's']);
                            if ($current_page > 1):
                                $prev_url = add_query_arg(['paged' => $current_page - 1], $base_url);
                                if ($search) {
                                    $prev_url = add_query_arg('s', $search, $prev_url);
                                }
                            ?>
                                <a href="<?php echo esc_url($prev_url); ?>" class="sb-module-button sb-module-button-secondary sb-module-button-sm">
                                    <?php esc_html_e('Previous', 'wpswitchboard'); ?>
                                </a>
                            <?php else: ?>
                                <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm" disabled>
                                    <?php esc_html_e('Previous', 'wpswitchboard'); ?>
                                </button>
                            <?php endif; ?>
                            <?php if ($current_page < $total_pages): ?>
                                <?php
                                $next_url = add_query_arg(['paged' => $current_page + 1], $base_url);
                                if ($search) {
                                    $next_url = add_query_arg('s', $search, $next_url);
                                }
                                ?>
                                <a href="<?php echo esc_url($next_url); ?>" class="sb-module-button sb-module-button-secondary sb-module-button-sm">
                                    <?php esc_html_e('Next', 'wpswitchboard'); ?>
                                </a>
                            <?php else: ?>
                                <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm" disabled>
                                    <?php esc_html_e('Next', 'wpswitchboard'); ?>
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }

    /**
     * Render settings view
     */
    private function render_settings_view() {
        $settings_saved = false;
        $slug_changed = false;

        // Handle settings save
        if (isset($_POST['save_shortener_settings']) && check_admin_referer('save_shortener_settings')) {
            $old_slug = get_option('switchboard_link_shortener_slug', 'go');
            $new_slug = sanitize_title($_POST['slug']);

            update_option('switchboard_link_shortener_slug', $new_slug);
            update_option('switchboard_link_shortener_default_length', intval($_POST['default_length']));

            // Sanitize global password (stored as plain text template, hashed when copied to individual links)
            // Note: Individual link passwords are hashed in create/update AJAX handlers (lines 2539, 2596)
            $global_password = isset($_POST['global_password']) ? sanitize_text_field($_POST['global_password']) : '';
            update_option('switchboard_link_shortener_global_password', $global_password);

            update_option('switchboard_link_shortener_global_expire_redirect', esc_url_raw($_POST['global_expire_redirect']));

            $settings_saved = true;

            // Check if slug changed
            if ($new_slug !== $old_slug) {
                $slug_changed = true;
            }
        }

        $slug = get_option('switchboard_link_shortener_slug', 'go');
        $default_length = get_option('switchboard_link_shortener_default_length', 6);
        $global_password = get_option('switchboard_link_shortener_global_password', '');
        $global_expire_redirect = get_option('switchboard_link_shortener_global_expire_redirect', home_url());

        ?>
        <div class="sb-module-container">
            <?php if ($settings_saved): ?>
                <div class="sb-sp-alert sb-sp-alert-success" style="margin-bottom: 20px;">
                     <?php esc_html_e('Settings saved successfully.', 'wpswitchboard'); ?>
                </div>
            <?php endif; ?>

            <form method="post">
                <?php wp_nonce_field('save_shortener_settings'); ?>
                <div class="sb-module-card">
                    <div class="sb-module-card-header">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Settings', 'wpswitchboard'); ?></h2>
                    </div>
                    <div class="sb-module-card-body">
                        <div class="sb-sp-field-horizontal" style="margin-bottom: 24px;">
                            <div class="sb-sp-field-horizontal-left">
                                <label for="slug" class="sb-sp-label">
                                    <?php esc_html_e('URL Slug', 'wpswitchboard'); ?>
                                    <span class="sb-module-required">*</span>
                                </label>
                                <p class="sb-sp-description">
                                    <?php esc_html_e('Example:', 'wpswitchboard'); ?> <code><?php echo home_url('/' . $slug . '/abc123'); ?></code>
                                </p>
                            </div>
                            <input type="text" id="slug" name="slug" value="<?php echo esc_attr($slug); ?>" class="sb-module-input" required>
                        </div>

                        <div class="sb-sp-field-horizontal" style="margin-bottom: 24px;">
                            <div class="sb-sp-field-horizontal-left">
                                <label for="default_length" class="sb-sp-label">
                                    <?php esc_html_e('Default Code Length', 'wpswitchboard'); ?>
                                    <span class="sb-module-required">*</span>
                                </label>
                                <p class="sb-sp-description"><?php esc_html_e('Characters in auto-generated codes (4-12)', 'wpswitchboard'); ?></p>
                            </div>
                            <input type="number" id="default_length" name="default_length" value="<?php echo esc_attr($default_length); ?>" class="sb-module-input" min="4" max="12" required style="width: 150px;">
                        </div>

                        <div class="sb-sp-field-horizontal" style="margin-bottom: 24px;">
                            <div class="sb-sp-field-horizontal-left">
                                <label for="global_password" class="sb-sp-label"><?php esc_html_e('Default Password', 'wpswitchboard'); ?></label>
                                <p class="sb-sp-description"><?php esc_html_e('Default password for new links (optional)', 'wpswitchboard'); ?></p>
                            </div>
                            <input type="text" id="global_password" name="global_password" value="<?php echo esc_attr($global_password); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('Leave empty for no password', 'wpswitchboard'); ?>">
                        </div>

                        <div class="sb-sp-field-horizontal" style="margin-bottom: 24px;">
                            <div class="sb-sp-field-horizontal-left">
                                <label for="global_expire_redirect" class="sb-sp-label">
                                    <?php esc_html_e('Expiration Redirect', 'wpswitchboard'); ?>
                                    <span class="sb-module-required">*</span>
                                </label>
                                <p class="sb-sp-description"><?php esc_html_e('Where to redirect expired links', 'wpswitchboard'); ?></p>
                            </div>
                            <input type="url" id="global_expire_redirect" name="global_expire_redirect" value="<?php echo esc_attr($global_expire_redirect); ?>" class="sb-module-input" required>
                        </div>
                    </div>
                    <div class="sb-module-card-footer">
                        <div style="display: flex; justify-content: flex-end;">
                            <button type="submit" name="save_shortener_settings" class="sb-module-button sb-module-button-primary">
                                <?php esc_html_e('Save Settings', 'wpswitchboard'); ?>
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <?php
    }

    /**
     * Render modals
     */
    private function render_modals() {
        ?>
        <!-- Add/Edit Link Modal -->
        <div id="link-modal" class="sb-module-modal" style="display:none;">
            <div class="sb-module-modal-backdrop"></div>
            <div class="sb-module-modal-content sb-module-modal-md">
                <div class="sb-module-modal-header">
                    <h2 id="modal-title" class="sb-module-modal-title"><?php esc_html_e('Add New Short Link', 'wpswitchboard'); ?></h2>
                    <button type="button" class="sb-module-modal-close modal-close">&times;</button>
                </div>
                <div class="sb-module-modal-body">
                    <form id="link-form">
                        <input type="hidden" id="link-id" name="link_id">

                        <div class="sb-sp-field-horizontal" style="margin-bottom: 16px;">
                            <div class="sb-sp-field-horizontal-left">
                                <label for="original-url" class="sb-sp-label">
                                    <?php esc_html_e('Original URL', 'wpswitchboard'); ?>
                                    <span class="sb-module-required">*</span>
                                </label>
                                <p class="sb-sp-description"><?php esc_html_e('The full URL to redirect to', 'wpswitchboard'); ?></p>
                            </div>
                            <input type="url" id="original-url" name="original_url" required placeholder="https://example.com/page" class="sb-module-input">
                        </div>

                        <div class="sb-sp-field-horizontal" style="margin-bottom: 16px;">
                            <div class="sb-sp-field-horizontal-left">
                                <label for="short-code" class="sb-sp-label">
                                    <?php esc_html_e('Short Code', 'wpswitchboard'); ?>
                                    <span class="sb-module-required">*</span>
                                </label>
                                <p class="sb-sp-description"><?php esc_html_e('Only letters, numbers, hyphens, and underscores allowed', 'wpswitchboard'); ?></p>
                                <p id="short-code-readonly-note" class="sb-sp-description" style="display: none; color: #9ca3af; font-style: italic;"><?php esc_html_e('Short codes cannot be changed after creation', 'wpswitchboard'); ?></p>
                            </div>
                            <div class="sb-module-input-wrapper">
                                <input type="text" id="short-code" name="short_code" required placeholder="abc123" class="sb-module-input">
                                <button type="button" id="generate-code-btn" class="sb-module-button sb-module-button-secondary sb-module-button-sm"><?php esc_html_e('Generate', 'wpswitchboard'); ?></button>
                            </div>
                        </div>

                        <!-- Link Preview -->
                        <div class="sb-sp-field-horizontal" id="link-preview-container" style="margin-bottom: 16px; display:none;">
                            <div class="sb-sp-field-horizontal-left">
                                <label class="sb-sp-label"><?php esc_html_e('Short Link Preview', 'wpswitchboard'); ?></label>
                                <p class="sb-sp-description"><?php esc_html_e('Your generated short link URL', 'wpswitchboard'); ?></p>
                            </div>
                            <div style="position: relative;  width: -webkit-fill-available; overflow: visible;">
                                <code id="link-preview-url" class="sb-module-input" style="width: 100%; background: #f9fafb; border: 1px solid #e5e7eb; padding: 8px 80px 8px 12px; font-size: 13px; display: block; box-sizing: border-box; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"></code>
                                <button type="button" id="copy-preview-btn" class="sb-module-button-in-input" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%);">
                                    <?php esc_html_e('COPY', 'wpswitchboard'); ?>
                                </button>
                            </div>
                        </div>

                        <div class="sb-sp-field-horizontal" style="margin-bottom: 16px;">
                            <div class="sb-sp-field-horizontal-left">
                                <label for="password" class="sb-sp-label"><?php esc_html_e('Password (Optional)', 'wpswitchboard'); ?></label>
                                <p class="sb-sp-description"><?php esc_html_e('Users will need to enter this password to access the link', 'wpswitchboard'); ?></p>
                            </div>
                            <input type="text" id="password" name="password" placeholder="<?php esc_attr_e('Leave empty for no password', 'wpswitchboard'); ?>" class="sb-module-input">
                        </div>

                        <div class="sb-sp-field-horizontal" style="margin-bottom: 16px;">
                            <div class="sb-sp-field-horizontal-left">
                                <label for="expires-at" class="sb-sp-label"><?php esc_html_e('Expiration Date (Optional)', 'wpswitchboard'); ?></label>
                                <p class="sb-sp-description"><?php esc_html_e('When this link should stop working', 'wpswitchboard'); ?></p>
                            </div>
                            <input type="datetime-local" id="expires-at" name="expires_at" class="sb-module-input">
                        </div>

                        <div class="sb-sp-field-horizontal" style="margin-bottom: 16px;">
                            <div class="sb-sp-field-horizontal-left">
                                <label for="expire-redirect-url" class="sb-sp-label"><?php esc_html_e('Expire Redirect URL (Optional)', 'wpswitchboard'); ?></label>
                                <p class="sb-sp-description"><?php esc_html_e('Override global expiration redirect', 'wpswitchboard'); ?></p>
                            </div>
                            <input type="url" id="expire-redirect-url" name="expire_redirect_url" placeholder="<?php echo esc_attr(home_url()); ?>" class="sb-module-input">
                        </div>

                        <div class="sb-sp-field-horizontal" style="margin-bottom: 16px;">
                            <div class="sb-sp-field-horizontal-left">
                                <label class="sb-sp-label"><?php esc_html_e('Active', 'wpswitchboard'); ?></label>
                                <p class="sb-sp-description"><?php esc_html_e('Uncheck to disable this short link temporarily', 'wpswitchboard'); ?></p>
                            </div>
                            <label class="sb-module-toggle">
                                <input type="checkbox" id="is-active" name="is_active" checked>
                                <span class="sb-module-toggle-slider"></span>
                            </label>
                        </div>
                    </form>
                </div>
                <div class="sb-module-modal-footer">
                    <button type="button" class="sb-module-button sb-module-button-secondary modal-cancel"><?php esc_html_e('Cancel', 'wpswitchboard'); ?></button>
                    <button type="button" class="sb-module-button sb-module-button-primary" id="save-link-btn">
                        <?php esc_html_e('Save Link', 'wpswitchboard'); ?>
                    </button>
                </div>
            </div>
        </div>

        <?php
    }

    /**
     * Render inline JavaScript
     */
    private function render_scripts() {
        $slug = get_option('switchboard_link_shortener_slug', 'go');
        $default_length = get_option('switchboard_link_shortener_default_length', 6);
        ?>
        <script>
        jQuery(document).ready(function($) {
            const ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
            const nonce = '<?php echo wp_create_nonce('switchboard_short_links'); ?>';
            const slug = '<?php echo esc_js($slug); ?>';
            const defaultLength = <?php echo intval($default_length); ?>;

            // Links Manager Object
            const LinksManager = {
                orderBy: 'created_at',
                order: 'DESC',
                search: '',

                init: function() {
                    this.bindEvents();
                    this.loadLinks();
                },

                bindEvents: function() {
                    const self = this;

                    // Sorting
                    $(document).on('click', '#short-links-table th.sortable', function() {
                        const column = $(this).data('column');
                        if (self.orderBy === column) {
                            self.order = self.order === 'DESC' ? 'ASC' : 'DESC';
                        } else {
                            self.orderBy = column;
                            self.order = 'DESC';
                        }
                        self.loadLinks();
                    });

                    // Select all
                    $('#cb-select-all-links').on('change', function() {
                        $('.link-checkbox').prop('checked', $(this).is(':checked'));
                    });
                },

                loadLinks: function() {
                    const self = this;
                    $.post(ajaxurl, {
                        action: 'switchboard_get_all_short_links',
                        nonce: nonce,
                        orderby: self.orderBy,
                        order: self.order,
                        search: self.search
                    }, function(response) {
                        if (response.success) {
                            self.renderLinks(response.data);
                            self.updateSortIndicators();
                        } else {
                            console.error('Failed to load links:', response);
                            $('#short-links-tbody').html('<tr><td colspan="8" class="sb-module-empty"><div class="sb-module-empty-icon"></div><p class="sb-module-empty-desc">Error loading links. Check console for details.</p></td></tr>');
                        }
                    }).fail(function(xhr, status, error) {
                        console.error('AJAX error:', status, error, xhr.responseText);
                        $('#short-links-tbody').html('<tr><td colspan="8" class="sb-module-empty"><div class="sb-module-empty-icon"></div><p class="sb-module-empty-desc">AJAX Error: ' + error + '</p></td></tr>');
                    });
                },

                renderLinks: function(links) {
                    const tbody = $('#short-links-tbody');
                    tbody.empty();

                    if (!links || links.length === 0) {
                        tbody.html('<tr><td colspan="8" class="sb-module-empty"><div class="sb-module-empty-icon"></div><p class="sb-module-empty-desc">No short links found</p></td></tr>');
                        return;
                    }

                    links.forEach(function(link) {
                        const row = $('<tr>');
                        const shortUrl = '<?php echo home_url('/'); ?>' + slug + '/' + link.short_code;
                        const shortPath = '/' + slug + '/' + link.short_code;
                        const isExpired = link.expires_at && new Date(link.expires_at) < new Date();

                        // Add expired class to row
                        if (isExpired) {
                            row.addClass('sb-module-row-expired');
                        }

                        // Checkbox
                        row.append(`<td style="width: 40px;"><input type="checkbox" class="sb-module-checkbox link-checkbox" value="${link.id}"></td>`);

                        // Short Link with copy button and external icon
                        const shortLinkHtml = `
                            <div style="display: flex; align-items: center; gap: 8px;">
                                <code class="sb-module-code">${shortPath}</code>
                                <button type="button" class="copy-link-btn" data-url="${shortUrl}" title="Copy link" style="background: none; border: none; padding: 0; cursor: pointer; color: #64748b; display: flex; align-items: center;">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width: 16px; height: 16px;">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M15.666 3.888A2.25 2.25 0 0 0 13.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 0 1-.75.75H9a.75.75 0 0 1-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 0 1-2.25 2.25H6.75A2.25 2.25 0 0 1 4.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 0 1 1.927-.184" />
                                    </svg>
                                </button>
                                <a href="${shortUrl}" target="_blank" title="Visit and test link" style="color: #64748b;">
                                    <span class="dashicons dashicons-external"></span>
                                </a>
                            </div>
                        `;
                        row.append(`<td>${shortLinkHtml}</td>`);

                        // Original URL
                        row.append(`<td><code class="sb-module-code">${link.original_url}</code></td>`);

                        // Clicks
                        row.append(`<td style="font-weight: 600;">${link.click_count || 0}</td>`);

                        // Status with toggle switch (grayed out if expired)
                        const isActive = link.is_active == 1;
                        const statusHtml = `
                            <label class="sb-module-toggle${isExpired ? ' sb-module-toggle-expired' : ''}"${isExpired ? ' title="Link has expired"' : ''}>
                                <input type="checkbox" class="toggle-link-status" data-id="${link.id}" ${isActive ? 'checked' : ''} ${isExpired ? 'disabled' : ''}>
                                <span class="sb-module-toggle-slider"></span>
                            </label>
                        `;
                        row.append(`<td>${statusHtml}</td>`);

                        // Expires
                        let expiresHtml = '<span class="sb-module-text-muted">Never</span>';
                        if (link.expires_at) {
                            const expireDate = new Date(link.expires_at);
                            const formattedExpireDate = (expireDate.getMonth() + 1) + '/' + expireDate.getDate() + '/' + expireDate.getFullYear();
                            if (isExpired) {
                                expiresHtml = `<span class="sb-module-text-muted" title="Expired on ${formattedExpireDate}" style="cursor: help;">Expired</span>`;
                            } else {
                                const now = new Date();
                                const diff = Math.floor((expireDate - now) / (1000 * 60 * 60 * 24));
                                expiresHtml = `<span class="sb-module-text-muted" title="Expires on ${formattedExpireDate}" style="cursor: help;">${diff} days</span>`;
                            }
                        }
                        row.append(`<td>${expiresHtml}</td>`);

                        // Created
                        const date = new Date(link.created_at);
                        const formatted = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
                        row.append(`<td class="sb-module-text-muted">${formatted}</td>`);

                        // Actions
                        row.append(`
                            <td>
                                <div style="display: flex; gap: 8px; align-items: center;">
                                    <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm edit-link" data-id="${link.id}">Edit</button>
                                    <button type="button" class="sb-module-button sb-module-button-danger sb-module-button-sm delete-link" data-id="${link.id}">Delete</button>
                                </div>
                            </td>
                        `);

                        tbody.append(row);
                    });
                },

                updateSortIndicators: function() {
                    $('#short-links-table th.sortable').removeClass('active asc desc');
                    const th = $('#short-links-table th[data-column="' + this.orderBy + '"]');
                    th.addClass('active');
                    th.addClass(this.order.toLowerCase());
                }
            };

            // Initialize Links Manager
            LinksManager.init();

            // Open add new link modal
            $('#add-new-link-btn').on('click', function(e) {
                e.preventDefault();
                $('#modal-title').text('<?php echo esc_js(__('Add New Short Link', 'wpswitchboard')); ?>');
                $('#link-form')[0].reset();
                $('#link-id').val('');
                $('#is-active').prop('checked', true);
                $('#link-preview-container').hide();
                // Enable shortcode field and show generate button for new links
                $('#short-code').prop('readonly', false).css('background', '');
                $('#generate-code-btn').show();
                $('#short-code-readonly-note').hide();
                $('#link-modal').show();
                setTimeout(function() {
                    $('#link-modal').addClass('show');
                }, 10);
            });

            // Close modal function
            const closeLinkModal = function() {
                $('#link-modal').removeClass('show');
                setTimeout(function() {
                    $('#link-modal').hide();
                }, 200); // Match CSS transition duration
            };

            // Ensure modal is hidden on load
            $('#link-modal').hide().removeClass('show');

            // Close modal on close button and cancel button
            $(document).on('click', '#link-modal .sb-module-modal-close, #link-modal .modal-cancel', function(e) {
                e.preventDefault();
                e.stopPropagation();
                closeLinkModal();
            });

            // Close modal on backdrop click
            $(document).on('click', '#link-modal .sb-module-modal-backdrop', function(e) {
                e.preventDefault();
                e.stopPropagation();
                closeLinkModal();
            });

            // Close modal on ESC key
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape' && $('#link-modal').is(':visible')) {
                    closeLinkModal();
                }
            });

            // Prevent modal content clicks from closing modal
            $(document).on('click', '#link-modal .sb-module-modal-content', function(e) {
                e.stopPropagation();
            });

            // Generate random code
            $('#generate-code-btn').on('click', function() {
                const code = generateRandomCode(defaultLength);
                $('#short-code').val(code);
                updateLinkPreview();
            });

            function generateRandomCode(length) {
                const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
                let code = '';
                for (let i = 0; i < length; i++) {
                    code += chars.charAt(Math.floor(Math.random() * chars.length));
                }
                return code;
            }

            // Update link preview
            function updateLinkPreview() {
                const shortCode = $('#short-code').val().trim();
                if (shortCode) {
                    const shortUrl = '<?php echo home_url('/'); ?>' + slug + '/' + shortCode;
                    $('#link-preview-url').text(shortUrl);
                    $('#link-preview-container').show();
                } else {
                    $('#link-preview-container').hide();
                }
            }

            // Update preview when short code changes
            $('#short-code').on('input', function() {
                updateLinkPreview();
            });

            // Copy preview link
            $('#copy-preview-btn').on('click', function(e) {
                e.preventDefault();
                const url = $('#link-preview-url').text();
                const $btn = $(this);

                navigator.clipboard.writeText(url).then(function() {
                    const originalText = $btn.text();
                    $btn.text('Copied!').css('color', 'var(--primary-500)');
                    setTimeout(function() {
                        $btn.text(originalText).css('color', '');
                    }, 2000);
                });
            });

            // Copy link button (for dashboard tables)
            $(document).on('click', '.copy-link-btn', function(e) {
                e.preventDefault();
                const url = $(this).data('url');
                const $btn = $(this);

                navigator.clipboard.writeText(url).then(function() {
                    const originalHtml = $btn.html();
                    $btn.html('Copied!').css('color', '#16a34a');
                    setTimeout(function() {
                        $btn.html(originalHtml).css('color', '');
                    }, 2000);
                });
            });

            // Save link
            $('#save-link-btn').on('click', function() {
                const linkId = $('#link-id').val();
                const action = linkId ? 'switchboard_update_short_link' : 'switchboard_create_short_link';

                const data = {
                    action: action,
                    nonce: nonce,
                    link_id: linkId,
                    original_url: $('#original-url').val(),
                    short_code: $('#short-code').val(),
                    password: $('#password').val(),
                    expires_at: $('#expires-at').val(),
                    expire_redirect_url: $('#expire-redirect-url').val(),
                    is_active: $('#is-active').prop('checked') ? 1 : 0
                };

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: data,
                    success: function(response) {
                        if (response.success) {
                            closeLinkModal();
                            LinksManager.loadLinks();
                        } else {
                            alert('Error: ' + response.data);
                        }
                    },
                    error: function() {
                        alert('An error occurred. Please try again.');
                    }
                });
            });

            // Edit link
            $(document).on('click', '.edit-link', function(e) {
                e.preventDefault();
                const linkId = $(this).data('id');

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_get_short_link',
                        nonce: nonce,
                        link_id: linkId
                    },
                    success: function(response) {
                        if (response.success) {
                            const link = response.data;
                            $('#modal-title').text('<?php echo esc_js(__('Edit Short Link', 'wpswitchboard')); ?>');
                            $('#link-id').val(link.id);
                            $('#original-url').val(link.original_url);
                            $('#short-code').val(link.short_code);
                            $('#password').val(link.password || '');
                            $('#expires-at').val(link.expires_at ? link.expires_at.replace(' ', 'T') : '');
                            $('#expire-redirect-url').val(link.expire_redirect_url || '');
                            $('#is-active').prop('checked', link.is_active == 1);
                            updateLinkPreview();
                            // Make shortcode readonly in edit mode
                            $('#short-code').prop('readonly', true).css('background', '#f3f4f6');
                            $('#generate-code-btn').hide();
                            $('#short-code-readonly-note').show();
                            $('#link-modal').show();
                            setTimeout(function() {
                                $('#link-modal').addClass('show');
                            }, 10);
                        } else {
                            alert('Error loading link data');
                        }
                    }
                });
            });

            // Delete link
            $(document).on('click', '.delete-link', function(e) {
                e.preventDefault();
                if (confirm('<?php echo esc_js(__('Are you sure you want to delete this short link?', 'wpswitchboard')); ?>')) {
                    const linkId = $(this).data('id');
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'switchboard_delete_short_link',
                            nonce: nonce,
                            id: linkId
                        },
                        success: function(response) {
                            if (response.success) {
                                LinksManager.loadLinks();
                            } else {
                                alert('Error: ' + response.data);
                            }
                        },
                        error: function() {
                            alert('An error occurred. Please try again.');
                        }
                    });
                }
            });

            // Toggle link status
            $(document).on('change', '.toggle-link-status', function() {
                const $toggle = $(this);
                const linkId = $toggle.data('id');
                const isActive = $toggle.prop('checked') ? 1 : 0;

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_toggle_link_status',
                        nonce: nonce,
                        link_id: linkId,
                        is_active: isActive
                    },
                    success: function(response) {
                        if (!response.success) {
                            // Revert toggle on error
                            $toggle.prop('checked', !isActive);
                            alert('Error: ' + response.data);
                        }
                    },
                    error: function() {
                        // Revert toggle on error
                        $toggle.prop('checked', !isActive);
                        alert('An error occurred. Please try again.');
                    }
                });
            });


            // Bulk actions (for both buttons)
            $('#doaction, #doaction-links').on('click', function(e) {
                e.preventDefault();
                const action = $('#bulk-action-selector-top').val();
                const checked = $('.link-checkbox:checked');

                if (action === '-1') {
                    alert('<?php echo esc_js(__('Please select a bulk action', 'wpswitchboard')); ?>');
                    return;
                }

                if (checked.length === 0) {
                    alert('<?php echo esc_js(__('Please select at least one link', 'wpswitchboard')); ?>');
                    return;
                }

                const linkIds = checked.map(function() {
                    return $(this).val();
                }).get();

                if (confirm('<?php echo esc_js(__('Are you sure you want to perform this action?', 'wpswitchboard')); ?>')) {
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'switchboard_bulk_action_short_links',
                            nonce: nonce,
                            bulk_action: action,
                            link_ids: linkIds
                        },
                        success: function(response) {
                            if (response.success) {
                                LinksManager.loadLinks();
                            } else {
                                alert('Error: ' + response.data);
                            }
                        },
                        error: function() {
                            alert('An error occurred. Please try again.');
                        }
                    });
                }
            });
        });
        </script>
        <?php
    }

    /**
     * Render inline styles
     * Minimal styles - most styling comes from switchboard-admin.css
     */
    private function render_styles() {
        ?>
        <style>
            /* Only keep minimal styles that aren't covered by global classes */
            /* Input wrapper for short code with generate button */
            .sb-sp-input-wrapper {
                display: flex;
                gap: 8px;
                align-items: center;
            }
            
            .sb-sp-input-wrapper .sb-sp-input {
                flex: 1;
            }

            /* Page Title & Badge Alignment */
            .wrap h1 {
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap: 0;
            }

            .wrap h1 > *:first-child {
                display: flex;
                align-items: center;
                gap: 0;
            }

            .switchboard-badge {
                font-size: 11px;
                padding: 4px 10px;
                margin-left: 8px;
                display: inline-flex;
                align-items: center;
                vertical-align: middle;
            }

            /* Dashboard Stats Grid */
            .stats-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
                gap: 20px;
                margin: 30px 0;
            }

            .stat-card {
                background: white;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                padding: 24px;
                display: flex;
                align-items: center;
                gap: 16px;
                transition: box-shadow 0.2s;
            }

            .stat-card:hover {
                box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            }

            .stat-icon {
                width: 56px;
                height: 56px;
                border-radius: 12px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24px;
                flex-shrink: 0;
            }

            .stat-content {
                flex: 1;
            }

            .stat-value {
                font-size: 32px;
                font-weight: 700;
                color: #1f2937;
                line-height: 1;
                margin-bottom: 4px;
            }

            .stat-label {
                font-size: 14px;
                color: #6b7280;
                font-weight: 500;
            }

            /* Dashboard Two Column Layout */
            .dashboard-two-col {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
                gap: 20px;
                margin-top: 30px;
            }

            .dashboard-card {
                background: white;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                padding: 24px;
            }

            .dashboard-card h3 {
                margin: 0 0 20px 0;
                font-size: 18px;
                color: #1f2937;
            }

            .dashboard-table {
                width: 100%;
                border-collapse: collapse;
            }

            .dashboard-table th {
                text-align: left;
                padding: 12px;
                border-bottom: 2px solid #e5e7eb;
                font-size: 12px;
                color: #6b7280;
                font-weight: 600;
                text-transform: uppercase;
            }

            .dashboard-table td {
                padding: 12px;
                border-bottom: 1px solid #f3f4f6;
            }

            .dashboard-table tr:last-child td {
                border-bottom: none;
            }

            .url-preview {
                font-size: 12px;
                color: #9ca3af;
            }

            .empty-state-text {
                text-align: center;
                color: #9ca3af;
                padding: 40px;
                font-style: italic;
            }

            /* Status and Feature Badges */
            .status-badge {
                display: inline-block;
                padding: 4px 10px;
                border-radius: 4px;
                font-size: 12px;
                font-weight: 600;
            }

            .status-active {
                background: #dcfce7;
                color: #166534;
            }

            .status-inactive {
                background: #f3f4f6;
                color: #6b7280;
            }

            .status-expired {
                background: #fef2f2;
                color: #dc2626;
            }

            .feature-badge {
                display: inline-block;
                padding: 3px 8px;
                border-radius: 3px;
                font-size: 11px;
                font-weight: 600;
                margin-right: 5px;
                margin-top: 5px;
            }

            .password-badge {
                background: #fef3c7;
                color: #92400e;
            }

            .expires-badge {
                background: var(--primary-100);
                color: #3730a3;
            }


            /* Modal Styles */
            .switchboard-modal {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                z-index: 100000;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .modal-content {
                background: white;
                border-radius: 8px;
                width: 90%;
                max-width: 600px;
                max-height: 90vh;
                overflow: auto;
                box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            }

            .modal-small {
                max-width: 400px;
            }

            .modal-header {
                padding: 24px;
                border-bottom: 1px solid #e5e7eb;
                display: flex;
                align-items: center;
                justify-content: space-between;
            }

            .modal-header h2 {
                margin: 0;
                font-size: 20px;
            }

            .modal-close {
                background: none;
                border: none;
                font-size: 28px;
                color: #9ca3af;
                cursor: pointer;
                padding: 0;
                width: 32px;
                height: 32px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 4px;
            }

            .modal-close:hover {
                background: #f3f4f6;
                color: #1f2937;
            }

            .modal-body {
                padding: 24px;
            }

            .modal-footer {
                padding: 16px 24px;
                border-top: 1px solid #e5e7eb;
                display: flex;
                justify-content: flex-end;
                gap: 10px;
            }

            .form-field {
                margin-bottom: 20px;
            }

            .form-field label {
                display: block;
                margin-bottom: 6px;
                font-weight: 600;
                color: #374151;
                font-size: 14px;
            }

            .form-field input[type="text"],
            .form-field input[type="url"],
            .form-field input[type="datetime-local"] {
                width: 100%;
                padding: 10px 12px;
                border: 1px solid #d1d5db;
                border-radius: 4px;
                font-size: 14px;
            }

            .form-field input:focus {
                outline: none;
                border-color: var(--primary-500);
                box-shadow: 0 0 0 1px var(--primary-500);
            }

            .form-field .description {
                margin-top: 6px;
                font-size: 12px;
                color: #6b7280;
            }

            .short-code-input-group {
                display: flex;
                gap: 10px;
            }

            .short-code-input-group input {
                flex: 1;
            }

            .form-row-two-col {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 16px;
            }

            /* Modal Checkbox Styling */
            .form-field input[type="checkbox"] {
                width: 18px !important;
                height: 18px !important;
                border: 2px solid #d1d5db !important;
                border-radius: 4px !important;
                cursor: pointer !important;
                vertical-align: middle !important;
                margin-right: 8px !important;
            }

            .form-field input[type="checkbox"]:checked {
                background-color: var(--primary-500) !important;
                border-color: var(--primary-500) !important;
            }

            .form-field input[type="checkbox"]:focus {
                outline: none !important;
                box-shadow: 0 0 0 3px rgba(var(--primary-500-rgb), 0.1) !important;
            }

            .form-field label {
                display: inline-flex !important;
                align-items: center !important;
                font-size: 14px !important;
                font-weight: 500 !important;
                cursor: pointer !important;
            }

            /* Settings */
            .switchboard-settings-container {
                background: white;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                padding: 24px;
                margin-top: 20px;
            }

            /* ===== MODERN UI ENHANCEMENTS - Switchboard Sky Blue ===== */

            /* Page Title Action Button */
            .wrap h1 .page-title-action {
                background: var(--primary-500) !important;
                color: white !important;
                border: none !important;
                padding: 0 16px !important;
                font-size: 13px !important;
                font-weight: 500 !important;
                border-radius: 4px !important;
                text-decoration: none !important;
                transition: background-color 0.15s ease !important;
                box-shadow: none !important;
                display: inline-flex !important;
                align-items: center !important;
                gap: 6px !important;
                height: 32px !important;
                line-height: 1 !important;
            }

            .wrap h1 .page-title-action:hover {
                background: var(--primary-600) !important;
            }

            .wrap h1 .page-title-action:active {
                background: var(--primary-700) !important;
            }

            /* Search Input */
            .search-box input[type="search"],
            .search-box input[type="text"] {
                height: 32px !important;
                padding: 0 12px !important;
                border: 1px solid #d1d5db !important;
                border-radius: 4px !important;
                font-size: 13px !important;
            }

            /* Search Button */
            input#search-submit,
            .search-box input[type="submit"] {
                background: var(--primary-500) !important;
                color: white !important;
                border: none !important;
                padding: 0 16px !important;
                border-radius: 4px !important;
                font-weight: 500 !important;
                font-size: 13px !important;
                transition: background-color 0.15s ease !important;
                cursor: pointer !important;
                height: 32px !important;
                line-height: 1 !important;
            }

            input#search-submit:hover {
                background: var(--primary-600) !important;
            }

            /* Bulk Actions Dropdown */
            .tablenav select#bulk-action-selector-top,
            .tablenav select#bulk-action-selector-bottom {
                border: 1px solid #d1d5db !important;
                border-radius: 4px !important;
                padding: 0 32px 0 12px !important;
                font-size: 13px !important;
                color: #374151 !important;
                background-color: white !important;
                background-image: url('data:image/svg+xml;charset=UTF-8,%3csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="%23374151"%3e%3cpath fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd"/%3e%3c/svg%3e') !important;
                background-position: right 8px center !important;
                background-repeat: no-repeat !important;
                background-size: 16px !important;
                appearance: none !important;
                -webkit-appearance: none !important;
                -moz-appearance: none !important;
                transition: border-color 0.15s ease !important;
                height: 32px !important;
                line-height: 1 !important;
            }

            .tablenav select:focus {
                outline: none !important;
                border-color: var(--primary-500) !important;
                box-shadow: 0 0 0 3px rgba(var(--primary-500-rgb), 0.1) !important;
            }

            /* Apply Button */
            #doaction,
            #doaction2,
            .tablenav .button.action {
                background: var(--primary-500) !important;
                color: white !important;
                border: none !important;
                padding: 0 16px !important;
                border-radius: 4px !important;
                font-weight: 500 !important;
                font-size: 13px !important;
                transition: background-color 0.15s ease !important;
                cursor: pointer !important;
                height: 32px !important;
                line-height: 1 !important;
            }

            #doaction:hover,
            #doaction2:hover {
                background: var(--primary-600) !important;
            }

            /* Table Enhancements */
            .wp-list-table {
                border: 1px solid #e5e7eb !important;
                border-radius: 8px !important;
                overflow: hidden !important;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05) !important;
            }

            .wp-list-table thead th {
                background: #f9fafb !important;
                color: #374151 !important;
                font-weight: 600 !important;
                font-size: 13px !important;
                text-transform: uppercase !important;
                letter-spacing: 0.5px !important;
                border-bottom: 2px solid #e5e7eb !important;
                padding: 14px 12px !important;
            }

            /* Column Widths */
            .wp-list-table .column-short_code {
                width: 25% !important;
            }

            .wp-list-table .column-original_url {
                width: 30% !important;
            }

            .wp-list-table .column-clicks {
                width: 8% !important;
            }

            .wp-list-table .column-toggle {
                width: 8% !important;
            }

            .wp-list-table .column-expires {
                width: 10% !important;
            }

            .wp-list-table .column-created {
                width: 12% !important;
            }

            .wp-list-table .column-actions {
                width: 7% !important;
            }

            .wp-list-table tbody tr {
                transition: background-color 0.15s ease !important;
                border-bottom: 1px solid #f3f4f6 !important;
            }

            .wp-list-table tbody tr:hover {
                background-color: #f9fafb !important;
            }

            .wp-list-table tbody td {
                padding: 16px 12px !important;
                vertical-align: middle !important;
            }

            .wp-list-table tbody tr:last-child {
                border-bottom: none !important;
            }

            /* Row Actions */
            .wp-list-table .row-actions {
                color: #6b7280 !important;
                font-size: 13px !important;
            }

            .wp-list-table .row-actions span {
                margin: 0 !important;
                padding: 0 6px !important;
            }

            .wp-list-table .row-actions span:first-child {
                padding-left: 0 !important;
            }

            .wp-list-table .row-actions a {
                color: var(--primary-500) !important;
                text-decoration: none !important;
                font-weight: 500 !important;
                transition: color 0.15s ease !important;
            }

            .wp-list-table .row-actions a:hover {
                color: var(--primary-600) !important;
            }

            .wp-list-table .row-actions .delete a {
                color: #ef4444 !important;
            }

            .wp-list-table .row-actions .delete a:hover {
                color: #dc2626 !important;
            }

            /* Checkbox Styling */
            .wp-list-table input[type="checkbox"] {
                width: 18px !important;
                height: 18px !important;
                border: 2px solid #d1d5db !important;
                border-radius: 4px !important;
                cursor: pointer !important;
                transition: all 0.2s ease !important;
            }

            .wp-list-table input[type="checkbox"]:checked {
                background-color: var(--primary-500) !important;
                border-color: var(--primary-500) !important;
            }

            .wp-list-table input[type="checkbox"]:focus {
                outline: none !important;
                box-shadow: 0 0 0 3px rgba(var(--primary-500-rgb), 0.1) !important;
            }

            /* Modal Buttons */
            .modal-footer .button {
                padding: 0 20px !important;
                font-size: 13px !important;
                font-weight: 500 !important;
                border-radius: 4px !important;
                border: none !important;
                cursor: pointer !important;
                transition: background-color 0.15s ease !important;
                display: inline-flex !important;
                align-items: center !important;
                justify-content: center !important;
                gap: 6px !important;
                height: 36px !important;
                line-height: 1 !important;
            }

            .modal-footer .button-primary {
                background: var(--primary-500) !important;
                color: white !important;
                box-shadow: none !important;
            }

            .modal-footer .button-primary:hover {
                background: var(--primary-600) !important;
            }

            .modal-footer .button-primary:active {
                background: var(--primary-700) !important;
            }

            .modal-footer .button-secondary,
            .modal-footer .modal-cancel {
                background: white !important;
                color: #374151 !important;
                border: 1px solid #d1d5db !important;
            }

            .modal-footer .button-secondary:hover,
            .modal-footer .modal-cancel:hover {
                background: #f9fafb !important;
                border-color: #9ca3af !important;
            }

            /* Small Buttons (Copy, etc.) */
            .button-small,
            .button.button-small {
                padding: 0 12px !important;
                font-size: 13px !important;
                border-radius: 4px !important;
                font-weight: 500 !important;
                transition: background-color 0.15s ease !important;
                height: 28px !important;
                line-height: 1 !important;
            }

            .copy-link-btn {
                background: #f3f4f6 !important;
                color: #374151 !important;
                border: 1px solid #e5e7eb !important;
            }

            .copy-link-btn:hover {
                background: #e5e7eb !important;
                border-color: #d1d5db !important;
            }

            /* Generate Button in Modal */
            .short-code-input-group .button {
                background: var(--primary-500) !important;
                color: white !important;
                border: none !important;
                padding: 0 16px !important;
                border-radius: 4px !important;
                font-weight: 500 !important;
                font-size: 13px !important;
                white-space: nowrap !important;
                transition: background-color 0.15s ease !important;
                height: 40px !important;
                line-height: 1 !important;
            }

            .short-code-input-group .button:hover {
                background: var(--primary-600) !important;
            }

            /* Tabs Navigation */
            .nav-tab {
                border: none !important;
                background: transparent !important;
                color: #6b7280 !important;
                padding: 12px 20px !important;
                font-weight: 500 !important;
                font-size: 13px !important;
                border-bottom: 2px solid transparent !important;
                margin: 0 4px !important;
                transition: color 0.15s ease, border-color 0.15s ease !important;
            }

            .nav-tab:hover {
                color: #374151 !important;
            }

            .nav-tab-active {
                color: var(--primary-500) !important;
                border-bottom-color: var(--primary-500) !important;
                background: transparent !important;
            }

            .nav-tab-active:hover {
                background: transparent !important;
            }

            /* Form Inputs Enhancement */
            .form-field input,
            .form-field textarea,
            .form-field select {
                transition: border-color 0.15s ease, box-shadow 0.15s ease !important;
                height: 40px !important;
                font-size: 13px !important;
            }

            .form-field input:focus,
            .form-field textarea:focus,
            .form-field select:focus {
                outline: none !important;
                border-color: var(--primary-500) !important;
                box-shadow: 0 0 0 3px rgba(var(--primary-500-rgb), 0.1) !important;
            }

            /* Hide default WP_List_Table pagination (we use custom pagination) */
            .sb-module-table-wrapper .tablenav-pages {
                display: none !important;
            }

            /* Pagination */
            .tablenav-pages a,
            .tablenav-pages span.current {
                border: 1px solid #e5e7eb !important;
                border-radius: 4px !important;
                padding: 4px 10px !important;
                margin: 0 2px !important;
                font-size: 13px !important;
                transition: background-color 0.15s ease, border-color 0.15s ease !important;
                height: 28px !important;
                line-height: 1 !important;
                display: inline-flex !important;
                align-items: center !important;
            }

            .tablenav-pages a:hover {
                background: #f9fafb !important;
                border-color: #d1d5db !important;
                color: #374151 !important;
            }

            .tablenav-pages span.current {
                background: var(--primary-500) !important;
                color: white !important;
                border-color: var(--primary-500) !important;
                font-weight: 500 !important;
            }

            /* Link Preview in Modal */
            #link-preview-container {
                background: #f9fafb !important;
                border: 1px solid #e5e7eb !important;
                border-radius: 4px !important;
                padding: 12px !important;
            }

            #link-preview-url {
                color: var(--primary-500) !important;
                font-family: 'Courier New', monospace !important;
                font-size: 13px !important;
                word-break: break-all !important;
            }

            #copy-preview-btn {
                background: var(--primary-500) !important;
                color: white !important;
                border: none !important;
                padding: 0 14px !important;
                border-radius: 4px !important;
                font-size: 13px !important;
                font-weight: 500 !important;
                margin-top: 8px !important;
                cursor: pointer !important;
                transition: background-color 0.15s ease !important;
                height: 32px !important;
                line-height: 1 !important;
            }

            #copy-preview-btn:hover {
                background: var(--primary-600) !important;
            }

            /* Remove WordPress default button shadows and borders */
            .button,
            .button-primary,
            .button-secondary {
                text-shadow: none !important;
            }
        </style>
        <?php
    }

    /**
     * Add Classic Editor box
     */
    public function add_classic_editor_box($post) {
        if (!in_array($post->post_type, array('post', 'page'))) {
            return;
        }

        if ($post->post_status !== 'publish' && $post->post_status !== 'draft') {
            return;
        }

        $link_id = get_post_meta($post->ID, '_switchboard_short_link_id', true);
        $short_code = get_post_meta($post->ID, '_switchboard_short_link_code', true);

        $slug = get_option('switchboard_link_shortener_slug', 'go');
        $short_url = $short_code ? home_url('/' . $slug . '/' . $short_code) : '';

        ?>
        <div class="misc-pub-section" id="switchboard-short-link-section">
            <style>
                #switchboard-short-link-section .short-link-display {
                    background: #f7f7f7;
                    padding: 8px;
                    border-radius: 4px;
                    margin-top: 8px;
                    font-family: monospace;
                    font-size: 12px;
                    word-break: break-all;
                }
                #switchboard-short-link-section .button-group {
                    margin-top: 8px;
                    display: flex;
                    gap: 6px;
                }
            </style>

            <strong>Short Link:</strong><br>

            <?php if ($short_url): ?>
                <div class="short-link-display"><?php echo esc_html($short_url); ?></div>
                <div class="button-group">
                    <button type="button" class="button button-small" onclick="copyShortLink(this, '<?php echo esc_js($short_url); ?>')">Copy</button>
                    <a href="<?php echo esc_url($short_url); ?>" target="_blank" class="button button-small">Open</a>
                </div>
            <?php else: ?>
                <p class="sb-sp-description">No short link generated yet.</p>
                <button type="button" class="button button-small" onclick="generateShortLink(<?php echo $post->ID; ?>, this)">
                    Generate Short Link
                </button>
            <?php endif; ?>

            <script>
            function copyShortLink(btn, url) {
                navigator.clipboard.writeText(url).then(function() {
                    var originalText = btn.textContent;
                    btn.textContent = 'Copied!';
                    btn.style.color = '#16a34a';
                    setTimeout(function() {
                        btn.textContent = originalText;
                        btn.style.color = '';
                    }, 2000);
                });
            }

            function generateShortLink(postId, btn) {
                btn.disabled = true;
                btn.textContent = 'Generating...';

                jQuery.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'switchboard_generate_post_short_link',
                        nonce: '<?php echo wp_create_nonce('switchboard_short_links'); ?>',
                        post_id: postId
                    },
                    success: function(response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            alert('Error: ' + response.data);
                            btn.disabled = false;
                            btn.textContent = 'Generate Short Link';
                        }
                    },
                    error: function() {
                        alert('An error occurred. Please try again.');
                        btn.disabled = false;
                        btn.textContent = 'Generate Short Link';
                    }
                });
            }
            </script>
        </div>
        <?php
    }

    /**
     * Enqueue Gutenberg assets
     */
    public function enqueue_gutenberg_assets() {
        global $post;

        if (!$post || !in_array($post->post_type, array('post', 'page'))) {
            return;
        }

        $link_id = get_post_meta($post->ID, '_switchboard_short_link_id', true);
        $short_code = get_post_meta($post->ID, '_switchboard_short_link_code', true);

        $slug = get_option('switchboard_link_shortener_slug', 'go');
        $short_url = $short_code ? home_url('/' . $slug . '/' . $short_code) : '';

        wp_enqueue_script('wp-plugins');
        wp_enqueue_script('wp-edit-post');
        wp_enqueue_script('wp-element');
        wp_enqueue_script('wp-components');
        wp_enqueue_script('wp-data');
        wp_enqueue_script('wp-dom-ready');

        $script = "
wp.domReady(function() {
    var wp = window.wp;

    if (!wp || !wp.plugins || !wp.editPost) {
        return;
    }

    const { registerPlugin } = wp.plugins;
    const { PluginDocumentSettingPanel } = wp.editPost;
    const { createElement: el } = wp.element;
    const { Button } = wp.components;
    const { useSelect } = wp.data;
    const { useState } = wp.element;

    const ShortLinkPanel = function() {
        const [shortUrl, setShortUrl] = useState('" . esc_js($short_url) . "');
        const [isGenerating, setIsGenerating] = useState(false);

        const postId = useSelect(function(select) {
            return select('core/editor').getCurrentPostId();
        });

        const generateShortLink = function() {
            setIsGenerating(true);

            fetch(ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'switchboard_generate_post_short_link',
                    nonce: '" . wp_create_nonce('switchboard_short_links') . "',
                    post_id: postId
                })
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.success) {
                    setShortUrl(data.data.short_url);
                    setIsGenerating(false);
                } else {
                    alert('Error: ' + data.data);
                    setIsGenerating(false);
                }
            })
            .catch(function(error) {
                alert('An error occurred. Please try again.');
                setIsGenerating(false);
            });
        };

        const copyToClipboard = function() {
            const input = document.querySelector('.switchboard-short-link-input');
            if (input) {
                input.select();
                input.setSelectionRange(0, 99999);

                try {
                    navigator.clipboard.writeText(shortUrl).then(function() {
                        const btn = document.querySelector('.switchboard-copy-short-link-btn');
                        if (btn) {
                            btn.textContent = 'Copied!';
                            btn.style.color = '#00a32a';
                            setTimeout(function() {
                                btn.textContent = 'Copy Link';
                                btn.style.color = '';
                            }, 2000);
                        }
                    });
                } catch(err) {
                    document.execCommand('copy');
                    const btn = document.querySelector('.switchboard-copy-short-link-btn');
                    if (btn) {
                        btn.textContent = 'Copied!';
                        btn.style.color = '#00a32a';
                        setTimeout(function() {
                            btn.textContent = 'Copy Link';
                            btn.style.color = '';
                        }, 2000);
                    }
                }
            }
        };

        if (!shortUrl) {
            return el(PluginDocumentSettingPanel, {
                name: 'switchboard-short-link',
                title: 'Short Link',
                className: 'switchboard-short-link-panel',
                icon: 'admin-links'
            },
                el('div', { style: { marginBottom: '12px' } },
                    el('p', { style: { margin: '0 0 12px 0', fontSize: '13px', lineHeight: '1.5', color: '#666' } },
                        'Generate a short link for this post.'
                    ),
                    el(Button, {
                        variant: 'secondary',
                        isSmall: false,
                        onClick: generateShortLink,
                        isBusy: isGenerating,
                        disabled: isGenerating,
                        style: { width: '100%' }
                    }, isGenerating ? 'Generating...' : 'Generate Short Link')
                )
            );
        }

        return el(PluginDocumentSettingPanel, {
            name: 'switchboard-short-link',
            title: 'Short Link',
            className: 'switchboard-short-link-panel',
            icon: 'admin-links'
        },
            el('div', { style: { marginBottom: '12px' } },
                el('p', { style: { margin: '0 0 12px 0', fontSize: '13px', lineHeight: '1.5', color: '#666' } },
                    'Your short link for this post.'
                ),
                el('input', {
                    type: 'text',
                    readOnly: true,
                    value: shortUrl,
                    className: 'switchboard-short-link-input',
                    style: {
                        width: '100%',
                        padding: '6px 8px',
                        border: '1px solid #ddd',
                        borderRadius: '2px',
                        fontSize: '12px',
                        fontFamily: 'monospace',
                        marginBottom: '8px',
                        cursor: 'text',
                        backgroundColor: '#f7f7f7'
                    },
                    onClick: function(e) { e.target.select(); }
                }),
                el('div', { style: { display: 'flex', gap: '8px' } },
                    el(Button, {
                        variant: 'secondary',
                        isSmall: true,
                        className: 'switchboard-copy-short-link-btn',
                        onClick: copyToClipboard,
                        style: { flex: 1 }
                    }, 'Copy Link'),
                    el('a', {
                        href: shortUrl,
                        target: '_blank',
                        className: 'button components-button is-secondary is-small',
                        style: { flex: 1, textAlign: 'center', textDecoration: 'none' }
                    }, 'Open')
                )
            )
        );
    };

    registerPlugin('switchboard-short-link', {
        render: ShortLinkPanel,
        icon: 'admin-links'
    });
});
        ";

        wp_add_inline_script('wp-dom-ready', $script);
    }

    /**
     * AJAX: Create short link
     */
    public function ajax_create_link() {
        check_ajax_referer('switchboard_short_links', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }

        $original_url = esc_url_raw($_POST['original_url']);
        $short_code = sanitize_title($_POST['short_code']);
        $password = !empty($_POST['password']) ? wp_hash_password($_POST['password']) : null;
        $expires_at = !empty($_POST['expires_at']) ? date('Y-m-d H:i:s', strtotime(sanitize_text_field($_POST['expires_at']))) : null;
        $expire_redirect_url = !empty($_POST['expire_redirect_url']) ? esc_url_raw($_POST['expire_redirect_url']) : null;
        $is_active = isset($_POST['is_active']) ? intval($_POST['is_active']) : 1;

        // Validate short code
        if (!preg_match('/^[a-z0-9_-]+$/i', $short_code)) {
            wp_send_json_error('Short code can only contain letters, numbers, hyphens, and underscores');
        }

        global $wpdb;

        // Check if short code already exists
        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$this->links_table} WHERE short_code = %s",
            $short_code
        ));

        if ($exists) {
            wp_send_json_error('Short code already exists');
        }

        // Insert link
        $result = $wpdb->insert(
            $this->links_table,
            array(
                'short_code' => $short_code,
                'original_url' => $original_url,
                'password' => $password,
                'expires_at' => $expires_at,
                'expire_redirect_url' => $expire_redirect_url,
                'is_active' => $is_active,
                'created_by' => get_current_user_id()
            ),
            array('%s', '%s', '%s', '%s', '%s', '%d', '%d')
        );

        if ($result) {
            wp_send_json_success('Short link created successfully');
        } else {
            wp_send_json_error('Failed to create short link');
        }
    }

    /**
     * AJAX: Update short link
     */
    public function ajax_update_link() {
        check_ajax_referer('switchboard_short_links', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }

        $link_id = intval($_POST['link_id']);
        $original_url = esc_url_raw($_POST['original_url']);
        $short_code = sanitize_title($_POST['short_code']);
        $password = !empty($_POST['password']) ? wp_hash_password($_POST['password']) : null;
        $expires_at = !empty($_POST['expires_at']) ? date('Y-m-d H:i:s', strtotime(sanitize_text_field($_POST['expires_at']))) : null;
        $expire_redirect_url = !empty($_POST['expire_redirect_url']) ? esc_url_raw($_POST['expire_redirect_url']) : null;
        $is_active = isset($_POST['is_active']) ? intval($_POST['is_active']) : 1;

        // Validate short code
        if (!preg_match('/^[a-z0-9_-]+$/i', $short_code)) {
            wp_send_json_error('Short code can only contain letters, numbers, hyphens, and underscores');
        }

        global $wpdb;

        // Check if short code already exists (excluding current link)
        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$this->links_table} WHERE short_code = %s AND id != %d",
            $short_code,
            $link_id
        ));

        if ($exists) {
            wp_send_json_error('Short code already exists');
        }

        // Update link
        $result = $wpdb->update(
            $this->links_table,
            array(
                'short_code' => $short_code,
                'original_url' => $original_url,
                'password' => $password,
                'expires_at' => $expires_at,
                'expire_redirect_url' => $expire_redirect_url,
                'is_active' => $is_active
            ),
            array('id' => $link_id),
            array('%s', '%s', '%s', '%s', '%s', '%d'),
            array('%d')
        );

        if ($result !== false) {
            wp_send_json_success('Short link updated successfully');
        } else {
            wp_send_json_error('Failed to update short link');
        }
    }

    /**
     * AJAX: Get short link
     */
    public function ajax_get_link() {
        check_ajax_referer('switchboard_short_links', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }

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

        global $wpdb;
        $link = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$this->links_table} WHERE id = %d",
            $link_id
        ));

        if ($link) {
            // Don't send hashed password, just indicate if it exists
            $link->password = !empty($link->password) ? '********' : '';
            wp_send_json_success($link);
        } else {
            wp_send_json_error('Link not found');
        }
    }

    /**
     * AJAX: Get all short links
     */
    public function ajax_get_all_links() {
        check_ajax_referer('switchboard_short_links', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }

        global $wpdb;

        $orderby = isset($_POST['orderby']) ? sanitize_text_field($_POST['orderby']) : 'created_at';
        $order = isset($_POST['order']) ? sanitize_text_field($_POST['order']) : 'DESC';
        $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';

        // SECURITY FIX: Validate orderby column (strict comparison)
        $allowed_columns = array('short_code', 'original_url', 'click_count', 'is_active', 'expires_at', 'created_at');
        if (!in_array($orderby, $allowed_columns, true)) {
            $orderby = 'created_at';
        }

        // SECURITY FIX: Validate order direction
        $order = strtoupper($order) === 'ASC' ? 'ASC' : 'DESC';

        $where = '';
        if (!empty($search)) {
            $where = $wpdb->prepare(" WHERE short_code LIKE %s OR original_url LIKE %s",
                '%' . $wpdb->esc_like($search) . '%',
                '%' . $wpdb->esc_like($search) . '%'
            );
        }

        // SECURITY FIX: Safe because $orderby and $order are whitelisted
        $query = "SELECT * FROM {$this->links_table} {$where} ORDER BY {$orderby} {$order}";

        $links = $wpdb->get_results($query, ARRAY_A);

        // SECURITY FIX: Don't expose database errors to users
        if ($wpdb->last_error) {
            error_log('Link Shortener Database Error: ' . $wpdb->last_error);
            wp_send_json_error('An error occurred while fetching links');
        }

        // SECURITY FIX: Don't expose password hashes
        foreach ($links as &$link) {
            if (!empty($link['password'])) {
                $link['password'] = '********';
            }
        }

        wp_send_json_success($links);
    }

    /**
     * AJAX: Delete short link
     */
    public function ajax_delete_link() {
        check_ajax_referer('switchboard_short_links', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }

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

        if ($this->delete_link($link_id)) {
            wp_send_json_success('Short link deleted successfully');
        } else {
            wp_send_json_error('Failed to delete short link');
        }
    }

    /**
     * AJAX: Toggle link active status
     */
    public function ajax_toggle_status() {
        check_ajax_referer('switchboard_short_links', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }

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

        global $wpdb;
        $result = $wpdb->update(
            $this->links_table,
            array('is_active' => $is_active),
            array('id' => $link_id),
            array('%d'),
            array('%d')
        );

        if ($result !== false) {
            wp_send_json_success(array(
                'message' => 'Status updated successfully',
                'is_active' => $is_active
            ));
        } else {
            wp_send_json_error('Failed to update status');
        }
    }

    /**
     * AJAX: Generate short link for post
     */
    public function ajax_generate_post_link() {
        check_ajax_referer('switchboard_short_links', 'nonce');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Permission denied');
        }

        $post_id = intval($_POST['post_id']);
        $post = get_post($post_id);

        if (!$post) {
            wp_send_json_error('Post not found');
        }

        // Check if link already exists
        $existing_link_id = get_post_meta($post_id, '_switchboard_short_link_id', true);
        if ($existing_link_id) {
            global $wpdb;
            $existing_link = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM {$this->links_table} WHERE id = %d",
                $existing_link_id
            ));

            if ($existing_link) {
                $slug = get_option('switchboard_link_shortener_slug', 'go');
                $short_url = home_url('/' . $slug . '/' . $existing_link->short_code);

                wp_send_json_success(array(
                    'link_id' => $existing_link->id,
                    'short_code' => $existing_link->short_code,
                    'short_url' => $short_url
                ));
            }
        }

        // Generate new short link
        $original_url = get_permalink($post_id);
        $default_length = get_option('switchboard_link_shortener_default_length', 6);
        $short_code = $this->generate_unique_code($default_length);

        global $wpdb;

        $result = $wpdb->insert(
            $this->links_table,
            array(
                'short_code' => $short_code,
                'original_url' => $original_url,
                'post_id' => $post_id,
                'is_active' => 1,
                'created_by' => get_current_user_id()
            ),
            array('%s', '%s', '%d', '%d', '%d')
        );

        if ($result) {
            $link_id = $wpdb->insert_id;

            // Save to post meta
            update_post_meta($post_id, '_switchboard_short_link_id', $link_id);
            update_post_meta($post_id, '_switchboard_short_link_code', $short_code);

            $slug = get_option('switchboard_link_shortener_slug', 'go');
            $short_url = home_url('/' . $slug . '/' . $short_code);

            wp_send_json_success(array(
                'link_id' => $link_id,
                'short_code' => $short_code,
                'short_url' => $short_url
            ));
        } else {
            wp_send_json_error('Failed to create short link');
        }
    }

    /**
     * Generate unique short code
     */
    private function generate_unique_code($length = 6) {
        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        $max_attempts = 10;

        global $wpdb;

        for ($i = 0; $i < $max_attempts; $i++) {
            $code = '';
            for ($j = 0; $j < $length; $j++) {
                $code .= $chars[rand(0, strlen($chars) - 1)];
            }

            $exists = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$this->links_table} WHERE short_code = %s",
                $code
            ));

            if (!$exists) {
                return $code;
            }
        }

        // If all attempts failed, append timestamp
        return substr($code, 0, $length - 3) . substr(time(), -3);
    }

    /**
     * AJAX handler for bulk actions
     */
    public function ajax_bulk_action() {
        check_ajax_referer('switchboard_short_links', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }

        $action = isset($_POST['bulk_action']) ? sanitize_text_field($_POST['bulk_action']) : '';
        $link_ids = isset($_POST['link_ids']) ? array_map('intval', $_POST['link_ids']) : array();

        if (empty($action) || empty($link_ids)) {
            wp_send_json_error('Invalid request');
        }

        $this->handle_bulk_action($action, $link_ids);
        wp_send_json_success(count($link_ids) . ' link(s) processed.');
    }

    /**
     * Handle bulk actions
     */
    private function handle_bulk_action($action, $link_ids) {
        global $wpdb;

        $link_ids = array_map('intval', $link_ids);
        $ids_placeholder = implode(',', array_fill(0, count($link_ids), '%d'));

        switch ($action) {
            case 'activate':
                $wpdb->query($wpdb->prepare(
                    "UPDATE {$this->links_table} SET is_active = 1 WHERE id IN ($ids_placeholder)",
                    $link_ids
                ));
                break;

            case 'deactivate':
                $wpdb->query($wpdb->prepare(
                    "UPDATE {$this->links_table} SET is_active = 0 WHERE id IN ($ids_placeholder)",
                    $link_ids
                ));
                break;

            case 'delete':
                foreach ($link_ids as $link_id) {
                    $this->delete_link($link_id);
                }
                break;
        }
    }

    /**
     * Delete link and its analytics
     */
    private function delete_link($link_id) {
        global $wpdb;

        // Delete analytics
        $wpdb->delete($this->analytics_table, array('link_id' => $link_id), array('%d'));

        // Delete link
        $result = $wpdb->delete($this->links_table, array('id' => $link_id), array('%d'));

        return $result !== false;
    }

    /**
     * Handle CSV export
     */
    public function handle_csv_export() {
        if (isset($_GET['page']) && $_GET['page'] === 'switchboard-short-links' &&
            isset($_GET['action']) && $_GET['action'] === 'export_csv' &&
            isset($_GET['_wpnonce'])) {

            if (!wp_verify_nonce($_GET['_wpnonce'], 'export_short_links_csv')) {
                wp_die('Invalid nonce');
            }

            if (!current_user_can('manage_options')) {
                wp_die('Permission denied');
            }

            global $wpdb;
            $links = $wpdb->get_results("SELECT * FROM {$this->links_table} ORDER BY created_at DESC");

            $slug = get_option('switchboard_link_shortener_slug', 'go');

            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="short-links-' . date('Y-m-d') . '.csv"');
            header('Pragma: no-cache');
            header('Expires: 0');

            $output = fopen('php://output', 'w');

            fputcsv($output, array('ID', 'Short Code', 'Short URL', 'Original URL', 'Clicks', 'Status', 'Expires At', 'Created At'));

            foreach ($links as $link) {
                $short_url = home_url('/' . $slug . '/' . $link->short_code);
                $status = $link->is_active == 1 ? 'Active' : 'Inactive';

                if ($link->expires_at && strtotime($link->expires_at) < time()) {
                    $status = 'Expired';
                }

                fputcsv($output, array(
                    $link->id,
                    $link->short_code,
                    $short_url,
                    $link->original_url,
                    $link->click_count,
                    $status,
                    $link->expires_at ?: 'Never',
                    $link->created_at
                ));
            }

            fclose($output);
            exit;
        }
    }

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return array(
            'options' => array(
                'switchboard_link_shortener_slug',
                'switchboard_link_shortener_default_length',
                'switchboard_link_shortener_global_password',
                'switchboard_link_shortener_global_expire_redirect',
                'switchboard_link_shortener_rewrite_flushed',
            ),
            'option_patterns' => array(),
            'tables' => array(
                $this->links_table,
                $this->analytics_table,
            ),
            'post_meta' => array(
                '_switchboard_short_link_id',
                '_switchboard_short_link_code',
            ),
            'user_meta' => array(),
        );
    }
}

// Initialize the module
$switchboard_instance = SwitchboardLinkShortener::get_instance();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
