<?php

namespace Limb_Chatbot\Includes\Admin\Pages\Setting;

use Limb_Chatbot\Includes\Admin\Admin;
use Limb_Chatbot\Includes\Integrations\Integrations;

/**
 * Class Page
 *
 * Handles the Settings submenu page for the Limb Chatbot plugin.
 * Responsible for rendering the settings page, enqueuing assets, and rendering a live chatbot preview.
 *
 * @package Limb_Chatbot\Includes\Admin\Pages\Setting
 * @since 1.0.0
 */
class Page {
    /**
     * Screen options
     *
     * @var array[]
     */
    public static $screen_options_officials = array(
        'lbaic_items_per_page'                  => array(
            'option'  => 'lbaic_admin_settings_items_per_page',
            'default' => 10,
        ),
    );

    /**
     * Menu slug for the settings page.
     *
     * @since 1.0.0
     * @var string
     */
    public static string $menu_slug = 'lbaic-dashboard&menu=knowledge';

    /**
     * Adds the "Settings" submenu page under the main "Limb" admin menu.
     * Also hooks required scripts and styles for the settings page.
     *
     * @return void
     * @since 1.0.0
     *
     */
    public function add_submenu_page() {
        $settings = add_submenu_page(
            Admin::$menu_slug,
            __( 'Knowledge', 'limb-chatbot' ),
            __( 'Knowledge', 'limb-chatbot' ),
            'manage_options',
            static::$menu_slug,
            array(
                $this,
                'render'
            ),
            8
        );
        add_action( 'admin_print_scripts-' . $settings, array( $this, 'scripts' ) );
        add_action( 'admin_print_styles-' . $settings, array( $this, 'styles' ) );
        add_action( 'load-' . $settings, array( $this, 'add_screen_options' ) );
        add_action( 'load-' . $settings, array( $this, 'remove_notices' ) );
        // Hook early to catch screen options save
        add_action( 'admin_init', array( $this, 'save_checkbox_screen_options' ), 5 );

        // Disable wp emojis cdn and scripts to not have conflicts
        remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
        add_filter( 'emoji_svg_url', '__return_false' ); // Critical to block emoji CDN
    }

    /**
     * Renders the settings page content by including the settings template.
     *
     * @return void
     * @since 1.0.0
     *
     */
    public function render() {
        include Limb_Chatbot()->get_plugin_dir_path() . 'templates/admin/lbaic-page-settings.php';
    }

    /**
     * Enqueues JavaScript assets required for the settings page.
     * Registers and localizes `lbaic-page-settings.js` and `lbaic-page-settings-chatbot.js`.
     *
     * @return void
     * @since 1.0.0
     *
     */
    public function scripts(): void {
        $limb_chatbot    = Limb_Chatbot();
        $plugin_dir_url  = $limb_chatbot->get_plugin_dir_url();
        $plugin_dir_path = $limb_chatbot->get_plugin_dir_path();
        $plugin_version  = $limb_chatbot->get_version();

        // Enqueue WordPress Media Library for file imports
        wp_enqueue_media();

        // Enqueue settings page (skeleton) js
        if ( ! wp_script_is( 'lbaic-page-settings-script', 'registered' ) ) {
            $settings_script_asset = include( $plugin_dir_path . 'dist/js/admin/lbaic-page-settings.asset.php' );
            wp_register_script( 'lbaic-page-settings-script', $plugin_dir_url . 'dist/js/admin/lbaic-page-settings.js', $settings_script_asset['dependencies'], $settings_script_asset['version'], true );
            wp_set_script_translations( 'lbaic-page-settings-script', 'limb-chatbot', $plugin_dir_path . 'languages' );
        }
        if ( ! wp_script_is( 'lbaic-page-settings-script', 'enqueued' ) ) {
            $post_types = get_post_types(
                    [ 'public' => true ],
                    'objects'
            );
            // Exclude unwanted ones
            $exclude = [ 'attachment', 'revision', 'nav_menu_item' ];
            foreach ( $exclude as $unset ) {
                unset( $post_types[ $unset ] );
            }
            // Format as 'post_type_name' => 'Label' (plural)
            $formatted = [];
            foreach ( $post_types as $name => $obj ) {
                $formatted[] = [
                        'name' => $obj->labels->name,
                        'slug' => $name
                ];
            }
            wp_enqueue_script( 'lbaic-page-settings-script' );
            // Get screen options data to localize
            $screen_options = array();
            $user_id        = get_current_user_id();
            foreach ( self::$screen_options_officials as $key => $args ) {
                $meta_value = get_user_meta( $user_id, $args['option'], true );
                // Handle checkbox (boolean) types
                if ( isset( $args['type'] ) && $args['type'] === 'checkbox' ) {
                    $screen_options[ $key ] = ( $meta_value === '1' || $meta_value === true || $meta_value === 'true' ) ? true : ( $meta_value !== '' ? (bool) $meta_value : $args['default'] );
                } else {
                    // Handle integer types (like per_page)
                    $screen_options[ $key ] = (int) ( $meta_value ?: $args['default'] );
                }
            }
            // Localize the script
            wp_localize_script( 'lbaic-page-settings-script', 'LimbChatbot', array(
	            'rest'           => array(
		            'url'   => get_rest_url( null, 'limb/chatbot/v1/' ),
		            'nonce' => wp_create_nonce( 'wp_rest' )
	            ),
	            'screen_options' => $screen_options,
	            'config'         => array(
		            'debug' => true,
	            ),
	            'wp_objects'     => array( 'post_types' => $formatted ),
	            'integrations'   => array_keys( Integrations::instance()->get_integrations() ),
	            'wp_cron'        => array(
		            'enabled' => ! defined( 'DISABLE_WP_CRON' ) || ! DISABLE_WP_CRON,
	            ),
	            'version'        => $plugin_version,
            ) );
        }
        // Enqueue chatbot settings page js
        $chatbot_settings_script_asset = include( $plugin_dir_path . 'dist/js/admin/lbaic-page-settings-chatbot.asset.php' );
        wp_register_script(
            'lbaic-page-settings-chatbot-script',
            $plugin_dir_url . 'dist/js/admin/lbaic-page-settings-chatbot.js',
            array_merge(
                $chatbot_settings_script_asset['dependencies'] ?: [],
                [ 'lbaic-page-settings-script' ]
            ),
            $chatbot_settings_script_asset['version'],
            true
        );
        wp_set_script_translations( 'lbaic-page-settings-chatbot-script', 'limb-chatbot', $plugin_dir_path . 'languages' );
        wp_enqueue_script( 'lbaic-page-settings-chatbot-script' );
        add_action( 'admin_footer', array( $this, 'add_screen_options_script' ) );
        ?>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
        <?php
    }

