<?php
/**
 * Admin UI for site chatbot (OpenAI BYOK + index).
 *
 * @package Maca_Menu_List
 */

if (!defined('ABSPATH')) {
    exit;
}

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/site-chat-index.php';

/**
 * Site chatbot admin screen.
 */
class Maca_MenuList_Admin_Site_Chat {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'), 16);
        add_action('admin_init', array($this, 'handle_actions'));
        add_action('wp_ajax_maca_site_chat_build_index', array($this, 'ajax_build_index'));
        add_action('wp_ajax_maca_site_chat_admin_ask', array($this, 'ajax_admin_ask'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
    }

    /**
     * Register submenu page.
     *
     * @return void
     */
    public function add_admin_menu() {
        if (!maca_menulist_site_chat_feature_available()) {
            return;
        }

        add_submenu_page(
            'maca-restu',
            __('Chatt', 'maca-restu-pro'),
            __('Chatt', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-site-chat',
            array($this, 'render_page')
        );
    }

    /**
     * Handle settings save and manual index build.
     *
     * @return void
     */
    public function handle_actions() {
        if (!is_admin() || !isset($_POST['maca_site_chat_action'])) {
            return;
        }

        if (!maca_menulist_user_can_manage_plugin() || !maca_menulist_site_chat_feature_available()) {
            return;
        }

        check_admin_referer('maca_site_chat', 'maca_site_chat_nonce');

        $action = sanitize_key(wp_unslash($_POST['maca_site_chat_action']));

        if ($action === 'save_settings') {
            $this->save_settings();
            return;
        }

        if ($action === 'build_index') {
            $result = maca_menulist_site_chat_build_index();
            $redirect = add_query_arg(
                array(
                    'page' => 'maca-restu-site-chat',
                    'maca_site_chat_notice' => is_wp_error($result) ? 'error' : 'success',
                    'maca_site_chat_message' => rawurlencode(is_wp_error($result) ? $result->get_error_message() : $result['message']),
                ),
                admin_url('admin.php')
            );
            wp_safe_redirect($redirect);
            exit;
        }
    }

    /**
     * Save chatbot settings.
     *
     * @return void
     */
    private function save_settings() {
        $enabled = isset($_POST['maca_site_chat_enabled']) ? '1' : '0';
        $floating = isset($_POST['maca_site_chat_floating']) ? '1' : '0';
        $embedding_model = isset($_POST['maca_site_chat_embedding_model'])
            ? sanitize_text_field(wp_unslash($_POST['maca_site_chat_embedding_model']))
            : 'text-embedding-3-small';
        $chat_model = isset($_POST['maca_site_chat_chat_model'])
            ? sanitize_text_field(wp_unslash($_POST['maca_site_chat_chat_model']))
            : 'gpt-4o-mini';
        $rate_limit = isset($_POST['maca_site_chat_rate_limit']) ? absint($_POST['maca_site_chat_rate_limit']) : 30;
        $page_ids = isset($_POST['maca_site_chat_wp_page_ids']) && is_array($_POST['maca_site_chat_wp_page_ids'])
            ? array_map('absint', wp_unslash($_POST['maca_site_chat_wp_page_ids']))
            : array();
        $chat_name = isset($_POST['maca_site_chat_name']) ? sanitize_text_field(wp_unslash($_POST['maca_site_chat_name'])) : '';
        $chat_name_en = isset($_POST['maca_site_chat_name_en']) ? sanitize_text_field(wp_unslash($_POST['maca_site_chat_name_en'])) : '';
        $avatar_url = isset($_POST['maca_site_chat_avatar_url'])
            ? maca_menulist_normalize_url(esc_url_raw(wp_unslash($_POST['maca_site_chat_avatar_url'])))
            : '';
        $avatar_preset = isset($_POST['maca_site_chat_avatar_preset'])
            ? sanitize_key(wp_unslash($_POST['maca_site_chat_avatar_preset']))
            : '';
        $valid_presets = array_merge(array_keys(maca_menulist_site_chat_get_bundled_avatars()), array('custom'));

        if (!in_array($avatar_preset, $valid_presets, true)) {
            $avatar_preset = '';
        }

        update_option('maca_menulist_site_chat_enabled', $enabled, false);
        update_option('maca_menulist_site_chat_floating', $floating, false);
        update_option('maca_menulist_site_chat_name', $chat_name, false);
        update_option('maca_menulist_site_chat_name_en', $chat_name_en, false);
        update_option('maca_menulist_site_chat_avatar_url', $avatar_url, false);
        update_option('maca_menulist_site_chat_avatar_preset', $avatar_preset, false);

        if ($enabled === '1') {
            maca_menulist_site_chat_install_bundled_avatars();

            if (
                $avatar_preset === ''
                && trim((string) get_option('maca_menulist_site_chat_avatar_url', '')) === ''
            ) {
                update_option('maca_menulist_site_chat_avatar_preset', 'female', false);
            }
        }
        update_option('maca_menulist_site_chat_embedding_model', $embedding_model, false);
        update_option('maca_menulist_site_chat_chat_model', $chat_model, false);
        update_option('maca_menulist_site_chat_rate_limit', max(5, min(200, $rate_limit)), false);
        update_option('maca_menulist_site_chat_wp_page_ids', array_values(array_filter($page_ids)), false);

        if (
            function_exists('maca_menulist_admin_secret_should_update')
            && isset($_POST['maca_site_chat_api_key'])
            && maca_menulist_admin_secret_should_update(wp_unslash($_POST['maca_site_chat_api_key']))
        ) {
            $api_key = sanitize_text_field(wp_unslash($_POST['maca_site_chat_api_key']));
            update_option(
                'maca_menulist_site_chat_api_key',
                maca_menulist_site_chat_encrypt_secret($api_key),
                false
            );
        }

        maca_menulist_site_chat_maybe_schedule_cron();

        if ($enabled === '1' && maca_menulist_site_chat_has_api_key()) {
            maca_menulist_site_chat_schedule_reindex();
        }

        add_settings_error(
            'maca_site_chat',
            'maca_site_chat_saved',
            __('Chatbot settings saved.', 'maca-restu-pro'),
            'success'
        );
    }

    /**
     * AJAX index build for admin button.
     *
     * @return void
     */
    public function ajax_build_index() {
        check_ajax_referer('maca_site_chat_admin', 'nonce');

        if (!maca_menulist_user_can_manage_plugin() || !maca_menulist_site_chat_feature_available()) {
            wp_send_json_error(array('message' => __('Permission denied.', 'maca-restu-pro')));
        }

        $result = maca_menulist_site_chat_build_index();

        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        }

        wp_send_json_success($result);
    }

    /**
     * Enqueue admin test chat assets.
     *
     * @param string $hook Admin page hook.
     * @return void
     */
    public function enqueue_admin_assets($hook) {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';

        if ($page !== 'maca-restu-site-chat') {
            return;
        }

        wp_enqueue_style(
            'maca-menulist-site-chat',
            MACA_MENULIST_PLUGIN_URL . 'assets/css/site-chat.css',
            array(),
            MACA_MENULIST_VERSION
        );

        wp_enqueue_media();

        wp_enqueue_script(
            'maca-menulist-admin-site-chat',
            MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-site-chat.js',
            array(),
            MACA_MENULIST_VERSION,
            true
        );

        wp_localize_script(
            'maca-menulist-admin-site-chat',
            'macaSiteChatAdmin',
            array(
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('maca_site_chat_admin'),
                'thinking' => __('Thinking…', 'maca-restu-pro'),
                'error' => __('Could not get an answer.', 'maca-restu-pro'),
                'noIndex' => __('Build the search index before testing the chatbot.', 'maca-restu-pro'),
            )
        );
    }

    /**
     * AJAX: admin test question (no guest rate limit).
     *
     * @return void
     */
    public function ajax_admin_ask() {
        check_ajax_referer('maca_site_chat_admin', 'nonce');

        if (!maca_menulist_user_can_manage_plugin() || !maca_menulist_site_chat_feature_available()) {
            wp_send_json_error(array('message' => __('Permission denied.', 'maca-restu-pro')));
        }

        $question = isset($_POST['question']) ? sanitize_text_field(wp_unslash($_POST['question'])) : '';
        $history = array();

        if (isset($_POST['history']) && is_string($_POST['history'])) {
            $decoded = json_decode(wp_unslash($_POST['history']), true);

            if (is_array($decoded)) {
                $history = $decoded;
            }
        }

        $result = maca_menulist_site_chat_ask(
            $question,
            $history,
            array(
                'skip_rate_limit' => true,
            )
        );

        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        }

        wp_send_json_success($result);
    }

