<?php

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

/**
 * The public-facing functionality of the plugin.
 *
 * @since      1.6.5
 */
class NewCodeByte_Chatbot_Frontend {

    /**
     * Register the hooks related to the public-facing functionality.
     *
     * @since    1.6.5
     */
    public function add_hooks() {
        // Carica SEMPRE gli script e gli stili su ogni pagina del frontend.
        // Questo è il metodo "primitivo" ma a prova di cache.
        add_action('wp_enqueue_scripts', [$this, 'enqueue_assets']);

        // Aggiunge l'HTML del widget al footer solo se la modalità è "widget".
        add_action('wp_footer', [$this, 'render_widget_html']);
        
        // Registra lo shortcode.
        add_shortcode('newcodebyte_chatbot', [$this, 'render_shortcode']);
    }

    /**
     * Enqueue scripts and styles for the public-facing side of the site.
     * Questa funzione ora viene eseguita sempre.
     *
     * @since    1.6.5
     */
    public function enqueue_assets() {
        // Non caricare nulla nel backend.
        if (is_admin()) {
            return;
        }

        wp_enqueue_script('chatbot-js', NCB_CHATBOT_PLUGIN_URL . 'assets/js/chatbot.js', ['jquery'], NCB_CHATBOT_VERSION, true);
        wp_enqueue_style('chatbot-style', NCB_CHATBOT_PLUGIN_URL . 'assets/css/chatbot.css', [], NCB_CHATBOT_VERSION);
        wp_enqueue_script('marked-js', NCB_CHATBOT_PLUGIN_URL . 'assets/js/marked.min.js', [], '15.0.7', true);
        wp_enqueue_script('dompurify-js', NCB_CHATBOT_PLUGIN_URL . 'assets/js/purify.min.js', [], '3.2.5', true);

        $custom_css = "
            :root {
                --chatbot-window-height: " . esc_attr(get_option('newcodebyte_chatbot_window_height', '600')) . "px;
                --chatbot-header-bg-color: " . esc_attr(get_option('newcodebyte_chatbot_header_bg_color', '#038AF9')) . ";
                --chatbot-header-text-color: " . esc_attr(get_option('newcodebyte_chatbot_header_text_color', '#fff')) . ";
                --chatbot-chatbox-bg-color: " . esc_attr(get_option('newcodebyte_chatbot_chatbox_bg_color', '#fff')) . ";
                --chatbot-user-message-bg-color: " . esc_attr(get_option('newcodebyte_chatbot_user_message_bg_color', '#add8e6')) . ";
                --chatbot-user-message-text-color: " . esc_attr(get_option('newcodebyte_chatbot_user_message_text_color', '#000')) . ";
                --chatbot-bot-message-bg-color: " . esc_attr(get_option('newcodebyte_chatbot_bot_message_bg_color', '#ffc0cb')) . ";
                --chatbot-bot-message-text-color: " . esc_attr(get_option('newcodebyte_chatbot_bot_message_text_color', '#000')) . ";
                --chatbot-send-button-bg-color: " . esc_attr(get_option('newcodebyte_chatbot_send_button_bg_color', '#dc3232')) . ";
                --chatbot-send-button-text-color: " . esc_attr(get_option('newcodebyte_chatbot_send_button_text_color', '#fff')) . ";
            }
        ";
        wp_add_inline_style('chatbot-style', $custom_css);

        wp_localize_script('chatbot-js', 'chatbot_i18n', [
            'type_your_message' => __('Type your message...', NCB_CHATBOT_TEXT_DOMAIN),
            'send' => __('Send', NCB_CHATBOT_TEXT_DOMAIN),
            'there_was_an_error' => __('There was an error.', NCB_CHATBOT_TEXT_DOMAIN),
            'welcome_message' => esc_attr(get_option('newcodebyte_chatbot_welcome_message', __('Hello! How can I assist you today?', NCB_CHATBOT_TEXT_DOMAIN))),
            'prechat_title' => esc_html(get_option('newcodebyte_chatbot_prechat_title', __('Before we start chatting', NCB_CHATBOT_TEXT_DOMAIN))),
            'prechat_description' => esc_html(get_option('newcodebyte_chatbot_prechat_description', __('Please provide the following information:', NCB_CHATBOT_TEXT_DOMAIN))),
            'prechat_name_label' => esc_html(get_option('newcodebyte_chatbot_prechat_name_label', __('Name', NCB_CHATBOT_TEXT_DOMAIN))),
            'prechat_email_label' => esc_html(get_option('newcodebyte_chatbot_prechat_email_label', __('Email', NCB_CHATBOT_TEXT_DOMAIN))),
            'prechat_button_text' => esc_html(get_option('newcodebyte_chatbot_prechat_button_text', __('Start Chat', NCB_CHATBOT_TEXT_DOMAIN))),
            'prechat_error_message' => esc_html(get_option('newcodebyte_chatbot_prechat_error_message', __('Please fill in all required fields.', NCB_CHATBOT_TEXT_DOMAIN))),
        ]);

        $custom_sound_url = get_option('newcodebyte_chatbot_notification_sound_url', '');
        $final_sound_url = !empty($custom_sound_url) ? $custom_sound_url : NCB_CHATBOT_PLUGIN_URL . 'assets/sounds/notification.mp3';

        wp_localize_script('chatbot-js', 'chatbot_params', [
            'chatbot_user_avatar_url' => esc_url(get_option('newcodebyte_chatbot_user_avatar_url', NCB_CHATBOT_PLUGIN_URL . 'assets/images/icon-user.png')),
            'chatbot_bot_avatar_url' => esc_url(get_option('newcodebyte_chatbot_bot_avatar_url', NCB_CHATBOT_PLUGIN_URL . 'assets/images/icon-bot.png')),
            'chatbot_icon_open_url' => esc_url(get_option('newcodebyte_chatbot_icon_open_url', NCB_CHATBOT_PLUGIN_URL . 'assets/images/icon-open.png')),
            'chatbot_icon_closed_url' => esc_url(get_option('newcodebyte_chatbot_icon_closed_url', NCB_CHATBOT_PLUGIN_URL . 'assets/images/icon-closed.gif')),
            'notification_sound_url' => esc_url($final_sound_url),
            'loading_gif_url' => esc_url(NCB_CHATBOT_PLUGIN_URL . 'assets/images/loading.gif'),
            'enable_prechat_form' => get_option('newcodebyte_chatbot_enable_prechat_form', '0'),
            'enable_proactive' => get_option('newcodebyte_chatbot_enable_proactive_message', '0'),
            'proactive_text' => get_option('newcodebyte_chatbot_proactive_message_text', __("Have a question?\nAsk me!", NCB_CHATBOT_TEXT_DOMAIN)),
            'proactive_delay' => get_option('newcodebyte_chatbot_proactive_message_delay', '5'),
            'site_id' => 'ncb_' . md5(get_home_url())
        ]);

        wp_localize_script('chatbot-js', 'chatbot_ajax', [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'newcodebyte_chatbot_message_nonce' => wp_create_nonce('newcodebyte_chatbot_send_message')
        ]);
    }