    /**
     * Enqueues CSS assets required for the settings page.
     * Loads both JS-generated and CSS-based styles for the settings UI and chatbot preview.
     *
     * @return void
     * @since 1.0.0
     *
     */
    public function styles(): void {
        $limb_chatbot    = Limb_Chatbot();
        $plugin_dir_url  = $limb_chatbot->get_plugin_dir_url();
        $plugin_dir_path = $limb_chatbot->get_plugin_dir_path();
        $version         = $limb_chatbot->get_version();
        if ( ! wp_style_is( 'lbaic-page-settings-style', 'registered' ) ) {
            wp_register_style( 'lbaic-page-settings-style', $plugin_dir_url . 'dist/css/admin/page/lbaic-page-settings.css', array(), $version );
        }
        wp_enqueue_style( 'lbaic-page-settings-style' );
        // Style
        wp_register_style( 'lbaic-chatbot-preview', $plugin_dir_url . 'dist/css/chatbot/lbaic-chatbot.css', array(), $version );
        wp_enqueue_style( 'lbaic-chatbot-preview' );
    }

    /**
     * Screen options fields with their labels
     *
     * @return array
     * @since 1.0.0
     *
     */
    private function get_screen_options_labels(): array {
        return array(
            'lbaic_items_per_page'                  => __( "Items per page", 'limb-chatbot' ),
        );
    }

    /**
     * Set screen options support
     *
     * @return void
     * @since 1.0.0
     *
     */
    public function add_screen_options(): void {
        $labels = $this->get_screen_options_labels();
        foreach ( self::$screen_options_officials as $key => $args ) {
            // Register all screen options, including checkboxes
            // WordPress will handle saving them through the set-screen-option filter
            add_screen_option( $key, array_merge(
                    array(
                            'label' => $labels[ $key ],
                    ),
                    $args,
            ) );
        }

        // Add custom screen settings for all custom screen options (items per page and checkbox)
        add_filter( 'screen_settings', array( $this, 'render_custom_screen_options' ), 10, 2 );

        // Show submit button for screen options
        add_filter( 'screen_options_show_submit', '__return_true' );

        $screen = get_current_screen();

        $screen->add_help_tab( [
                'id'      => 'lbaic_chatbot_welcome_tab',
                'title'   => __( 'Overview', 'limb-chatbot' ),
                'content' => $this->get_help_tab_content( 'lbaic_chatbot_welcome_tab' ),
        ] );
        $screen->add_help_tab( [
                'id'      => 'lbaic_chatbot_support_tab',
                'title'   => __( 'Help & Support', 'limb-chatbot' ),
                'content' => $this->get_help_tab_support_content( 'lbaic_chatbot_support_tab' ),
        ] );
    }