    /**
     * Render admin page.
     *
     * @return void
     */
    public function render_page() {
        if (!maca_menulist_user_can_manage_plugin()) {
            wp_die(esc_html__('You do not have permission to access this page.', 'maca-restu-pro'));
        }

        if (!maca_menulist_site_chat_feature_available()) {
            echo maca_menulist_pro_locked_notice('site_chatbot'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (isset($_GET['maca_site_chat_notice'], $_GET['maca_site_chat_message'])) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $type = sanitize_key(wp_unslash($_GET['maca_site_chat_notice'])) === 'success' ? 'success' : 'error';
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $message = sanitize_text_field(rawurldecode((string) wp_unslash($_GET['maca_site_chat_message'])));
            add_settings_error('maca_site_chat', 'maca_site_chat_build', $message, $type);
        }

        settings_errors('maca_site_chat');

        $enabled = maca_menulist_site_chat_enabled();
        $floating = get_option('maca_menulist_site_chat_floating', '0') === '1';
        $embedding_model = maca_menulist_site_chat_get_embedding_model();
        $chat_model = maca_menulist_site_chat_get_chat_model();
        $rate_limit = maca_menulist_site_chat_get_rate_limit();
        $has_key = maca_menulist_site_chat_has_api_key();
        $index_status = maca_menulist_site_chat_get_index_status();
        $chunk_count = maca_menulist_db_site_chat_count_chunks();
        $selected_pages = maca_menulist_site_chat_get_wp_page_ids();
        $chat_name = maca_menulist_site_chat_get_name_local();
        $chat_name_en = maca_menulist_site_chat_get_name_en();
        $avatar_url = maca_menulist_site_chat_get_avatar_url();
        $avatar_preset = maca_menulist_site_chat_get_avatar_preset();
        $custom_avatar_url = trim((string) get_option('maca_menulist_site_chat_avatar_url', ''));
        $bundled_avatars = maca_menulist_site_chat_get_bundled_avatars();

        if ($avatar_preset === '' && $custom_avatar_url !== '') {
            $avatar_preset = 'custom';
        }

        if ($avatar_preset === '') {
            $avatar_preset = 'female';
        }

        $pages = get_pages(
            array(
                'sort_column' => 'post_title',
                'sort_order' => 'ASC',
            )
        );
        ?>
        <div class="wrap maca-admin-wrap">
            <h1><?php esc_html_e('Chatt', 'maca-restu-pro'); ?></h1>
            <p class="description">
                <?php esc_html_e('Answer guest questions using your own OpenAI API key. Content is indexed locally — only relevant snippets are sent with each question.', 'maca-restu-pro'); ?>
            </p>

            <form method="post">
                <?php wp_nonce_field('maca_site_chat', 'maca_site_chat_nonce'); ?>
                <input type="hidden" name="maca_site_chat_action" value="save_settings">

                <h2><?php esc_html_e('Appearance', 'maca-restu-pro'); ?></h2>
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row">
                            <label for="maca_site_chat_name"><?php echo esc_html(maca_menulist_admin_primary_field_label(__('Chatbot name', 'maca-restu-pro'))); ?></label>
                        </th>
                        <td>
                            <input type="text" class="regular-text" id="maca_site_chat_name" name="maca_site_chat_name" value="<?php echo esc_attr($chat_name); ?>" placeholder="<?php echo esc_attr(maca_menulist_site_chat_get_default_display_name()); ?>">
                            <p class="description"><?php esc_html_e('Shown in the chat header on the website. Leave empty for the default title.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <?php if (maca_menulist_admin_show_local_content_fields()) : ?>
                    <tr>
                        <th scope="row">
                            <label for="maca_site_chat_name_en"><?php echo esc_html(maca_menulist_bilingual_field_label(__('Chatbot name', 'maca-restu-pro'), true)); ?></label>
                        </th>
                        <td>
                            <input type="text" class="regular-text" id="maca_site_chat_name_en" name="maca_site_chat_name_en" value="<?php echo esc_attr($chat_name_en); ?>" placeholder="<?php esc_attr_e('Restaurant assistant', 'maca-restu-pro'); ?>">
                        </td>
                    </tr>
                    <?php endif; ?>
                    <tr>
                        <th scope="row"><?php esc_html_e('Chatbot image', 'maca-restu-pro'); ?></th>
                        <td>
                            <fieldset class="maca-site-chat-avatar-picker">
                                <legend class="screen-reader-text"><?php esc_html_e('Chatbot image', 'maca-restu-pro'); ?></legend>
                                <div class="maca-site-chat-avatar-options">
                                    <?php foreach ($bundled_avatars as $preset_key => $preset_data) : ?>
                                        <?php
                                        $preset_url = maca_menulist_site_chat_get_bundled_avatar_url($preset_key);
                                        $preset_id = 'maca_site_chat_avatar_preset_' . $preset_key;
                                        ?>
                                        <label class="maca-site-chat-avatar-option" for="<?php echo esc_attr($preset_id); ?>">
                                            <input
                                                type="radio"
                                                name="maca_site_chat_avatar_preset"
                                                id="<?php echo esc_attr($preset_id); ?>"
                                                value="<?php echo esc_attr($preset_key); ?>"
                                                <?php checked($avatar_preset, $preset_key); ?>
                                            >
                                            <?php if ($preset_url !== '') : ?>
                                                <img src="<?php echo esc_url($preset_url); ?>" alt="" width="64" height="64">
                                            <?php endif; ?>
                                            <span><?php echo esc_html($preset_data['label']); ?></span>
                                        </label>
                                    <?php endforeach; ?>
                                    <label class="maca-site-chat-avatar-option" for="maca_site_chat_avatar_preset_custom">
                                        <input
                                            type="radio"
                                            name="maca_site_chat_avatar_preset"
                                            id="maca_site_chat_avatar_preset_custom"
                                            value="custom"
                                            <?php checked($avatar_preset, 'custom'); ?>
                                        >
                                        <span class="maca-site-chat-avatar-option-custom-icon" aria-hidden="true">+</span>
                                        <span><?php esc_html_e('Custom image', 'maca-restu-pro'); ?></span>
                                    </label>
                                </div>
                            </fieldset>
                            <div class="maca-site-chat-avatar-custom" <?php echo $avatar_preset === 'custom' ? '' : 'hidden'; ?>>
                                <input type="url" class="regular-text" id="maca_site_chat_avatar_url" name="maca_site_chat_avatar_url" value="<?php echo esc_attr($custom_avatar_url); ?>">
                                <button type="button" class="button maca-site-chat-upload" data-target="#maca_site_chat_avatar_url"><?php esc_html_e('Select image', 'maca-restu-pro'); ?></button>
                                <?php if ($custom_avatar_url !== '') : ?>
                                    <p class="maca-site-chat-avatar-preview"><img src="<?php echo esc_url($custom_avatar_url); ?>" alt="" width="64" height="64"></p>
                                <?php endif; ?>
                            </div>
                            <p class="description"><?php esc_html_e('Portrait shown in the chat header and floating button. Built-in avatars are copied to your media library when the chatbot is enabled.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                </table>

                <h2><?php esc_html_e('Settings', 'maca-restu-pro'); ?></h2>
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><?php esc_html_e('Enable chatbot', 'maca-restu-pro'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="maca_site_chat_enabled" value="1" <?php checked($enabled); ?>>
                                <?php esc_html_e('Show chatbot on the website', 'maca-restu-pro'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Floating button', 'maca-restu-pro'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="maca_site_chat_floating" value="1" <?php checked($floating); ?>>
                                <?php esc_html_e('Show floating chat button on all public pages', 'maca-restu-pro'); ?>
                            </label>
                            <p class="description"><?php esc_html_e('You can also place the chatbot with shortcode [maca_site_chat] or the Chatt block.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_site_chat_api_key"><?php esc_html_e('OpenAI API key', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <?php
                            $api_key_attrs = maca_menulist_admin_secret_input_attrs(
                                $has_key,
                                array(
                                    'id' => 'maca_site_chat_api_key',
                                    'name' => 'maca_site_chat_api_key',
                                )
                            );
                            ?>
                            <input <?php echo maca_menulist_admin_secret_field_attr_string($api_key_attrs); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
                            <p class="description"><?php esc_html_e('Stored encrypted on your server. Used for indexing (embeddings) and guest chat. Billing goes to your OpenAI account.', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_site_chat_embedding_model"><?php esc_html_e('Embedding model', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" class="regular-text" id="maca_site_chat_embedding_model" name="maca_site_chat_embedding_model" value="<?php echo esc_attr($embedding_model); ?>">
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_site_chat_chat_model"><?php esc_html_e('Chat model', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" class="regular-text" id="maca_site_chat_chat_model" name="maca_site_chat_chat_model" value="<?php echo esc_attr($chat_model); ?>">
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="maca_site_chat_rate_limit"><?php esc_html_e('Rate limit', 'maca-restu-pro'); ?></label>
                        </th>
                        <td>
                            <input type="number" min="5" max="200" id="maca_site_chat_rate_limit" name="maca_site_chat_rate_limit" value="<?php echo esc_attr((string) $rate_limit); ?>">
                            <span class="description"><?php esc_html_e('Questions per hour per visitor IP', 'maca-restu-pro'); ?></span>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('WordPress pages', 'maca-restu-pro'); ?></th>
                        <td>
                            <?php if (empty($pages)) : ?>
                                <p><?php esc_html_e('No published pages found.', 'maca-restu-pro'); ?></p>
                            <?php else : ?>
                                <fieldset>
                                    <legend class="screen-reader-text"><?php esc_html_e('Include WordPress pages in the chat index', 'maca-restu-pro'); ?></legend>
                                    <?php foreach ($pages as $page) : ?>
                                        <label style="display:block;margin-bottom:4px;">
                                            <input type="checkbox" name="maca_site_chat_wp_page_ids[]" value="<?php echo esc_attr((string) $page->ID); ?>" <?php checked(in_array((int) $page->ID, $selected_pages, true)); ?>>
                                            <?php echo esc_html(get_the_title($page)); ?>
                                        </label>
                                    <?php endforeach; ?>
                                </fieldset>
                                <p class="description"><?php esc_html_e('Optional. Page slug and path are indexed so the chatbot can point guests to the right page. Restu content (menu, hours, events, booking rules) is always indexed when available.', 'maca-restu-pro'); ?></p>
                            <?php endif; ?>
                        </td>
                    </tr>
                </table>

                <?php submit_button(__('Save settings', 'maca-restu-pro')); ?>
            </form>

            <hr>

            <h2><?php esc_html_e('Search index', 'maca-restu-pro'); ?></h2>
            <p>
                <?php
                printf(
                    /* translators: %d: chunk count */
                    esc_html__('Indexed chunks: %d', 'maca-restu-pro'),
                    (int) $chunk_count
                );
                ?>
            </p>
            <?php if (!empty($index_status['built_at'])) : ?>
                <p class="description">
                    <?php
                    printf(
                        /* translators: 1: datetime, 2: status message */
                        esc_html__('Last build: %1$s — %2$s', 'maca-restu-pro'),
                        esc_html((string) $index_status['built_at']),
                        esc_html((string) ($index_status['message'] ?? ''))
                    );
                    ?>
                </p>
            <?php endif; ?>

            <p><?php esc_html_e('Indexed sources: menu dishes, active campaign menus, opening hours and exceptions, Info hub news and events, booking rules, menu footer, and selected WordPress pages.', 'maca-restu-pro'); ?></p>

            <form method="post" style="margin-top:12px;">
                <?php wp_nonce_field('maca_site_chat', 'maca_site_chat_nonce'); ?>
                <input type="hidden" name="maca_site_chat_action" value="build_index">
                <?php submit_button(__('Build index now', 'maca-restu-pro'), 'secondary', 'submit', false); ?>
            </form>

            <p class="description"><?php esc_html_e('Rebuild after menu or content changes. A daily automatic rebuild runs when the chatbot is enabled. Content changes also schedule a rebuild after about two minutes.', 'maca-restu-pro'); ?></p>

            <hr>

            <h2><?php esc_html_e('Test chat', 'maca-restu-pro'); ?></h2>
            <p class="description"><?php esc_html_e('Try questions here before enabling the chatbot for guests. Uses the same index and OpenAI settings as the public widget.', 'maca-restu-pro'); ?></p>

            <?php if ($chunk_count <= 0) : ?>
                <p><?php esc_html_e('Build the search index first to test the chatbot.', 'maca-restu-pro'); ?></p>
            <?php else : ?>
                <div class="maca-site-chat maca-site-chat--admin-test" data-maca-site-chat-admin="1">
                    <div class="maca-site-chat-panel">
                        <div class="maca-site-chat-header">
                            <div class="maca-site-chat-header-main">
                            <?php if ($avatar_url !== '') : ?>
                                <img class="maca-site-chat-avatar" src="<?php echo esc_url($avatar_url); ?>" alt="" width="36" height="36">
                            <?php endif; ?>
                            <strong class="maca-site-chat-title"><?php echo esc_html(maca_menulist_site_chat_get_display_name()); ?></strong>
                            </div>
                        </div>
                        <div class="maca-site-chat-messages" role="log" aria-live="polite"></div>
                        <form class="maca-site-chat-form">
                            <label class="screen-reader-text" for="maca-site-chat-admin-input"><?php esc_html_e('Test question', 'maca-restu-pro'); ?></label>
                            <textarea id="maca-site-chat-admin-input" class="maca-site-chat-input" rows="2" placeholder="<?php esc_attr_e('e.g. Are you open on Sunday? Is there gluten-free food?', 'maca-restu-pro'); ?>"></textarea>
                            <button type="submit" class="maca-site-chat-send"><?php esc_html_e('Send', 'maca-restu-pro'); ?></button>
                        </form>
                    </div>
                </div>
            <?php endif; ?>
        </div>
        <?php $this->render_media_uploader_script(); ?>
        <?php
    }

    /**
     * Media library picker for chatbot avatar.
     *
     * @return void
     */
    private function render_media_uploader_script() {
        ?>
        <script>
        jQuery(function($) {
            function syncAvatarCustomField() {
                var isCustom = $('input[name="maca_site_chat_avatar_preset"]:checked').val() === 'custom';
                $('.maca-site-chat-avatar-custom').prop('hidden', !isCustom);
            }

            $('input[name="maca_site_chat_avatar_preset"]').on('change', syncAvatarCustomField);
            syncAvatarCustomField();

            $('.maca-site-chat-upload').on('click', function(e) {
                e.preventDefault();
                var target = $(this).data('target');
                var frame = wp.media({
                    title: <?php echo wp_json_encode(__('Select image', 'maca-restu-pro')); ?>,
                    button: { text: <?php echo wp_json_encode(__('Use image', 'maca-restu-pro')); ?> },
                    multiple: false
                });
                frame.on('select', function() {
                    var attachment = frame.state().get('selection').first().toJSON();
                    $(target).val(attachment.url);
                    $('#maca_site_chat_avatar_preset_custom').prop('checked', true);
                    syncAvatarCustomField();
                });
                frame.open();
            });
        });
        </script>
        <?php
    }
}

new Maca_MenuList_Admin_Site_Chat();
