<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class LiveLang_Admin {

    /** @var LiveLang_DB */
    protected $db;

    protected $available_langs = array(
        'af' => 'Afrikaans',
        'sq' => 'Albanian',
        'am' => 'Amharic',
        'ar' => 'Arabic',
        'hy' => 'Armenian',
        'az' => 'Azerbaijani',
        'eu' => 'Basque',
        'be' => 'Belarusian',
        'bn' => 'Bengali',
        'bs' => 'Bosnian',
        'bg' => 'Bulgarian',
        'ca' => 'Catalan',
        'zh' => 'Chinese',
        'hr' => 'Croatian',
        'cs' => 'Czech',
        'da' => 'Danish',
        'nl' => 'Dutch',
        'en' => 'English',
        'et' => 'Estonian',
        'fi' => 'Finnish',
        'fr' => 'French',
        'gl' => 'Galician',
        'ka' => 'Georgian',
        'de' => 'German',
        'el' => 'Greek',
        'gu' => 'Gujarati',
        'he' => 'Hebrew',
        'hi' => 'Hindi',
        'hu' => 'Hungarian',
        'is' => 'Icelandic',
        'id' => 'Indonesian',
        'it' => 'Italian',
        'ja' => 'Japanese',
        'kn' => 'Kannada',
        'kk' => 'Kazakh',
        'km' => 'Khmer',
        'ko' => 'Korean',
        'lo' => 'Lao',
        'lv' => 'Latvian',
        'lt' => 'Lithuanian',
        'mk' => 'Macedonian',
        'ms' => 'Malay',
        'ml' => 'Malayalam',
        'mt' => 'Maltese',
        'mr' => 'Marathi',
        'mn' => 'Mongolian',
        'ne' => 'Nepali',
        'nb' => 'Norwegian Bokmål',
        'nn' => 'Norwegian Nynorsk',
        'fa' => 'Persian',
        'pl' => 'Polish',
        'pt' => 'Portuguese',
        'pa' => 'Punjabi',
        'ro' => 'Romanian',
        'ru' => 'Russian',
        'sr' => 'Serbian',
        'si' => 'Sinhala',
        'sk' => 'Slovak',
        'sl' => 'Slovenian',
        'es' => 'Spanish',
        'sw' => 'Swahili',
        'sv' => 'Swedish',
        'ta' => 'Tamil',
        'te' => 'Telugu',
        'th' => 'Thai',
        'tr' => 'Turkish',
        'uk' => 'Ukrainian',
        'ur' => 'Urdu',
        'uz' => 'Uzbek',
        'vi' => 'Vietnamese',
        'cy' => 'Welsh',
    );

    public function __construct( $db ) {
        $this->db = $db;

        add_action( 'admin_menu', array( $this, 'register_menu' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'init', array( $this, 'check_flush_rewrite_rules' ) );
        // Add Plugin actions
		add_filter( 'plugin_action_links_' . LIVELANG_PLUGIN_BASE, [ $this, 'livelang_plugin_action_links' ], 10, 4 );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );

        add_action( 'wp_ajax_livelang_clear_translations', array( $this, 'ajax_clear_translations' ) );
        add_action( 'wp_ajax_livelang_flush_cache', array( $this, 'ajax_flush_cache' ) );
        add_action( 'admin_post_livelang_delete', array( $this, 'handle_delete' ) );
        add_action( 'admin_post_livelang_toggle_status', array( $this, 'handle_toggle_status' ) );
        add_action( 'admin_post_livelang_flush_rules', array( $this, 'handle_flush_rules' ) );
        add_action( 'admin_post_livelang_bulk_action', array( $this, 'handle_bulk_action' ) );
        add_action( 'admin_post_livelang_export_csv', array( $this, 'handle_export_csv' ) );
        add_action( 'wp_ajax_livelang_add_language', array( $this, 'ajax_add_language' ) );
        add_action( 'wp_ajax_livelang_delete_language', array( $this, 'ajax_delete_language' ) );
        add_action( 'wp_ajax_livelang_update_language', array( $this, 'ajax_update_language' ) );
        add_action( 'wp_ajax_livelang_reorder_languages', array( $this, 'ajax_reorder_languages' ) );
        add_action( 'wp_ajax_livelang_set_default_language', array( $this, 'ajax_set_default_language' ) );
        add_action( 'wp_ajax_livelang_get_languages', array( $this, 'ajax_get_languages' ) );
    }

    public function get_all_available_languages() {
        return $this->available_langs;
    }

    public function livelang_plugin_action_links( $links, $plugin_file, $plugin_data, $context ) {
        $settings_url = admin_url( 'admin.php?page=livelang-settings' );
        $links[]      = '<a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Settings', 'livelang' ) . '</a>';
        return $links;
    }

    public function register_menu() {
        add_menu_page(
            __( 'LiveLang', 'livelang' ),
            __( 'LiveLang', 'livelang' ),
            'manage_options',
            'livelang',
            array( $this, 'render_translations_page' ),
            LIVELANG_PLUGIN_URL . 'assets/images/livelang.png', // use png icon
            58
        );

        add_submenu_page(
            'livelang',
            __( 'Translations', 'livelang' ),
            __( 'Translations', 'livelang' ),
            'manage_options',
            'livelang',
            array( $this, 'render_translations_page' )
        );

        add_submenu_page(
            'livelang',
            __( 'Settings', 'livelang' ),
            __( 'Settings', 'livelang' ),
            'manage_options',
            'livelang-settings',
            array( $this, 'render_settings_page' )
        );
    }

    public function register_settings() {
        register_setting( 
            'livelang_settings_group', 
            'livelang_settings', 
            array(
                'sanitize_callback' => array( $this, 'sanitize_settings' ),
                'default' => array(
                    'translate_numbers' => 1,
                    'switcher_enabled' => 0,
                    'switcher_position' => 'bottom-right',
                    'switcher_bg_color' => '#ffffff',
                    'switcher_text_color' => '#333333',
                    'switcher_accent_color' => '#2563eb',
                ) 
            ) 
        );

        add_settings_section(
            'livelang_main',
            __( 'LiveLang Settings', 'livelang' ),
            '__return_false',
            'livelang-settings'
        );

        add_settings_field(
            'livelang_roles',
            __( 'Allowed Roles', 'livelang' ),
            array( $this, 'field_roles' ),
            'livelang-settings',
            'livelang_main'
        );



        add_settings_section(
            'livelang_filters',
            __( 'Translation Filters', 'livelang' ),
            '__return_false',
            'livelang-settings'
        );

        add_settings_field(
            'livelang_translate_numbers',
            __( 'Translate Text with Numbers', 'livelang' ),
            array( $this, 'field_translate_numbers' ),
            'livelang-settings',
            'livelang_filters'
        );

        add_settings_section(
            'livelang_maintenance',
            __( 'Maintenance Actions', 'livelang' ),
            '__return_false',
            'livelang-settings'
        );

        add_settings_field(
            'livelang_maintenance_clear',
            __( 'Clear / Manage Translation Data', 'livelang' ),
            array( $this, 'field_maintenance_clear' ),
            'livelang-settings',
            'livelang_maintenance'
        );

        add_settings_field(
            'livelang_maintenance_flush',
            __( 'Flush Rewrite Rules', 'livelang' ),
            array( $this, 'field_maintenance_flush' ),
            'livelang-settings',
            'livelang_maintenance'
        );
    }

    public function check_flush_rewrite_rules() {
        if ( get_option( 'livelang_flush_rewrite_rules' ) ) {
            flush_rewrite_rules( true );
            delete_option( 'livelang_flush_rewrite_rules' );
        }
    }

    public function sanitize_settings( $input ) {
        $output = array();

        $output['allowed_roles'] = array();
        if ( ! empty( $input['allowed_roles'] ) && is_array( $input['allowed_roles'] ) ) {
            foreach ( $input['allowed_roles'] as $role ) {
                $output['allowed_roles'][] = sanitize_text_field( $role );
            }
        }

        $output['translate_numbers'] = ! empty( $input['translate_numbers'] ) ? 1 : 0;

        $output['switcher_enabled'] = ! empty( $input['switcher_enabled'] ) ? 1 : 0;
        $output['switcher_position'] = isset( $input['switcher_position'] ) ? sanitize_text_field( $input['switcher_position'] ) : 'bottom-right';
        $output['switcher_bg_color'] = isset( $input['switcher_bg_color'] ) ? sanitize_hex_color( $input['switcher_bg_color'] ) : '#ffffff';
        $output['switcher_text_color'] = isset( $input['switcher_text_color'] ) ? sanitize_hex_color( $input['switcher_text_color'] ) : '#333333';
        $output['switcher_accent_color'] = isset( $input['switcher_accent_color'] ) ? sanitize_hex_color( $input['switcher_accent_color'] ) : '#2563eb';

        return $output;
    }



    public function field_enabled() {
        $options = get_option( 'livelang_settings', array() );
        $enabled = ! empty( $options['enabled'] );
        ?>
        <label>
            <input type="checkbox" name="livelang_settings[enabled]" value="1" <?php checked( $enabled ); ?>>
            <?php esc_html_e( 'Enable plugin functionality', 'livelang' ); ?>
        </label>
        <?php
    }

    public function field_roles() {
        $options = get_option( 'livelang_settings', array() );
        $allowed = isset( $options['allowed_roles'] ) ? (array) $options['allowed_roles'] : array();

        global $wp_roles;
        $roles = $wp_roles->roles;
        ?>
        <fieldset>
            <!-- all -->
            <label>
                <input type="checkbox" name="livelang_settings[allowed_roles][]" value="all"
                    <?php checked( in_array( 'all', $allowed, true ) ); ?>>
                <?php esc_html_e( 'All Roles', 'livelang' ); ?>
            </label>
            <br><br>
            <?php foreach ( $roles as $role_key => $role ) : ?>
                <label>
                    <input type="checkbox" name="livelang_settings[allowed_roles][]" value="<?php echo esc_attr( $role_key ); ?>"
                        <?php checked( in_array( $role_key, $allowed, true ) ); ?>>
                    <?php echo esc_html( $role['name'] ); ?>
                </label><br>
            <?php endforeach; ?>
            <p class="description">
                <?php esc_html_e( 'Only selected roles will see the frontend translation mode toggle.', 'livelang' ); ?>
            </p>
        </fieldset>
        <?php
    }

    public function field_translate_numbers() {
        $options = get_option( 'livelang_settings', array() );
        $translate_numbers = isset($options['translate_numbers']) ? $options['translate_numbers'] : 1; 
        ?>
        <label>
            <input type="checkbox" name="livelang_settings[translate_numbers]" value="1" <?php checked( 1, $translate_numbers ); ?>>
            <?php esc_html_e( 'Enable translation of text containing numbers', 'livelang' ); ?>
        </label>
        <p class="description">
            <?php esc_html_e( 'When disabled, text containing numbers (e.g., "10 English Books") will skip the number part (translate only "English Books").', 'livelang' ); ?>
        </p>
        <?php
    }

    public function field_maintenance_clear() {
        $danger_zone_url = admin_url( 'admin.php?page=livelang#livelang-danger-zone' );
        ?>
        <p>
            <a href="<?php echo esc_url( $danger_zone_url ); ?>" class="button button-secondary">
                <?php esc_html_e( 'Go to Danger Zone', 'livelang' ); ?>
            </a>
        </p>
        <p class="description">
            <?php esc_html_e( 'Clearing translation data (fully or by language/scope) now lives on the Translations screen, with an export-first option and a typed confirmation step so it can\'t be triggered by accident.', 'livelang' ); ?>
        </p>
        <?php
    }

    public function field_maintenance_flush() {
        $flush_url = wp_nonce_url( admin_url( 'admin-post.php?action=livelang_flush_rules' ), 'livelang_flush_rules_nonce' );
        ?>
        <a href="<?php echo esc_url( $flush_url ); ?>" class="button button-secondary">
            <?php esc_html_e( 'Flush Rewrite Rules', 'livelang' ); ?>
        </a>
        <p><?php esc_html_e( 'Use this if language permalinks lead to a 404 error.', 'livelang' ); ?></p>
        <?php
    }

    public function render_settings_page() {
        $options = get_option( 'livelang_settings', array() );
        $grand_total = $this->db->get_total_count();
        $active_total = $this->db->get_total_count( array( 'status' => 'active' ) );
        $configured_langs = $this->get_languages();
        ?>
        <div class="wrap">
            <div class="livelang-admin-dashboard">
                <!-- Header -->
                <header class="livelang-header">
                    <div class="livelang-header-left">
                        <div class="livelang-brand-icon">⚡</div>
                        <div>
                            <h1>
                                <?php esc_html_e( 'LiveLang Pro Settings', 'livelang' ); ?>
                                <span class="livelang-header-badge">v<?php echo esc_html( LIVELANG_VERSION ); ?></span>
                            </h1>
                        </div>
                    </div>
                    <div class="livelang-header-actions">
                        <a href="<?php echo esc_url( home_url( '/?livelang_edit=1' ) ); ?>" target="_blank" class="livelang-btn livelang-btn-primary">
                            <span class="dashicons dashicons-welcome-write-blog"></span>
                            <?php esc_html_e( 'Open Visual Translator', 'livelang' ); ?>
                        </a>
                        <button type="button" class="livelang-btn livelang-btn-outline" id="livelang-quick-flush-btn" data-nonce="<?php echo esc_attr( wp_create_nonce( 'livelang_flush_cache' ) ); ?>">
                            <span class="dashicons dashicons-update"></span>
                            <?php esc_html_e( 'Flush Cache', 'livelang' ); ?>
                        </button>
                    </div>
                </header>

                <!-- Metrics Overview Row -->
                <div class="livelang-stats-row">
                    <div class="livelang-stat-card">
                        <div class="livelang-stat-icon-wrap blue">
                            <span class="dashicons dashicons-translation"></span>
                        </div>
                        <div>
                            <div class="livelang-stat-value"><?php echo esc_html( $grand_total ); ?></div>
                            <div class="livelang-stat-label"><?php esc_html_e( 'Total Strings', 'livelang' ); ?></div>
                        </div>
                    </div>
                    <div class="livelang-stat-card">
                        <div class="livelang-stat-icon-wrap green">
                            <span class="dashicons dashicons-yes-alt"></span>
                        </div>
                        <div>
                            <div class="livelang-stat-value"><?php echo esc_html( $active_total ); ?></div>
                            <div class="livelang-stat-label"><?php esc_html_e( 'Active Translations', 'livelang' ); ?></div>
                        </div>
                    </div>
                    <div class="livelang-stat-card">
                        <div class="livelang-stat-icon-wrap purple">
                            <span class="dashicons dashicons-admin-site-alt3"></span>
                        </div>
                        <div>
                            <div class="livelang-stat-value"><?php echo esc_html( count( $configured_langs ) ); ?></div>
                            <div class="livelang-stat-label"><?php esc_html_e( 'Languages', 'livelang' ); ?></div>
                        </div>
                    </div>
                    <div class="livelang-stat-card">
                        <div class="livelang-stat-icon-wrap amber">
                            <span class="dashicons dashicons-shield"></span>
                        </div>
                        <div>
                            <div class="livelang-stat-value"><?php echo esc_html( $this->db->get_total_count( array( 'is_global' => 1 ) ) ); ?></div>
                            <div class="livelang-stat-label"><?php esc_html_e( 'Global Rules', 'livelang' ); ?></div>
                        </div>
                    </div>
                </div>

                <div class="livelang-main-layout">
                    <!-- Sidebar Nav -->
                    <aside class="livelang-sidebar">
                        <div class="livelang-sidebar-label"><?php esc_html_e( 'Navigation', 'livelang' ); ?></div>
                        <?php
                        $current_tab = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : 'general'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                        $nav_items = array(
                            'general'   => array( 'label' => __( 'General Settings', 'livelang' ), 'icon' => 'admin-generic' ),
                            'languages' => array( 'label' => __( 'Language Manager', 'livelang' ), 'icon' => 'translation' ),
                            'switcher'  => array( 'label' => __( 'Switcher Style', 'livelang' ), 'icon' => 'admin-appearance' ),
                            'help'      => array( 'label' => __( 'Help & Shortcodes', 'livelang' ), 'icon' => 'editor-help' ),
                        );

                        foreach ( $nav_items as $id => $item ) :
                            $active_class = ( $current_tab === $id ) ? 'is-active' : '';
                            $url = add_query_arg( 'tab', $id, admin_url( 'admin.php?page=livelang-settings' ) );
                            ?>
                            <a href="<?php echo esc_url( $url ); ?>" class="livelang-nav-item <?php echo esc_attr( $active_class ); ?>" data-livelang-tab="<?php echo esc_attr( $id ); ?>">
                                <span class="dashicons dashicons-<?php echo esc_attr( $item['icon'] ); ?>"></span>
                                <?php echo esc_html( $item['label'] ); ?>
                            </a>
                        <?php endforeach; ?>
                        
                        <div style="margin-top:20px; padding:12px; background:#f8fafc; border-radius:8px; border:1px solid #e2e8f0; font-size:12px; color:#64748b;">
                            <strong style="color:#0f172a; display:block; margin-bottom:4px;">💡 Pro Tip</strong>
                            Translate text directly on your frontend site using the high-productivity visual editor!
                        </div>
                    </aside>

                    <!-- Content Area -->
                    <main class="livelang-content">
                        
                        <!-- General Settings -->
                        <div id="livelang-tab-general" class="livelang-tab-panel <?php echo ( $current_tab === 'general' ) ? 'is-active' : ''; ?>">
                            <div class="livelang-card">
                                <div class="livelang-card-header">
                                    <h2><span class="dashicons dashicons-admin-generic" style="color:var(--ll-primary);"></span> <?php esc_html_e( 'Core Configuration', 'livelang' ); ?></h2>
                                </div>
                                <div class="livelang-card-body">
                                    <form method="post" action="options.php">
                                        <?php settings_fields( 'livelang_settings_group' ); ?>
                                        <table class="livelang-settings-table">
                                            <tr>
                                                <th><?php esc_html_e( 'Allowed User Roles', 'livelang' ); ?></th>
                                                <td>
                                                    <div style="display:grid; grid-template-columns: repeat(2, 1fr); gap:12px;">
                                                        <?php
                                                        $roles = get_editable_roles();
                                                        $allowed_roles = isset( $options['allowed_roles'] ) ? (array) $options['allowed_roles'] : array( 'administrator' );
                                                        foreach ( $roles as $role_key => $role_data ) :
                                                            ?>
                                                            <label style="font-size:13px; font-weight:500; display:flex; align-items:center; gap:8px;">
                                                                <input type="checkbox" name="livelang_settings[allowed_roles][]" value="<?php echo esc_attr( $role_key ); ?>" <?php checked( in_array( $role_key, $allowed_roles, true ) ); ?>>
                                                                <?php echo esc_html( $role_data['name'] ); ?>
                                                            </label>
                                                            <?php
                                                        endforeach;
                                                        ?>
                                                    </div>
                                                </td>
                                            </tr>
                                             <tr>
                                                <th><?php esc_html_e( 'Translate Dynamic Numbers', 'livelang' ); ?></th>
                                                <td>
                                                    <label class="livelang-switch">
                                                        <input type="checkbox" name="livelang_settings[translate_numbers]" value="1" <?php checked( $options['translate_numbers'] ?? 1, 1 ); ?>>
                                                        <span class="livelang-slider"></span>
                                                    </label>
                                                    <p class="description" style="margin-top:6px; color:var(--ll-text-muted);"><?php esc_html_e( 'Automatically match strings with dynamic numbers using the {NUM} placeholder engine (e.g. "Showing all 4 results").', 'livelang' ); ?></p>
                                                </td>
                                            </tr>
                                        </table>
                                        <div style="margin-top:24px; padding-top:20px; border-top:1px solid var(--ll-border);">
                                            <button type="submit" class="livelang-btn livelang-btn-primary">
                                                <span class="dashicons dashicons-saved"></span>
                                                <?php esc_html_e( 'Save Configuration', 'livelang' ); ?>
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <div class="livelang-card">
                                <div class="livelang-card-header">
                                    <h2><span class="dashicons dashicons-update" style="color:var(--ll-success);"></span> <?php esc_html_e( 'System Maintenance & Rules', 'livelang' ); ?></h2>
                                </div>
                                <div class="livelang-card-body">
                                    <div style="display:flex; gap:14px;">
                                        <button type="button" class="livelang-btn livelang-btn-outline" id="livelang-flush-cache-btn-main" data-nonce="<?php echo esc_attr( wp_create_nonce( 'livelang_flush_cache' ) ); ?>">
                                            <span class="dashicons dashicons-update"></span>
                                            <?php esc_html_e( 'Flush Translation Cache', 'livelang' ); ?>
                                        </button>
                                        <?php 
                                        $flush_url = wp_nonce_url( admin_url( 'admin-post.php?action=livelang_flush_rules' ), 'livelang_flush_rules_nonce' );
                                        ?>
                                        <a href="<?php echo esc_url( $flush_url ); ?>" class="livelang-btn livelang-btn-outline">
                                            <span class="dashicons dashicons-admin-links"></span>
                                            <?php esc_html_e( 'Fix Links & Permalinks (404)', 'livelang' ); ?>
                                        </a>
                                    </div>
                                    <p class="description" style="margin-top:12px; color:var(--ll-text-muted);">
                                        <?php esc_html_e( 'Safe maintenance actions. Flushing cache clears lookups without affecting translation data.', 'livelang' ); ?>
                                    </p>
                                </div>
                            </div>
                        </div>

                        <!-- Languages Settings -->
                        <div id="livelang-tab-languages" class="livelang-tab-panel <?php echo ( $current_tab === 'languages' ) ? 'is-active' : ''; ?>">
                            <div class="livelang-card">
                                <div class="livelang-card-header">
                                    <h2><span class="dashicons dashicons-translation" style="color:var(--ll-primary);"></span> <?php esc_html_e( 'Language Manager', 'livelang' ); ?></h2>
                                </div>
                                <div class="livelang-card-body">
                                    <table class="livelang-table" style="margin-bottom:24px;">
                                        <thead>
                                            <tr>
                                                <th style="width:40px;"></th>
                                                <th><?php esc_html_e( 'Code', 'livelang' ); ?></th>
                                                <th><?php esc_html_e( 'Display Name', 'livelang' ); ?></th>
                                                <th style="text-align:center;"><?php esc_html_e( 'Default', 'livelang' ); ?></th>
                                                <th style="width:120px; text-align:right;"><?php esc_html_e( 'Actions', 'livelang' ); ?></th>
                                            </tr>
                                        </thead>
                                        <tbody id="livelang-languages-tbody">
                                            <!-- Dynamic Content -->
                                        </tbody>
                                    </table>

                                    <div style="padding:18px; background:var(--ll-bg-alt); border-radius:10px; border:1px dashed var(--ll-border-strong);">
                                        <div style="display:flex; gap:12px; align-items:center;">
                                            <select id="livelang-language-code" style="flex:1; max-width:100%;">
                                                <option value=""><?php esc_html_e( 'Choose language to add...', 'livelang' ); ?></option>
                                                <?php
                                                $all_langs = $this->get_all_available_languages();
                                                foreach ( $all_langs as $code => $name ) {
                                                    echo '<option value="' . esc_attr( $code ) . '">' . esc_html( $name ) . ' (' . esc_html( $code ) . ')</option>';
                                                }
                                                ?>
                                            </select>
                                            <button type="button" id="livelang-add-language-btn" class="livelang-btn livelang-btn-primary">
                                                <span class="dashicons dashicons-plus-alt2"></span>
                                                <?php esc_html_e( 'Add Language', 'livelang' ); ?>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Switcher Style Settings -->
                        <div id="livelang-tab-switcher" class="livelang-tab-panel <?php echo ( $current_tab === 'switcher' ) ? 'is-active' : ''; ?>">
                            <div class="livelang-visual-settings">
                                <div class="livelang-settings-col">
                                    <div class="livelang-card">
                                        <div class="livelang-card-header">
                                            <h2><span class="dashicons dashicons-admin-appearance" style="color:var(--ll-primary);"></span> <?php esc_html_e( 'Switcher Options', 'livelang' ); ?></h2>
                                        </div>
                                        <div class="livelang-card-body">
                                            <form method="post" action="options.php">
                                                <?php settings_fields( 'livelang_settings_group' ); ?>
                                                <table class="livelang-settings-table">
                                                    <tr>
                                                        <th style="width:180px;"><?php esc_html_e( 'Show Switcher', 'livelang' ); ?></th>
                                                        <td>
                                                            <label class="livelang-switch">
                                                                <input type="checkbox" name="livelang_settings[switcher_enabled]" id="livelang-switcher-enabled" value="1" <?php checked( $options['switcher_enabled'] ?? 1, 1 ); ?>>
                                                                <span class="livelang-slider"></span>
                                                            </label>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <th><?php esc_html_e( 'Position', 'livelang' ); ?></th>
                                                        <td>
                                                            <select name="livelang_settings[switcher_position]" id="livelang-switcher-position">
                                                                <option value="bottom-right" <?php selected( $options['switcher_position'] ?? 'bottom-right', 'bottom-right' ); ?>><?php esc_html_e( 'Bottom Right', 'livelang' ); ?></option>
                                                                <option value="bottom-left" <?php selected( $options['switcher_position'] ?? 'bottom-right', 'bottom-left' ); ?>><?php esc_html_e( 'Bottom Left', 'livelang' ); ?></option>
                                                                <option value="top-right" <?php selected( $options['switcher_position'] ?? 'bottom-right', 'top-right' ); ?>><?php esc_html_e( 'Top Right', 'livelang' ); ?></option>
                                                                <option value="top-left" <?php selected( $options['switcher_position'] ?? 'bottom-right', 'top-left' ); ?>><?php esc_html_e( 'Top Left', 'livelang' ); ?></option>
                                                            </select>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <th><?php esc_html_e( 'Theme Colors', 'livelang' ); ?></th>
                                                        <td>
                                                            <div style="display:flex; gap:16px; align-items:center;">
                                                                <div style="display:flex; flex-direction:column; gap:4px;">
                                                                    <small style="color:var(--ll-text-muted); font-weight:600;">Background</small>
                                                                    <input type="color" name="livelang_settings[switcher_bg_color]" id="livelang-switcher-bg-color" value="<?php echo esc_attr( $options['switcher_bg_color'] ?? '#ffffff' ); ?>" style="width:44px; height:40px; padding:2px; border:1px solid #cbd5e1; border-radius:6px; cursor:pointer;">
                                                                </div>
                                                                <div style="display:flex; flex-direction:column; gap:4px;">
                                                                    <small style="color:var(--ll-text-muted); font-weight:600;">Text</small>
                                                                    <input type="color" name="livelang_settings[switcher_text_color]" id="livelang-switcher-text-color" value="<?php echo esc_attr( $options['switcher_text_color'] ?? '#333333' ); ?>" style="width:44px; height:40px; padding:2px; border:1px solid #cbd5e1; border-radius:6px; cursor:pointer;">
                                                                </div>
                                                                <div style="display:flex; flex-direction:column; gap:4px;">
                                                                    <small style="color:var(--ll-text-muted); font-weight:600;">Accent</small>
                                                                    <input type="color" name="livelang_settings[switcher_accent_color]" id="livelang-switcher-accent-color" value="<?php echo esc_attr( $options['switcher_accent_color'] ?? '#2563eb' ); ?>" style="width:44px; height:40px; padding:2px; border:1px solid #cbd5e1; border-radius:6px; cursor:pointer;">
                                                                </div>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                </table>
                                                <div style="margin-top:24px;">
                                                    <button type="submit" class="livelang-btn livelang-btn-primary">
                                                        <span class="dashicons dashicons-saved"></span>
                                                        <?php esc_html_e( 'Save Styling', 'livelang' ); ?>
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>

                                <div class="livelang-preview-col">
                                    <div class="livelang-card" style="position:sticky; top:20px;">
                                        <div class="livelang-card-header">
                                            <h2><span class="dashicons dashicons-visibility"></span> <?php esc_html_e( 'Live Preview', 'livelang' ); ?></h2>
                                        </div>
                                        <div class="livelang-card-body" style="padding:12px;">
                                            <div class="livelang-preview-canvas">
                                                <div class="livelang-mock-browser">
                                                    <div class="livelang-browser-header">
                                                        <span class="livelang-dot" style="background:#ff5f56"></span>
                                                        <span class="livelang-dot" style="background:#ffbd2e"></span>
                                                        <span class="livelang-dot" style="background:#27c93f"></span>
                                                    </div>
                                                    <div style="padding:24px; flex:1; position:relative; background:#ffffff;">
                                                        <div style="height:12px; width:65%; background:#f1f5f9; margin-bottom:12px; border-radius:3px;"></div>
                                                        <div style="height:12px; width:90%; background:#f1f5f9; margin-bottom:12px; border-radius:3px;"></div>
                                                        <div style="height:12px; width:45%; background:#f1f5f9; border-radius:3px;"></div>

                                                        <div id="livelang-floating-preview" class="livelang-floating-preview bottom-right" style="position:absolute;">
                                                            <div class="livelang-preview-btn">
                                                                <span class="livelang-preview-flag">🇺🇸</span>
                                                                <span class="livelang-preview-label"><?php esc_html_e( 'English', 'livelang' ); ?></span>
                                                                <span class="livelang-preview-arrow">▾</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Help & Resources -->
                        <div id="livelang-tab-help" class="livelang-tab-panel <?php echo ( $current_tab === 'help' ) ? 'is-active' : ''; ?>">
                            <div class="livelang-card">
                                <div class="livelang-card-header">
                                    <h2><span class="dashicons dashicons-lightbulb" style="color:var(--ll-warning);"></span> <?php esc_html_e( 'Quickstart Guide', 'livelang' ); ?></h2>
                                </div>
                                <div class="livelang-card-body">
                                    <ul style="list-style:decimal; padding-left:20px; font-size:14px; line-height:1.8; color:var(--ll-dark);">
                                        <li><strong>Add Secondary Languages</strong>: Navigate to the Language Manager tab and add your target languages.</li>
                                        <li><strong>Open Visual Translator</strong>: Click the <code>Open Visual Translator</code> button at top right or visit your website while logged in.</li>
                                        <li><strong>Click & Translate</strong>: Hover over any text string or image, click to translate, and hit <code>Save & Next ↵</code>!</li>
                                    </ul>
                                </div>
                            </div>

                             <div class="livelang-card">
                                <div class="livelang-card-header">
                                    <h2><span class="dashicons dashicons-shortcode"></span> <?php esc_html_e( 'Shortcodes', 'livelang' ); ?></h2>
                                </div>
                                <div class="livelang-card-body">
                                    <p style="font-size:13px; color:var(--ll-text-muted);"><?php esc_html_e( 'Display the language switcher anywhere in your header, footer, or menu:', 'livelang' ); ?></p>
                                    <code class="livelang-code-chip" style="display:inline-block; font-size:14px; padding:10px 16px; margin:10px 0;">[livelang_language_switcher]</code>
                                </div>
                            </div>
                        </div>
                    </main>
                </div>
            </div>
        </div>
        <?php
    }

    private function get_allowed_html_for_dash() {
        return array(
            'b'      => array(),
            'strong' => array(),
            'i'      => array(),
            'em'     => array(),
            'a'      => array( 'href' => true, 'title' => true, 'target' => true ),
            'span'   => array( 'class' => true, 'style' => true ),
            'br'     => array(),
            'u'      => array(),
        );
    }

    public function render_translations_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $items_per_page = 20;
        $current_page   = isset( $_GET['paged'] ) ? max( 1, intval( $_GET['paged'] ) ) : 1; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $offset         = ( $current_page - 1 ) * $items_per_page;

        $search   = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $language = isset( $_GET['language'] ) ? sanitize_text_field( wp_unslash( $_GET['language'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $status   = isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        $filter_args = array(
            'search'   => $search,
            'language' => $language,
            'status'   => $status,
        );

        $total_items       = $this->db->get_total_count( $filter_args );
        $translations      = $this->db->get_all( $items_per_page, $offset, $filter_args );
        $total_pages       = max( 1, ceil( $total_items / $items_per_page ) );
        $grand_total       = $this->db->get_total_count();
        $active_total      = $this->db->get_total_count( array( 'status' => 'active' ) );
        $available_langs   = $this->db->get_distinct_languages();
        $configured_langs  = $this->get_languages();

        $base_url = remove_query_arg( array( 'paged', 'livelang_bulk_nonce' ) );

        ?>
        <div class="wrap">
            <div class="livelang-admin-dashboard">
                <header class="livelang-header">
                    <div class="livelang-header-left">
                        <div class="livelang-brand-icon">🗃️</div>
                        <div>
                            <h1>
                                <?php esc_html_e( 'Stored Translations', 'livelang' ); ?>
                                <span class="livelang-header-badge"><?php echo esc_html( $grand_total ); ?> <?php esc_html_e( 'Records', 'livelang' ); ?></span>
                            </h1>
                        </div>
                    </div>
                    <div class="livelang-header-actions">
                         <a href="#livelang-danger-zone" class="livelang-btn livelang-btn-outline">
                            <span class="dashicons dashicons-shield"></span>
                            <?php esc_html_e( 'Danger Zone / Delete Data', 'livelang' ); ?>
                        </a>
                    </div>
                </header>

                <div class="livelang-stats-row">
                    <div class="livelang-stat-card">
                        <div class="livelang-stat-icon-wrap blue">
                            <span class="dashicons dashicons-translation"></span>
                        </div>
                        <div>
                            <div class="livelang-stat-value"><?php echo esc_html( $grand_total ); ?></div>
                            <div class="livelang-stat-label"><?php esc_html_e( 'Total Strings', 'livelang' ); ?></div>
                        </div>
                    </div>
                    <div class="livelang-stat-card">
                        <div class="livelang-stat-icon-wrap green">
                            <span class="dashicons dashicons-yes-alt"></span>
                        </div>
                        <div>
                            <div class="livelang-stat-value"><?php echo esc_html( $active_total ); ?></div>
                            <div class="livelang-stat-label"><?php esc_html_e( 'Active Strings', 'livelang' ); ?></div>
                        </div>
                    </div>
                    <div class="livelang-stat-card">
                        <div class="livelang-stat-icon-wrap purple">
                            <span class="dashicons dashicons-admin-site-alt3"></span>
                        </div>
                        <div>
                            <div class="livelang-stat-value"><?php echo esc_html( count( $configured_langs ) ); ?></div>
                            <div class="livelang-stat-label"><?php esc_html_e( 'Languages', 'livelang' ); ?></div>
                        </div>
                    </div>
                </div>

            <div class="livelang-card" style="margin-bottom:20px;">
                <div class="livelang-card-body livelang-filters-bar">
                    <form method="get" class="livelang-filters-form">
                        <input type="hidden" name="page" value="livelang">
                        <div class="livelang-search-wrap">
                            <span class="dashicons dashicons-search"></span>
                            <input type="search" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Search original or translated text…', 'livelang' ); ?>">
                        </div>
                        <select name="language">
                            <option value=""><?php esc_html_e( 'All Languages', 'livelang' ); ?></option>
                            <?php foreach ( $available_langs as $lang_code ) : ?>
                                <option value="<?php echo esc_attr( $lang_code ); ?>" <?php selected( $language, $lang_code ); ?>><?php echo esc_html( strtoupper( $lang_code ) ); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <select name="status">
                            <option value=""><?php esc_html_e( 'All Statuses', 'livelang' ); ?></option>
                            <option value="active" <?php selected( $status, 'active' ); ?>><?php esc_html_e( 'Active', 'livelang' ); ?></option>
                            <option value="inactive" <?php selected( $status, 'inactive' ); ?>><?php esc_html_e( 'Inactive', 'livelang' ); ?></option>
                        </select>
                        <button type="submit" class="livelang-btn livelang-btn-primary">
                            <span class="dashicons dashicons-filter" style="margin-right:4px;"></span>
                            <?php esc_html_e( 'Filter', 'livelang' ); ?>
                        </button>
                        <?php if ( $search || $language || $status ) : ?>
                            <a href="<?php echo esc_url( remove_query_arg( array( 's', 'language', 'status', 'paged' ) ) ); ?>" class="livelang-btn livelang-btn-outline">
                                <span class="dashicons dashicons-dismiss" style="margin-right:4px;"></span>
                                <?php esc_html_e( 'Reset', 'livelang' ); ?>
                            </a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>

            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" id="livelang-bulk-form">
                <input type="hidden" name="action" value="livelang_bulk_action">
                <?php wp_nonce_field( 'livelang_bulk_action_nonce' ); ?>
                <input type="hidden" name="redirect_to" value="<?php echo esc_url( $base_url . ( $current_page > 1 ? '&paged=' . $current_page : '' ) ); ?>">

                <div class="livelang-bulk-actions-bar">
                    <select name="bulk_action">
                        <option value=""><?php esc_html_e( 'Bulk actions', 'livelang' ); ?></option>
                        <option value="activate"><?php esc_html_e( 'Mark Active', 'livelang' ); ?></option>
                        <option value="deactivate"><?php esc_html_e( 'Mark Inactive', 'livelang' ); ?></option>
                        <option value="delete"><?php esc_html_e( 'Delete', 'livelang' ); ?></option>
                    </select>
                    <button type="submit" class="livelang-btn livelang-btn-outline" onclick="return confirm('<?php echo esc_js( __( 'Apply this bulk action to all selected rows?', 'livelang' ) ); ?>');"><?php esc_html_e( 'Apply', 'livelang' ); ?></button>
                </div>

                <div class="livelang-card">
                    <div class="livelang-card-body" style="padding:0;">
                        <table class="livelang-table">
                            <thead>
                                <tr>
                                    <th style="width:36px;"><input type="checkbox" id="livelang-select-all"></th>
                                    <th style="width:50px;">ID</th>
                                    <th><?php esc_html_e( 'Original Content', 'livelang' ); ?></th>
                                    <th><?php esc_html_e( 'Translated Text', 'livelang' ); ?></th>
                                    <th><?php esc_html_e( 'Language', 'livelang' ); ?></th>
                                    <th><?php esc_html_e( 'Scope', 'livelang' ); ?></th>
                                    <th><?php esc_html_e( 'Status', 'livelang' ); ?></th>
                                    <th style="width:120px; text-align:right;"><?php esc_html_e( 'Actions', 'livelang' ); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php if ( ! empty( $translations ) ) : ?>
                                <?php foreach ( $translations as $row ) : ?>
                                    <tr>
                                        <td><input type="checkbox" name="ids[]" value="<?php echo esc_attr( $row->id ); ?>" class="livelang-row-checkbox"></td>
                                        <td style="color:var(--livelang-text-muted); font-size:12px;">#<?php echo esc_html( $row->id ); ?></td>
                                        <td>
                                            <div style="max-width:280px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="<?php echo esc_attr($row->original_text); ?>">
                                                <?php echo esc_html( wp_trim_words( $row->original_text, 10 ) ); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div style="font-weight:600; max-width:280px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="<?php echo esc_attr($row->translated_text); ?>">
                                                <?php echo esc_html( wp_trim_words( $row->translated_text, 10 ) ); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="livelang-header-badge" style="background:#f1f5f9; color:#475569; margin:0;">
                                                <?php echo esc_html( strtoupper($row->language) ); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($row->is_global) : ?>
                                                <span class="dashicons dashicons-admin-site" style="font-size:18px; color:var(--livelang-primary);" title="Global"></span>
                                            <?php else : ?>
                                                <span class="dashicons dashicons-media-text" style="font-size:18px; color:var(--livelang-text-muted);" title="Specific Page"></span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="livelang-status livelang-status-<?php echo esc_attr($row->status); ?>">
                                                <?php echo esc_html( ucfirst( $row->status ) ); ?>
                                            </span>
                                        </td>
                                        <td style="text-align:right;">
                                            <?php
                                            $paged_param = ( $current_page > 1 ) ? '&paged=' . $current_page : '';
                                            $toggle_url = wp_nonce_url( admin_url( 'admin-post.php?action=livelang_toggle_status&id=' . intval( $row->id ) . $paged_param ), 'livelang_toggle_' . $row->id );
                                            $delete_url = wp_nonce_url( admin_url( 'admin-post.php?action=livelang_delete&id=' . intval( $row->id ) . $paged_param ), 'livelang_delete_' . $row->id );
                                            ?>
                                            <a href="<?php echo esc_url( $toggle_url ); ?>" class="dashicons dashicons-visibility" style="text-decoration:none; color:var(--livelang-text-muted); margin-right:12px; font-size:18px;" title="Toggle Status"></a>
                                            <a href="<?php echo esc_url( $delete_url ); ?>" class="dashicons dashicons-trash" style="text-decoration:none; color:var(--livelang-danger); font-size:18px;" title="Delete" onclick="return confirm('<?php echo esc_js( __( 'Are you sure you want to delete this translation?', 'livelang' ) ); ?>')"></a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else : ?>
                                <tr><td colspan="8" style="text-align:center; padding:60px; color:var(--livelang-text-muted);">
                                    <span class="dashicons dashicons-translation" style="font-size:48px; width:48px; height:48px; opacity:0.2; margin-bottom:15px; display:block; margin-left:auto; margin-right:auto;"></span>
                                    <?php
                                    if ( $search || $language || $status ) {
                                        esc_html_e( 'No translations match your filters.', 'livelang' );
                                    } else {
                                        esc_html_e( 'No translation records yet. Go to the frontend to start!', 'livelang' );
                                    }
                                    ?>
                                </td></tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </form>

            <?php if ( $total_pages > 1 ) : ?>
                <div class="livelang-pagination" style="margin-top:20px; display:flex; justify-content:center;">
                    <?php
                    echo wp_kses_post( paginate_links( array(
                        'base'      => add_query_arg( 'paged', '%#%' ),
                        'format'    => '',
                        'prev_text' => '&laquo;',
                        'next_text' => '&raquo;',
                        'total'     => $total_pages,
                        'current'   => $current_page,
                    ) ) );
                    ?>
                </div>
            <?php endif; ?>

            <div class="livelang-card livelang-danger-zone" id="livelang-danger-zone">
                <div class="livelang-card-header">
                    <h2>
                        <span class="dashicons dashicons-warning" style="color:var(--livelang-danger);"></span>
                        <?php esc_html_e( 'Danger Zone', 'livelang' ); ?>
                    </h2>
                </div>
                <div class="livelang-card-body">
                    <p class="description">
                        <?php esc_html_e( 'Delete stored translation data. This is separate from the safe maintenance actions (cache flush, rewrite rules) on the Settings screen — nothing here runs unless you pick a scope and type DELETE to confirm.', 'livelang' ); ?>
                    </p>

                    <p>
                        <?php
                        $export_url = wp_nonce_url( admin_url( 'admin-post.php?action=livelang_export_csv' ), 'livelang_export_csv_nonce' );
                        ?>
                        <a href="<?php echo esc_url( $export_url ); ?>" class="livelang-btn livelang-btn-outline">
                            <span class="dashicons dashicons-download" style="margin-right:8px; font-size:16px;"></span>
                            <?php esc_html_e( 'Export All as CSV First', 'livelang' ); ?>
                        </a>
                    </p>

                    <div class="livelang-danger-form">
                        <label for="livelang-danger-scope"><?php esc_html_e( 'What do you want to delete?', 'livelang' ); ?></label>
                        <select id="livelang-danger-scope">
                            <option value=""><?php esc_html_e( '— Choose a scope —', 'livelang' ); ?></option>
                            <option value="inactive"><?php esc_html_e( 'Only inactive translations', 'livelang' ); ?></option>
                            <option value="page_specific"><?php esc_html_e( 'Only page-specific translations (keep globals)', 'livelang' ); ?></option>
                            <option value="global"><?php esc_html_e( 'Only global (site-wide) translations', 'livelang' ); ?></option>
                            <option value="language"><?php esc_html_e( 'Everything in one language…', 'livelang' ); ?></option>
                            <option value="all"><?php esc_html_e( 'Absolutely everything', 'livelang' ); ?></option>
                        </select>

                        <select id="livelang-danger-language" style="display:none;">
                            <option value=""><?php esc_html_e( '— Choose a language —', 'livelang' ); ?></option>
                            <?php foreach ( $available_langs as $lang_code ) : ?>
                                <option value="<?php echo esc_attr( $lang_code ); ?>"><?php echo esc_html( strtoupper( $lang_code ) ); ?></option>
                            <?php endforeach; ?>
                        </select>

                        <div id="livelang-danger-confirm-wrap" style="display:none;">
                            <label for="livelang-danger-confirm-input">
                                <?php
                                printf(
                                    /* translators: %s is the literal word DELETE the person must type. */
                                    esc_html__( 'Type %s to confirm:', 'livelang' ),
                                    '<code>DELETE</code>'
                                );
                                ?>
                            </label>
                            <input type="text" id="livelang-danger-confirm-input" autocomplete="off" placeholder="DELETE">
                        </div>

                        <button type="button" class="livelang-btn livelang-btn-danger" id="livelang-danger-submit" data-nonce="<?php echo esc_attr( wp_create_nonce( 'livelang_clear' ) ); ?>" disabled>
                            <?php esc_html_e( 'Permanently Delete', 'livelang' ); ?>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php
    }

    /**
     * Danger Zone: delete translations. Requires an explicit scope so a
     * mistaken click can't silently wipe everything - "All translations" is
     * still a valid scope, but it has to be chosen on purpose via the
     * scope dropdown, not triggered by a mislabeled button (see 2.2.x
     * changelog - "Flush Cache" and "Clear All" used to share one button).
     */
    public function ajax_clear_translations() {
        check_ajax_referer( 'livelang_clear' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Not allowed.', 'livelang' ) ) );
        }

        $scope    = isset( $_POST['scope'] ) ? sanitize_text_field( wp_unslash( $_POST['scope'] ) ) : '';
        $language = isset( $_POST['language'] ) ? sanitize_text_field( wp_unslash( $_POST['language'] ) ) : '';
        $confirm  = isset( $_POST['confirm_text'] ) ? sanitize_text_field( wp_unslash( $_POST['confirm_text'] ) ) : '';

        // Server-side backstop for the type-to-confirm safeguard in the UI -
        // belt and braces alongside the JS-side gate.
        if ( strtoupper( $confirm ) !== 'DELETE' ) {
            wp_send_json_error( array( 'message' => __( 'Confirmation text did not match.', 'livelang' ) ) );
        }

        switch ( $scope ) {
            case 'inactive':
                $deleted = $this->db->clear_filtered( array( 'status' => 'inactive' ) );
                break;
            case 'global':
                $deleted = $this->db->clear_filtered( array( 'is_global' => 1 ) );
                break;
            case 'page_specific':
                $deleted = $this->db->clear_filtered( array( 'is_global' => 0 ) );
                break;
            case 'language':
                if ( empty( $language ) ) {
                    wp_send_json_error( array( 'message' => __( 'Please choose a language.', 'livelang' ) ) );
                }
                $deleted = $this->db->clear_filtered( array( 'language' => $language ) );
                break;
            case 'all':
                $this->db->clear_all();
                $deleted = -1; // signal "everything", exact count not tracked by TRUNCATE.
                break;
            default:
                wp_send_json_error( array( 'message' => __( 'Please choose what to clear.', 'livelang' ) ) );
                return;
        }

        wp_send_json_success( array( 'deleted' => $deleted ) );
    }

    /**
     * Genuinely safe cache flush: invalidates the cached translation maps
     * (by bumping the cache-version salt) without touching any stored
     * translation data. This is the real "Flush Cache" action - it used to
     * incorrectly share a button/handler with the destructive clear-all.
     */
    public function ajax_flush_cache() {
        check_ajax_referer( 'livelang_flush_cache' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Not allowed.', 'livelang' ) ) );
        }

        $this->db->clear_translation_cache();
        wp_send_json_success();
    }

    /**
     * Streams a CSV backup of stored translations. Offered right next to
     * the Danger Zone so clearing data is never someone's only option if
     * they change their mind afterwards.
     */
    public function handle_export_csv() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Not allowed', 'livelang' ) );
        }
        check_admin_referer( 'livelang_export_csv_nonce' );

        global $wpdb;
        $table = $this->db->table;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $rows = $wpdb->get_results( "SELECT id, slug, language, original_text, translated_text, is_global, status FROM {$table} ORDER BY id ASC" );

        nocache_headers();
        header( 'Content-Type: text/csv; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename="livelang-translations-backup-' . gmdate( 'Y-m-d' ) . '.csv"' );

        $output = fopen( 'php://output', 'w' );
        fputcsv( $output, array( 'id', 'slug', 'language', 'original_text', 'translated_text', 'is_global', 'status' ) );

        foreach ( (array) $rows as $row ) {
            fputcsv( $output, array(
                $row->id,
                $row->slug,
                $row->language,
                $row->original_text,
                $row->translated_text,
                $row->is_global,
                $row->status,
            ) );
        }

        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
        fclose( $output );
        exit;
    }

    public function handle_delete() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Not allowed', 'livelang' ) );
        }
        $id = isset( $_GET['id'] ) ? intval( $_GET['id'] ) : 0;
        check_admin_referer( 'livelang_delete_' . $id );
        if ( $id ) {
            $this->db->delete( $id );
        }
        wp_safe_redirect( admin_url( 'admin.php?page=livelang' ) );
        exit;
    }

    public function handle_toggle_status() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Not allowed', 'livelang' ) );
        }
        $id = isset( $_GET['id'] ) ? intval( $_GET['id'] ) : 0;
        check_admin_referer( 'livelang_toggle_' . $id );

        if ( $id ) {
            global $wpdb;
            $table = $this->db->table;
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $row   = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $id ) );
            if ( $row ) {
                $new_status = ( $row->status === 'active' ) ? 'inactive' : 'active';
                $this->db->update( $id, array( 'status' => $new_status ) );
            }
        }

        wp_safe_redirect( admin_url( 'admin.php?page=livelang' ) );
        exit;
    }

    public function handle_bulk_action() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Not allowed', 'livelang' ) );
        }
        check_admin_referer( 'livelang_bulk_action_nonce' );

        $action     = isset( $_POST['bulk_action'] ) ? sanitize_text_field( wp_unslash( $_POST['bulk_action'] ) ) : '';
        $ids        = isset( $_POST['ids'] ) ? array_map( 'intval', (array) wp_unslash( $_POST['ids'] ) ) : array();
        $redirect_to = isset( $_POST['redirect_to'] ) ? esc_url_raw( wp_unslash( $_POST['redirect_to'] ) ) : admin_url( 'admin.php?page=livelang' );

        if ( ! empty( $ids ) ) {
            switch ( $action ) {
                case 'activate':
                    $this->db->bulk_update_status( $ids, 'active' );
                    break;
                case 'deactivate':
                    $this->db->bulk_update_status( $ids, 'inactive' );
                    break;
                case 'delete':
                    $this->db->bulk_delete( $ids );
                    break;
            }
        }

        wp_safe_redirect( $redirect_to );
        exit;
    }

    public function handle_flush_rules() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Not allowed', 'livelang' ) );
        }
        check_admin_referer( 'livelang_flush_rules_nonce' );

        flush_rewrite_rules( true );

        wp_safe_redirect( add_query_arg( 'settings-updated', 'true', admin_url( 'admin.php?page=livelang-settings' ) ) );
        exit;
    }

    public function enqueue_admin_assets() {
        $screen = get_current_screen();
        if ( $screen && strpos( $screen->id, 'livelang' ) !== false ) {
            wp_enqueue_script(
                'livelang-admin',
                LIVELANG_PLUGIN_URL . 'assets/js/livelang-admin.js',
                array( 'jquery', 'jquery-ui-sortable' ),
                LIVELANG_VERSION,
                true
            );

            wp_enqueue_style(
                'livelang-admin',
                LIVELANG_PLUGIN_URL . 'assets/css/livelang-admin.css',
                array(),
                LIVELANG_VERSION
            );
        }

        // localize script if needed
        $plan_upgrade_url = (function_exists('liv_fs')) ? liv_fs()->get_upgrade_url() : 'https://livelang.pro/pricing';
        wp_localize_script(
            'livelang-admin',
            'LiveLangAdminSettings',
            array(
                'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
                'nonce'     => wp_create_nonce( 'livelang_clear' ),
                'langNonce' => wp_create_nonce( 'livelang_languages' ),
                'isPro'     => ( class_exists( 'LiveLang_Pro' ) && liv_fs()->is__premium_only() ),
                'planUpgradeUrl'    => $plan_upgrade_url, 
            )
        );
    }

    /**
     * Get all languages
     */
    public function get_languages() {
        $languages = get_option( 'livelang_languages', array() );
        
        if ( ! is_array( $languages ) ) {
            $languages = array();
        }

        // wordpress default language if not found
        $locale = get_locale(); // e.g. en_US

        // Get language code (first part)
        $wp_default_lang_code = substr($locale, 0, 2);

        if ( empty( $languages ) ) {
            // Default languages
            $languages = array(
                array(
                    'code'      => $wp_default_lang_code,
                    'label'     => $this->available_langs[$wp_default_lang_code] ?? $wp_default_lang_code,
                    'is_default' => 1,
                    'order'     => 0,
                )
            );
            update_option( 'livelang_languages', $languages );
        }
        return $languages;
    }

    /**
     * AJAX: Get all languages
     */
    public function ajax_get_languages() {
        check_ajax_referer( 'livelang_languages' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'Not allowed' ) );
        }

        $languages = $this->get_languages();
        wp_send_json_success( $languages );
    }

    /**
     * AJAX: Add language
     */
    public function ajax_add_language() {
        check_ajax_referer( 'livelang_languages' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'Not allowed' ) );
        }

        $code = isset( $_POST['code'] ) ? sanitize_text_field( wp_unslash( $_POST['code'] ) ) : '';
        $label = isset( $_POST['label'] ) ? sanitize_text_field( wp_unslash( $_POST['label'] ) ) : '';

        if ( empty( $code ) || empty( $label ) ) {
            wp_send_json_error( array( 'message' => 'Code and label are required' ) );
        }

        // Validate code format (2-5 lowercase letters)
        if ( ! preg_match( '/^[a-z]{2,5}$/', $code ) ) {
            wp_send_json_error( array( 'message' => 'Invalid code format' ) );
        }

        $languages = $this->get_languages();

        // Check if code already exists
        foreach ( $languages as $lang ) {
            if ( $lang['code'] === $code ) {
                wp_send_json_error( array( 'message' => 'Language code already exists' ) );
            }
        }

        // Check 3-language limit for Free version
        if ( ! ( class_exists( 'LiveLang_Pro' ) && liv_fs()->is__premium_only() ) && count( $languages ) >= 3 ) {
            wp_send_json_error( array( 'message' => 'Maximum 3 languages allowed. Upgrade to Pro for unlimited languages.' ) );
        }

        $new_language = array(
            'code'       => $code,
            'label'      => $label,
            'is_default' => 0,
            'order'      => count( $languages ),
        );

        $languages[] = $new_language;
        update_option( 'livelang_languages', $languages );

        // Schedule rewrite rules flush on next admin_init
        update_option( 'livelang_flush_rewrite_rules', true );

        wp_send_json_success( array( 'language' => $new_language ) );
    }

    /**
     * AJAX: Delete language
     */
    public function ajax_delete_language() {
        check_ajax_referer( 'livelang_languages' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'Not allowed' ) );
        }

        $code = isset( $_POST['code'] ) ? sanitize_text_field( wp_unslash( $_POST['code'] ) ) : '';

        if ( empty( $code ) ) {
            wp_send_json_error( array( 'message' => 'Code is required' ) );
        }

        $languages = $this->get_languages();
        $updated = array();

        foreach ( $languages as $lang ) {
            if ( $lang['code'] !== $code ) {
                $updated[] = $lang;
            }
        }

        if ( count( $updated ) === count( $languages ) ) {
            wp_send_json_error( array( 'message' => 'Language not found' ) );
        }

        update_option( 'livelang_languages', $updated );
        
        // Schedule rewrite rules flush after deleting a language
        update_option( 'livelang_flush_rewrite_rules', true );
        
        wp_send_json_success();
    }

    /**
     * AJAX: Update language
     */
    public function ajax_update_language() {
        check_ajax_referer( 'livelang_languages' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'Not allowed' ) );
        }

        $code = isset( $_POST['code'] ) ? sanitize_text_field( wp_unslash( $_POST['code'] ) ) : '';
        $label = isset( $_POST['label'] ) ? sanitize_text_field( wp_unslash( $_POST['label'] ) ) : '';

        if ( empty( $code ) || empty( $label ) ) {
            wp_send_json_error( array( 'message' => 'Code and label are required' ) );
        }

        $languages = $this->get_languages();
        $found = false;

        foreach ( $languages as &$lang ) {
            if ( $lang['code'] === $code ) {
                $lang['label'] = $label;
                $found = true;
                break;
            }
        }

        if ( ! $found ) {
            wp_send_json_error( array( 'message' => 'Language not found' ) );
        }

        update_option( 'livelang_languages', $languages );
        update_option( 'livelang_flush_rewrite_rules', true );
        wp_send_json_success();
    }

    /**
     * AJAX: Reorder languages
     */
    public function ajax_reorder_languages() {
        check_ajax_referer( 'livelang_languages' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'Not allowed' ) );
        }

        $order = ( isset( $_POST['order'] ) && is_array( $_POST['order'] ) ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['order'] ) ) : array();

        if ( empty( $order ) ) {
            wp_send_json_error( array( 'message' => 'Order is required' ) );
        }

        $languages = $this->get_languages();
        $updated = array();

        foreach ( $order as $index => $code ) {
            $code = sanitize_text_field( $code );
            foreach ( $languages as $lang ) {
                if ( $lang['code'] === $code ) {
                    $lang['order'] = $index;
                    $updated[] = $lang;
                    break;
                }
            }
        }

        usort( $updated, function ( $a, $b ) {
            return $a['order'] - $b['order'];
        });

        update_option( 'livelang_languages', $updated );
        update_option( 'livelang_flush_rewrite_rules', true );
        wp_send_json_success();
    }

    /**
     * AJAX: Set default language
     */
    public function ajax_set_default_language() {
        check_ajax_referer( 'livelang_languages' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'Not allowed' ) );
        }

        $code = isset( $_POST['code'] ) ? sanitize_text_field( wp_unslash( $_POST['code'] ) ) : '';

        if ( empty( $code ) ) {
            wp_send_json_error( array( 'message' => 'Code is required' ) );
        }

        $languages = $this->get_languages();
        $found = false;

        foreach ( $languages as &$lang ) {
            if ( $lang['code'] === $code ) {
                $lang['is_default'] = 1;
                $found = true;
            } else {
                $lang['is_default'] = 0;
            }
        }

        if ( ! $found ) {
            wp_send_json_error( array( 'message' => 'Language not found' ) );
        }

        update_option( 'livelang_languages', $languages );
        update_option( 'livelang_flush_rewrite_rules', true );
        
        // Update cookie to reflect new default language
        if ( ! headers_sent() ) {
            setcookie( 'livelang_lang', $code, array(
                'expires'  => time() + MONTH_IN_SECONDS,
                'path'     => COOKIEPATH,
                'domain'   => COOKIE_DOMAIN,
                'secure'   => is_ssl(),
                'httponly' => false,
                'samesite' => 'Lax',
            ) );
        }
        
        // Clear specific translation cache via versioning
        $this->db->clear_translation_cache();
        
        wp_send_json_success();
    }
}