    private function get_help_tab_content( $tab ) {
        ob_start();
        switch ( $tab ) {
            case 'lbaic_chatbot_welcome_tab':
                ?>
                <div class="lbaic-settings-welcome-message-body">
                    <p class="lbaic-settings-welcome-message-desc"><?php
                        // translators: Text about being fanatical about support
                        esc_html_e( "We built this plugin with care to help you set up AI Agents easily. Everything you see right now is 100% free.", 'limb-chatbot' );
                        ?></p>
                    <p class="lbaic-settings-welcome-message-desc"><?php
                        // translators: Text about being fanatical about support
                        esc_html_e( "The FREE version is built to handle most of your needs right out of the box. We do have some advanced premium features available, but they’re completely optional. The only possible ongoing costs you might see come from AI providers (like OpenAI or Gemini) once you connect your own API key—and even then, those costs are usually very small and depend on how much your chatbot is used.", 'limb-chatbot' );
                        ?></p>

                    <p class="lbaic-settings-welcome-message-desc"><?php
                        // translators: Text about being fanatical about support
                        esc_html_e( "🧭 Our Vision We believe websites should feel like a conversation — not a puzzle. Whether someone wants to search, shop, or submit something, it should all happen naturally — by just asking the chatbot. We’re building a future where your AI agent becomes your visitor’s personal assistant inside your website.", 'limb-chatbot' );
                        ?></p>

                </div>
                <div class="lbaic-settings-welcome-message-header">
                    <div class="lbaic-settings-welcome-message-title">
                        <span class="lbaic-settings-welcome-message-title-in"><b>🚀 <?php esc_html_e( "Coming Soon", 'limb-chatbot' ); ?></b></span>
                    </div>
                </div>
                <div class="lbaic-settings-welcome-message-body">
                    <ul class="lbaic-settings-welcome-message-list">
                        <li class="lbaic-settings-welcome-message-list-item">
                            <span class="lbaic-settings-welcome-message-desc"><?php
                                // translators: %1$s and %2$s wrap "WooCommerce Integration" in bold tags.
                                echo wp_kses( sprintf( __( "🛒 %1\$sWooCommerce Integration%2\$s - Product recommendations, add-to-cart, order status tracking, and inventory questions.", 'limb-chatbot' ), '<b>', '</b>' ), array( 'b' => array() ) );
                                ?></span>
                        </li>
                        <li class="lbaic-settings-welcome-message-list-item">
                            <span class="lbaic-settings-welcome-message-desc"><?php
                                // translators: %1$s and %2$s wrap "Streaming Responses" in bold tags.
                                echo wp_kses( sprintf( __( "⚡ %1\$sStreaming Responses%2\$s - Real-time word-by-word AI replies for faster conversations.", 'limb-chatbot' ), '<b>', '</b>' ), array( 'b' => array() ) );
                                ?></span>
                        </li>
                        <li class="lbaic-settings-welcome-message-list-item">
                            <span class="lbaic-settings-welcome-message-desc"><?php
                                // translators: %1$s and %2$s wrap "OpenAI Fine-Tuning" in bold tags.
                                echo wp_kses( sprintf( __( "🎓 %1\$sOpenAI Fine-Tuning%2\$s - Train custom models on your Q&A dataset for domain-specific conversations.", 'limb-chatbot' ), '<b>', '</b>' ), array( 'b' => array() ) );
                                ?></span>
                        </li>
                    </ul>
                </div>
                <div class="lbaic-settings-welcome-message-body">
                    <span class="lbaic-settings-welcome-message-welcome-text"><?php esc_html_e( "Thanks for being part of this journey.", 'limb-chatbot' ); ?></span>
                    <svg class='lbaic-settings-welcome-message-i'
                         xmlns='http://www.w3.org/2000/svg'
                         fill='none'
                         viewBox='0 0 24 50'>
                        <path
                                d="M8.508 13.026c-.21-.72-.455-1.621-.562-2.36l-.005-.031a18 18 0 0 1-.126-1.13A22 22 0 0 1 7.74 7.78c-.04-2.49.492-4.28.724-4.758.328-.763.83-1.47 1.72-1.842a4 4 0 0 1 .995-.283c.132-.018.256-.025.381-.022.097.003.176.042.172.075-.002.034-.078.05-.168.047a2 2 0 0 0-.354.018c-.33.043-.66.147-.98.278-.842.353-1.313 1.008-1.632 1.728-.237.467-.784 2.272-.736 4.811a22 22 0 0 0 .095 1.872v.003c.035.374.07.668.112.955l.003.018c.109.742.352 1.623.555 2.315.038.133.044.246.012.255-.032.008-.09-.09-.13-.225m8.854 1.174c-.49.554-1.223 1.231-1.898 1.778a22 22 0 0 1-1.644 1.219c-.306.203-.634.435-1.035.709l-.284.193a25 25 0 0 1-1.42.887 25.5 25.5 0 0 0-3.256 2.24c-.456.37-.776.65-1.073.897-.535.447-.975.844-1.472 1.306-.72.663-1.578 1.736-2.04 2.495a22 22 0 0 0-1.32 2.457c-.415.91-.72 1.719-.952 2.44q-.102.317-.184.606c-.138.486-.243.93-.321 1.351-.457 2.61-.33 4.159-.312 5.112.032.74.057 1.148.074 1.448q.008.134.017.246c.056.664.152 1.275.297 1.997q.05.243.106.502a12.4 12.4 0 0 0 .51 1.723l.002.007.018.049.014.037.005.012.003.005c.01.023.017.044.02.048l.005.016.02.054.07.203.107.277.008.02c.04.104.09.224.149.373.054.135.08.266.056.296-.025.03-.089-.053-.144-.188l-.151-.375a13 13 0 0 1-.164-.43l-.082-.222-.02-.054a13.168 13.168 0 0 1-.559-1.89q-.054-.249-.103-.489a18 18 0 0 1-.303-2.097l-.018-.293c-.014-.294-.034-.652-.061-1.336-.014-.915-.14-2.433.312-5.048.082-.444.195-.922.338-1.419q.082-.285.178-.586c.231-.715.528-1.505.93-2.39a22 22 0 0 1 1.21-2.302l.036-.058.044-.072c.493-.82 1.409-1.97 2.21-2.7.478-.44.91-.827 1.44-1.267.261-.216.534-.456.98-.821a25 25 0 0 1 3.313-2.284q.168-.098.343-.203a24 24 0 0 0 1.363-.878c.4-.274.766-.533 1.117-.768.288-.192.915-.633 1.575-1.173.663-.538 1.336-1.164 1.767-1.648l.136-.152c.39-.441.773-.902 1.045-1.296 1.163-1.803 3.564-4.916 3.971-7.273l.017-.09c.436-2.127-.745-3.117-1.58-3.415a7 7 0 0 0-.76-.266 4.5 4.5 0 0 0-.76-.151 3.8 3.8 0 0 0-.787-.007c-1.062.106-1.698.794-2.157 1.504a6 6 0 0 0-.235.4v.002c-.32.594-.545 1.182-.75 1.754-.368 1.05-.579 1.806-.792 2.41-.056.161-.114.321-.17.465l-1.635-.604.018-.06c.094-.315.164-.595.229-.886.12-.548.19-1.062.226-1.566l.008-.134a9.4 9.4 0 0 0-.041-1.625c-.015-.124-.005-.232.028-.24s.076.09.091.216a9.5 9.5 0 0 1 .037 1.754 11 11 0 0 1-.227 1.601 13 13 0 0 1-.254.978l1.407.52c.05-.128.104-.274.155-.42.217-.61.429-1.375.803-2.44.203-.568.426-1.155.749-1.76q.111-.208.24-.414c.465-.726 1.134-1.463 2.25-1.576a4 4 0 0 1 .825.007 4.6 4.6 0 0 1 .907.194c.158.05.356.115.64.232.864.295 2.113 1.387 1.653 3.556l-.004.025c-.394 1.81-1.037 2.776-1.4 3.509a14 14 0 0 1-.932 1.51c-.177.251-.313.437-.452.634a86 86 0 0 0-1.076 1.545c-.303.447-.725.957-1.107 1.392l-.002.002zM2.458 46.826c.062.14.087.26.056.272s-.106-.086-.169-.226a31 31 0 0 1-.412-.968c-.055-.135-.074-.256-.042-.267s.1.09.155.225c.13.318.274.656.412.964m15.753-32.63c-.092.106-.207.192-.252.192s-.006-.086.087-.192q.076-.085.236-.273c.745-.905 3.03-3.529 4.261-6.852.102-.288.176-.53.242-.78.187-1.006.573-2.058-.4-3.7-.346-.482-.85-.837-1.422-1.073-1.722-.805-3.875-.687-4.944.966-1.12 1.538-1.518 3.512-2.253 5.367l-.429-.158c.537-1.679.785-3.52.421-5.237-.188-.838-.607-1.678-1.356-2.018-.745-.346-1.647-.16-2.448.176A3.5 3.5 0 0 0 8.54 1.703c-1.46 1.98-1.505 4.706-1.313 7.182.104 2.114 1.155 5.869 1.646 6.64.062.127.09.236.06.25s-.107-.071-.17-.2c-.495-.78-1.548-4.539-1.654-6.657C6.916 6.43 6.944 3.7 8.424 1.655c.387-.503.895-.911 1.483-1.156.815-.341 1.746-.548 2.55-.183.809.364 1.246 1.249 1.446 2.106.383 1.757.146 3.616-.385 5.33l.072.027c.711-1.832 1.088-3.827 2.24-5.437 1.095-1.755 3.488-1.906 5.233-1.07.609.249 1.165.635 1.544 1.17 1.05 1.815.479 2.821.307 3.836-.067.257-.14.5-.243.795-1.215 3.314-3.46 5.912-4.214 6.836q-.166.197-.246.287m-5.162 4.31c-.47.329-1.02.691-1.621 1.054a31 31 0 0 0-3.243 2.238 24 24 0 0 0-1.94 1.717 31 31 0 0 0-1.73 1.854 14 14 0 0 0-1.474 2.057 16.4 16.4 0 0 0-1.67 3.997v.004c-.424 1.54-.528 3.161-.562 4.318-.085 4.071.734 6.515 1.025 7.75.578 2.161 1.755 4.417 2.842 6.434.093.21-.194-.069-.418-.502l-.022-.042-.233-.44-.328-.608c-.282-.43-1.721-3.67-1.985-4.906C1.422 42.256.458 39.888.54 35.725c.037-1.155.28-2.744.704-4.299l.004-.012a16.6 16.6 0 0 1 1.687-4.049 14.3 14.3 0 0 1 1.536-2.134l.014-.016c.457-.527.917-1.03 1.673-1.785a24 24 0 0 1 1.975-1.746 31 31 0 0 1 3.231-2.228 29 29 0 0 0 1.596-1.037c.118-.082.233-.13.258-.107s-.052.112-.17.194m.4.643q-.783.575-1.607 1.097c-3.208 2.04-6.067 4.489-8.028 7.586a16.7 16.7 0 0 0-1.68 3.879 17 17 0 0 0-.634 4.078c-.079 3.926.777 6.304 1.06 7.501.307 1.114.438 1.41.615 1.859l.015.036v.002l.017.033.013.028.008.02.014.032.211.523c.083.202.136.338.198.49l.019.047c.057.14.119.29.208.495.053.121.074.234.036.231-.038-.002-.116-.11-.17-.233-.095-.219-.161-.38-.219-.523l-.018-.045c-.056-.141-.106-.267-.179-.446l-.257-.624c-.184-.466-.336-.813-.654-1.984-.261-1.143-1.113-3.467-1.038-7.444a17.2 17.2 0 0 1 .654-4.162 16.8 16.8 0 0 1 1.676-3.854c1.918-3.226 4.741-5.738 8.031-7.693a39 39 0 0 0 1.62-1.015 37 37 0 0 0 1.893-1.411c1.665-1.334 2.84-2.483 3.846-3.682.215-.261.819-.932 1.596-1.974q.345-.459.723-1.024c.613-.925 1.3-2.064 1.833-3.486.11-.293.2-.575.273-.833.198-1.116.836-2.17-.326-4.437-.398-.63-1.098-1.194-1.9-1.518-1.173-.493-2.751-.873-4.163-.256-1.403.617-2.101 1.84-2.526 2.65-.549 1.11-.74 1.753-.907 2.196a71 71 0 0 0-.365 1.054c-.143.424-.278.812-.42 1.159l1.294.478c.435-1.413.692-2.71.557-4.618-.014-.153-.005-.295.027-.31s.075.1.09.257c.146 1.939-.113 3.26-.559 4.708l-1.522-.562c.143-.344.277-.735.422-1.162a70 70 0 0 1 .373-1.074c.165-.438.354-1.075.907-2.192.431-.816 1.14-2.064 2.588-2.699 1.46-.632 3.067-.238 4.25.258.817.33 1.54.91 1.95 1.558 1.197 2.319.552 3.366.36 4.494a11 11 0 0 1-.274.85c-.533 1.438-1.226 2.592-1.84 3.523-.252.377-.496.72-.723 1.027-.796 1.068-1.369 1.701-1.55 1.926-1.04 1.25-2.273 2.453-3.96 3.802-.561.446-1.177.908-1.859 1.384M7.89 1.027c.106-.128.228-.216.26-.2.031.015-.036.123-.14.247-.549.662-.784 1.225-.956 1.648-.299.798-.372 1.194-.49 1.785-.28 1.525-.262 3.003-.155 4.314.185 2.181.648 3.907.922 4.813.043.14.054.262.022.272-.033.008-.096-.1-.139-.241a23.7 23.7 0 0 1-.924-4.81c-.108-1.32-.13-2.812.153-4.364.116-.58.184-.955.474-1.75.172-.433.403-1.013.973-1.714"
                        ></path>
                    </svg>
                </div>
                <?php
                break;
            default:
                break;
        }

        return ob_get_clean();
    }

