<?php
class SeekMake_Astra_AI {

    protected $version;

    public function __construct() {
        $this->version = SEEKMAKE_VERSION;
    }

    public function init() {
        $this->load_dependencies();
        $this->define_hooks();
    }

    private function load_dependencies() {
    }

    private function define_hooks() {
        add_shortcode('seekmake_astra_ai', array($this, 'render_shortcode'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_assets'));
        add_action('elementor/widgets/register', array($this, 'register_elementor_widgets'));
    }

    public function register_elementor_widgets($widgets_manager) {
        require_once SEEKMAKE_PLUGIN_DIR . 'includes/features/astra-ai/class-astra-ai-elementor.php';
        $widgets_manager->register(new SeekMake_Astra_AI_Elementor());
    }

    public function enqueue_assets() {
        wp_enqueue_style(
            'seekmake-astra-ai',
            SEEKMAKE_PLUGIN_URL . 'assets/astra-ai/css/astra-ai.css',
            array(),
            $this->version
        );
    }

    public function render_shortcode($atts) {
        $atts = shortcode_atts(array(
            'manufacturer_id' => get_option('seekmake_manufacturer_id', ''),
            'lang' => 'en',
            'class' => ''
        ), $atts, 'seekmake_astra_ai');

        $manufacturer_id = SeekMake_Security::sanitize_manufacturer_id($atts['manufacturer_id']);
        $lang = SeekMake_Security::sanitize_language($atts['lang']);
        $custom_class = sanitize_text_field($atts['class']);

        if (!SeekMake_Security::validate_manufacturer_id($manufacturer_id, true)) {
            return '<p class="seekmake-error">' . esc_html__('Please authenticate your SeekMake account to use this feature.', 'seekmake') . '</p>';
        }

        return $this->render_inline($manufacturer_id, $lang, $custom_class);
    }

    private function render_inline($manufacturer_id, $lang, $custom_class) {
        $iframe_url = SEEKMAKE_API_URL . '/astra-bot?isEmbed=true&manufacturer=' . esc_attr($manufacturer_id) . '&lang=' . esc_attr($lang);
        $escaped_class = esc_attr($custom_class);
        
        ob_start();
        ?>
        <section id="seekmake-bot-widget" class="seekmake-astra-container <?php echo $escaped_class; ?>">
            <iframe
                id="seekmake-embed-bot"
                class="seekmake-embed-bot"
                src="<?php echo esc_url($iframe_url); ?>"
                sandbox="allow-downloads allow-scripts allow-same-origin allow-forms"
                allow="identity-credentials-get"
                style="width: 100%; height: 600px; border: 0px;"
                scrolling="no"
            ></iframe>
        </section>
        <script src="<?php echo esc_url(SEEKMAKE_API_URL . '/assets/public/iq-api-latest.js'); ?>"></script>
        <?php
        return ob_get_clean();
    }
}
