<?php
namespace AI_BotKit\Public;

use AI_BotKit\Models\Chatbot;

/**
 * Handles shortcode integration for the chat interface
 */
class Shortcode_Handler {

    public function __construct() {
        $this->register_shortcodes();
    }

    /**
     * Register shortcodes
     */
    private function register_shortcodes(): void {
        add_shortcode('ai_botkit_widget', [$this, 'render_widget']);
    }

    /**
     * Render chat widget
     * 
     * @param array $atts Shortcode attributes
     * @return string Rendered chat widget
     */
    public function render_widget($atts = []): string {
        // Parse attributes
        $args = shortcode_atts([
            'id' => '',
        ], $atts);

        // Sanitize input
        $chatbot_id = sanitize_text_field($args['id']);

        global $ai_botkit_url;
        wp_enqueue_script(
            'ai-botkit-chatbot',
            $ai_botkit_url . '/embed.js',
            [],
            AI_BOTKIT_VERSION,
            false
        );

        return sprintf(
            '<div id="ai-bot-kit-chatbot" data-chatbot-id="%s"></div>',
            esc_attr($chatbot_id)
        );
    }

    /**
     * Render sitewide chatbot
     */
    public function render_sitewide_chatbot(): void {
        $site_wide_chatbot_id = get_option('ai_botkit_chatbot_sitewide_enabled');
        $enabled_pages = get_option('ai_botkit_chatbot_enabled_pages');
        $enabled_post_types = get_option('ai_botkit_chatbot_enabled_post_types', []);

        // check if there is already a widget on the page
        global $post;

        if ( isset($post->post_content) && has_shortcode($post->post_content, 'ai_botkit_widget') ) {
            return;
        }

        if ( isset($site_wide_chatbot_id) && $site_wide_chatbot_id != 0 ) {
            echo do_shortcode('[ai_botkit_widget id="' . esc_attr($site_wide_chatbot_id) . '"]');
            return;
        }

        if ( is_array($enabled_pages) && isset($enabled_pages[$post->ID]) ) {
            echo do_shortcode('[ai_botkit_widget id="' . esc_attr($enabled_pages[$post->ID][0]) . '"]');
            return;
        }

        $current_post_type = get_post_type();
        if ( is_array($enabled_post_types) && isset($enabled_post_types[$current_post_type]) && !empty($enabled_post_types[$current_post_type]) ) {
            echo do_shortcode('[ai_botkit_widget id="' . esc_attr($enabled_post_types[$current_post_type][0]) . '"]');
        }
    }
    
} 