    private function get_help_tab_support_content( $tab ) {
        ob_start();
        switch ( $tab ) {
            case 'lbaic_chatbot_support_tab':
                // Support links
                $documentation_url = 'https://wpaichatbot.com/documentation/getting-started/installation/';
                $discussions_url = 'https://wordpress.org/support/plugin/limb-chatbot/';
                $contact_us_url = 'https://wpaichatbot.com/'; // TODO: Add your Contact Us URL
                ?>
                <div class="lbaic-settings-welcome-message-header">
                    <div class="lbaic-settings-welcome-message-title">
                        <span class="lbaic-settings-welcome-message-title-in"><b><?php esc_html_e( "Help & Support", 'limb-chatbot' ); ?></b></span>
                    </div>
                </div>
                <div class="lbaic-settings-welcome-message-body">
                    <p class="lbaic-settings-welcome-message-desc"><?php
                        // translators: Text about being fanatical about support
                        esc_html_e( "We’re passionate about great support and want to ensure you get the most out of your website with Limb Chatbot. If you ever need assistance, there are multiple places where you can find help:", 'limb-chatbot' );
                        ?></p>
                </div>
                <div class="lbaic-settings-welcome-message-body">
                    <ul class="lbaic-settings-welcome-message-list">
                        <li class="lbaic-settings-welcome-message-list-item">
                            <span class="lbaic-settings-welcome-message-desc"><?php
                                // translators: %1$s is the Documentation link, %2$s is the closing tag.
                                echo wp_kses( sprintf( __( "%1\$sDocumentation%2\$s. Our extensive documentation contains references and guides for most situations you may encounter.", 'limb-chatbot' ), '<a href="' . esc_url( $documentation_url ) . '" target="_blank"><b>', '</b></a>' ), array(
                                        'a' => array(
                                                'href'   => array(),
                                                'target' => array()
                                        ),
                                        'b' => array()
                                ) );
                                ?></span>
                        </li>
                        <li class="lbaic-settings-welcome-message-list-item">
                            <span class="lbaic-settings-welcome-message-desc"><?php
                                // translators: %1$s is the Discussions link, %2$s is the closing tag.
                                echo wp_kses( sprintf( __( "%1\$sDiscussions%2\$s. We have an active and friendly community on our WordPress Support Forums who may be able to help you figure out the 'how-tos' of the Limb Chatbot world.", 'limb-chatbot' ), '<a href="' . esc_url( $discussions_url ) . '" target="_blank"><b>', '</b></a>' ), array(
                                        'a' => array(
                                                'href'   => array(),
                                                'target' => array()
                                        ),
                                        'b' => array()
                                ) );
                                ?></span>
                        </li>

                        <li class="lbaic-settings-welcome-message-list-item">
                            <span class="lbaic-settings-welcome-message-desc"><?php
                                // translators: %1$s is the Discussions link, %2$s is the closing tag.
                                echo wp_kses( sprintf( __( "%1\$ssupport@wpaichatbot.com%2\$s", 'limb-chatbot' ), '<a href="mailto:support@wpaichatbot.com' . esc_url( $discussions_url ) . '" target="_blank"><b>', '</b></a>' ), array(
                                        'a' => array(
                                                'href'   => array(),
                                                'target' => array()
                                        ),
                                        'b' => array()
                                ) );
                                ?></span>
                        </li>
                        <li class="lbaic-settings-welcome-message-list-item">
                            <span class="lbaic-settings-welcome-message-desc"><?php
                                // translators: %1$s is the Discussions link, %2$s is the closing tag.
                                echo wp_kses( sprintf( __( "%1\$sContact Us%2\$s", 'limb-chatbot' ), '<a href="' . esc_url( $contact_us_url ) . '" target="_blank"><b>', '</b></a>' ), array(
                                        'a' => array(
                                                'href'   => array(),
                                                'target' => array()
                                        ),
                                        'b' => array()
                                ) );
                                ?></span>
                        </li>
                    </ul>
                </div>
                <?php
                break;
            default:
                break;
        }

        return ob_get_clean();
    }