    /**
     * Render the chatbox widget HTML in the footer, only if in widget mode.
     *
     * @since    1.6.5
     */
    public function render_widget_html() {
        $display_mode = get_option('newcodebyte_chatbot_display_mode', 'widget');
        if ($display_mode === 'widget') {
            $is_widget = true;
            require_once NCB_CHATBOT_PLUGIN_DIR . 'public/views/chatbot-display.php';
        }
    }

    /**
     * Render the chatbot for the [newcodebyte_chatbot] shortcode.
     *
     * @param array $atts Shortcode attributes.
     * @return string The shortcode output.
     * @since    1.6.5
     */
    public function render_shortcode($atts) {
        $display_mode = get_option('newcodebyte_chatbot_display_mode', 'widget');
        if ($display_mode !== 'shortcode') {
            return '';
        }

        // Gli script sono già caricati globalmente, non serve chiamare enqueue qui.

        ob_start();
        $is_widget = false;
        require NCB_CHATBOT_PLUGIN_DIR . 'public/views/chatbot-display.php';
        $chatbox_html = ob_get_clean();

        $output = '<div class="chatbot-shortcode-wrapper">' . $chatbox_html . '</div>';
        $output .= "<script>
            document.addEventListener('DOMContentLoaded', function() {
                (function($) {
                    var wrapper = $('.chatbot-shortcode-wrapper');
                    if (wrapper.length) {
                        var chatbox = wrapper.find('#chatbox');
                        if (chatbox.length) {
                            chatbox.css({'display': 'flex', 'position': 'absolute', 'bottom': '0', 'height': '100%', 'width': '100%', 'right': 'auto', 'left': 'auto'});
                            chatbox.find('#chatbox-close').hide();
                            $(document).trigger('chatbot:ready');
                        }
                    }
                })(jQuery);
            });
        </script>";
        
        return $output;
    }
}