    /**
     * Remove the header notices
     *
     * @return void
     * @since 1.0.0
     *
     */
    public function remove_notices(): void {
        remove_all_actions( 'admin_notices' );
        remove_all_actions( 'all_admin_notices' );
    }

    /**
     * Render custom screen options (checkboxes)
     *
     * @param string $screen_settings Current screen settings HTML
     * @param \WP_Screen $screen Current screen object
     *
     * @return string
     * @since 1.0.0
     *
     */
    public function render_custom_screen_options( $screen_settings, $screen ) {
        // Only render on our settings page
        if ( strpos( $screen->id, 'lbaic-dashboard' ) === false ) {
            return $screen_settings;
        }

        $labels  = $this->get_screen_options_labels();
        $user_id = get_current_user_id();
        $output  = '';

        foreach ( self::$screen_options_officials as $key => $args ) {
            $option_name = $args['option'];

            // Render items per page option
            if ( $key === 'lbaic_items_per_page' ) {
                $current_value = get_user_meta( $user_id, $option_name, true );
                $per_page      = (int) ( $current_value ?: $args['default'] );

                $output .= '<fieldset class="screen-options">';
                $output .= '<legend>' . esc_html__( 'Pagination', 'limb-chatbot' ) . '</legend>';
                $output .= '<label for="' . esc_attr( $key ) . '">' . esc_html( $labels[ $key ] ) . '</label>&nbsp';
                $output .= '<input type="number" step="1" min="1" max="999" class="screen-per-page" name="' . esc_attr( $key ) . '" id="' . esc_attr( $key ) . '" value="' . esc_attr( $per_page ) . '" />';
                $output .= '</fieldset>';
            } // Render checkbox types
            elseif ( isset( $args['type'] ) && $args['type'] === 'checkbox' ) {
                $current_value = get_user_meta( $user_id, $option_name, true );
                // Convert to boolean, default to false
                $checked = ( $current_value === '1' || $current_value === true || $current_value === 'true' ) ? 'checked="checked"' : '';

                $output .= '<fieldset class="screen-options">';
                $output .= '<legend>' . esc_html__( 'Advanced', 'limb-chatbot' ) . '</legend>';
                $output .= '<label for="' . esc_attr( $option_name ) . '">';
                // Use the option name as the checkbox name so it can be processed
                $output .= '<input type="checkbox" name="lbaic_checkbox_' . esc_attr( $key ) . '" id="' . esc_attr( $option_name ) . '" value="1" ' . $checked . ' data-option-name="' . esc_attr( $option_name ) . '" />';
                $output .= esc_html( $labels[ $key ] );
                $output .= '</label>';
                $output .= '</fieldset>';
            }
        }

        return $screen_settings . $output;
    }

    /**
     * Save screen options
     *
     * @param mixed $status Current status
     * @param string $option Option name
     * @param mixed $value Option value
     *
     * @return int|bool|mixed
     * @since 1.0.0
     *
     */
    public function set_screen_options( $status, $option, $value ) {
        foreach ( self::$screen_options_officials as $key => $args ) {
            if ( isset( $args['option'] ) && $args['option'] === $option ) {
                $user_id = get_current_user_id();

                // Handle checkbox (boolean) types
                if ( isset( $args['type'] ) && $args['type'] === 'checkbox' ) {
                    // Save as '1' for true, '' for false
                    $bool_value = ( $value === '1' || $value === 1 || $value === true || $value === 'true' ) ? '1' : '';
                    update_user_meta( $user_id, $option, $bool_value );

                    return $bool_value;
                }

                // Handle integer types (like items_per_page)
                $int_value = (int) $value;
                update_user_meta( $user_id, $option, $int_value );

                return $int_value;
            }
        }

        // When any screen option is saved, also process all our custom screen options
        // This ensures all options are saved even if they don't go through the standard mechanism
        $this->process_all_screen_options_on_save();

        return $status;
    }

    /**
     * Process all custom screen options when any screen option is saved
     * This is called from set_screen_options filter to ensure all options are saved
     *
     * @return void
     * @since 1.0.0
     *
     */
    private function process_all_screen_options_on_save() {
        // Only process if this is a screen options save request
        if ( ! isset( $_POST['screenoptionnonce'] ) ) {
            return;
        }

        $user_id = get_current_user_id();
        if ( ! $user_id ) {
            return;
        }

        // Handle each screen option
        foreach ( self::$screen_options_officials as $key => $args ) {
            $option_name = $args['option'];
            $value       = null;

            // Check wp_screen_options format first (if JavaScript converted it)
            if ( isset( $_POST['wp_screen_options'] ) &&
                 is_array( $_POST['wp_screen_options'] ) &&
                 isset( $_POST['wp_screen_options']['option'] ) &&
                 $_POST['wp_screen_options']['option'] === $option_name &&
                 isset( $_POST['wp_screen_options']['value'] ) ) {
                $value = $_POST['wp_screen_options']['value'];
            } else {
                // Check direct POST fields - WordPress uses the key as input name
                $post_keys = array(
                        $key, // WordPress uses the key as the input name
                        $option_name, // Direct option name (fallback)
                        'lbaic_checkbox_' . $key, // With prefix for checkboxes (fallback)
                );

                foreach ( $post_keys as $post_key ) {
                    if ( isset( $_POST[ $post_key ] ) ) {
                        $value = $_POST[ $post_key ];
                        break;
                    }
                }
            }

            // Only save if we found a value
            if ( $value !== null ) {
                // Handle checkbox (boolean) types
                if ( isset( $args['type'] ) && $args['type'] === 'checkbox' ) {
                    $value = ( $value === '1' || $value === 1 || $value === true || $value === 'true' ) ? '1' : '';
                } else {
                    // Handle integer types (like items_per_page)
                    $value = (int) $value;
                    // Ensure minimum value of 1
                    if ( $value < 1 ) {
                        $value = $args['default'];
                    }
                }

                update_user_meta( $user_id, $option_name, $value );
            }
        }
    }

    /**
     * Handle saving of all custom screen options
     * This is needed because unchecked checkboxes don't appear in POST data
     * and to ensure all our custom options are saved
     *
     * @return void
     * @since 1.0.0
     *
     */
    public function save_checkbox_screen_options() {
        // Check if this is a screen options save request
        // WordPress screen options form uses 'screenoptionnonce' field
        if ( ! isset( $_POST['screenoptionnonce'] ) ) {
            return;
        }

        // Verify nonce
        if ( ! wp_verify_nonce( $_POST['screenoptionnonce'], 'screen-options-nonce' ) ) {
            return;
        }

        // Process all custom screen options immediately
        $this->process_all_screen_options_on_save();
    }

    /**
     * Adds JavaScript to handle saving checkbox screen options
     *
     * @return void
     * @since 1.0.0
     *
     */
    public function add_screen_options_script() {
        $screen = get_current_screen();
        if ( ! $screen || strpos( $screen->id, 'lbaic-dashboard' ) === false ) {
            return;
        }
        ?>
        <script type="text/javascript">
            (function ($) {
                $(document).ready(function () {
                    // Handle screen options form submission
                    // WordPress processes screen options via wp_screen_options[option] and wp_screen_options[value]
                    // We need to convert our checkbox to this format
                    var form = $('#adv-settings');
                    if (form.length) {
                        // Function to save all custom screen options via WordPress screen options mechanism
                        function saveAllScreenOptions() {
                            <?php foreach ( self::$screen_options_officials as $key => $args ) : ?>
                            <?php $option_name = $args['option']; ?>
                            <?php if ( isset( $args['type'] ) && $args['type'] === 'checkbox' ) : ?>
                            // Handle checkbox options
                            var checkbox_<?php echo esc_js( $key ); ?> = $('input[data-option-name="<?php echo esc_js( $option_name ); ?>"]');
                            if (checkbox_<?php echo esc_js( $key ); ?>.length) {
                                var isChecked = checkbox_<?php echo esc_js( $key ); ?>[0].checked;
                                var checkboxValue = isChecked ? '1' : '0';

                                // Remove any existing wp_screen_options for this option
                                form.find('input[name="wp_screen_options[option]"][value="<?php echo esc_js( $option_name ); ?>"]').next('input[name="wp_screen_options[value]"]').remove();
                                form.find('input[name="wp_screen_options[option]"][value="<?php echo esc_js( $option_name ); ?>"]').remove();

                                // Add in WordPress screen options format
                                form.append('<input type="hidden" name="wp_screen_options[option]" value="<?php echo esc_js( $option_name ); ?>" />');
                                form.append('<input type="hidden" name="wp_screen_options[value]" value="' + checkboxValue + '" />');
                            }
                            <?php else : ?>
                            // Handle other options (like items_per_page)
                            // WordPress uses the key as the input name, and the option name for saving
                            var optionInput_<?php echo esc_js( $key ); ?> = form.find('input[name="<?php echo esc_js( $key ); ?>"]');
                            if (optionInput_<?php echo esc_js( $key ); ?>.length) {
                                var optionValue = optionInput_<?php echo esc_js( $key ); ?>.val();

                                // Remove any existing wp_screen_options for this option
                                form.find('input[name="wp_screen_options[option]"][value="<?php echo esc_js( $option_name ); ?>"]').next('input[name="wp_screen_options[value]"]').remove();
                                form.find('input[name="wp_screen_options[option]"][value="<?php echo esc_js( $option_name ); ?>"]').remove();

                                // Add in WordPress screen options format (using option name, not key)
                                form.append('<input type="hidden" name="wp_screen_options[option]" value="<?php echo esc_js( $option_name ); ?>" />');
                                form.append('<input type="hidden" name="wp_screen_options[value]" value="' + optionValue + '" />');
                            }
                            <?php endif; ?>
                            <?php endforeach; ?>
                        }

                        // Save all custom screen options BEFORE form is submitted
                        form.on('submit', function (e) {
                            saveAllScreenOptions();
                        });

                        // Handle when Apply button is clicked - this is the main way WordPress saves screen options
                        $(document).on('click', '#screen-options-apply, #screen-options-save', function (e) {
                            // Save all custom screen options immediately
                            saveAllScreenOptions();
                        });

                    }
                });
            })(jQuery);
        </script>
        <?php
    }
}