<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @package Inqyra
 */
// If this file is called directly, abort.
if ( !defined( 'WPINC' ) ) {
    die;
}
/**
 * Public class.
 */
class Inqyra_Public {
    /**
     * Plugin name.
     *
     * @var string
     */
    private $plugin_name;

    /**
     * Plugin version.
     *
     * @var string
     */
    private $version;

    /**
     * Current agent.
     *
     * @var object|null
     */
    private $agent;

    /**
     * Initialize the class.
     *
     * @param string $plugin_name The plugin name.
     * @param string $version     The plugin version.
     */
    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        $this->agent = $this->get_active_agent();
    }

    /**
     * Register public styles.
     */
    public function enqueue_styles() {
        if ( !$this->should_load_widget() ) {
            return;
        }
        wp_enqueue_style(
            $this->plugin_name . '-widget',
            INQYRA_URL . 'public/css/inqyra-widget.css',
            [],
            $this->version
        );
    }

    /**
     * Register public scripts.
     */
    public function enqueue_scripts() {
        if ( !$this->should_load_widget() ) {
            return;
        }
        wp_enqueue_script(
            $this->plugin_name . '-widget',
            INQYRA_URL . 'public/js/inqyra-widget.js',
            [],
            $this->version,
            true
        );
        // Pass configuration to JavaScript
        wp_localize_script( $this->plugin_name . '-widget', 'inqyraConfig', $this->get_widget_config() );
    }

    /**
     * Render the chat widget in the footer.
     */
    public function render_widget() {
        if ( !$this->should_load_widget() ) {
            return;
        }
        // Add CSS to hide widget on mobile if disabled.
        if ( isset( $this->agent->widget_mobile_enabled ) && !$this->agent->widget_mobile_enabled ) {
            wp_add_inline_style( $this->plugin_name . '-widget', '@media (max-width: 767px) { #inqyra-widget-container { display: none !important; } }' );
        }
        // Widget container - JavaScript will populate this
        echo '<div id="inqyra-widget-container"></div>';
    }

    /**
     * Check if the widget should be loaded on this page.
     *
     * @return bool Whether to load the widget.
     */
    private function should_load_widget() : bool {
        // Block widget if premium license has expired
        if ( function_exists( 'inqyra_is_license_expired' ) && inqyra_is_license_expired() ) {
            return false;
        }
        // Don't load in admin
        if ( is_admin() ) {
            return false;
        }
        // Need an active agent
        if ( !$this->agent ) {
            return false;
        }
        // Check if widget is enabled
        if ( isset( $this->agent->widget_enabled ) && !$this->agent->widget_enabled ) {
            return false;
        }
        // Check page visibility settings
        if ( !$this->should_display_on_current_page() ) {
            return false;
        }
        // Check if the agent's specific provider has an API key
        $provider_key = Inqyra_AI_Provider_Factory::get_api_key( $this->agent->provider ?? 'claude' );
        if ( empty( $provider_key ) ) {
            return false;
        }
        // Check if daily token limit is exceeded
        if ( !empty( $this->agent->daily_token_limit ) && $this->agent->daily_token_limit > 0 ) {
            global $wpdb;
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
            $daily_tokens = (int) $wpdb->get_var( $wpdb->prepare(
                'SELECT COALESCE(SUM(m.tokens_used), 0) FROM %i m
                 JOIN %i c ON c.id = m.conversation_id
                 WHERE c.agent_id = %d AND m.created_at > DATE_SUB(NOW(), INTERVAL 1 DAY)',
                $wpdb->prefix . 'inqyra_messages',
                $wpdb->prefix . 'inqyra_conversations',
                $this->agent->id
            ) );
            if ( $daily_tokens >= $this->agent->daily_token_limit ) {
                return false;
            }
        }
        // Check if daily cost limit is exceeded
        if ( !empty( $this->agent->cost_limit_usd ) && $this->agent->cost_limit_usd > 0 ) {
            global $wpdb;
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
            $daily_cost = (float) $wpdb->get_var( $wpdb->prepare(
                'SELECT COALESCE(SUM(m.cost_usd), 0) FROM %i m
                 JOIN %i c ON c.id = m.conversation_id
                 WHERE c.agent_id = %d AND m.created_at > DATE_SUB(NOW(), INTERVAL 1 DAY)',
                $wpdb->prefix . 'inqyra_messages',
                $wpdb->prefix . 'inqyra_conversations',
                $this->agent->id
            ) );
            if ( $daily_cost >= $this->agent->cost_limit_usd ) {
                return false;
            }
        }
        return true;
    }

    /**
     * Check if widget should display on the current page based on visibility settings.
     *
     * @return bool Whether to display on this page.
     */
    private function should_display_on_current_page() : bool {
        return true;
    }

    /**
     * Get the active agent for the current site.
     *
     * @return object|null Agent object or null.
     */
    private function get_active_agent() {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
        return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE active = 1 ORDER BY updated_at DESC LIMIT 1", $wpdb->prefix . 'inqyra_agents' ) );
    }

    /**
     * Get widget configuration for JavaScript.
     *
     * @return array Widget configuration.
     */
    private function get_widget_config() : array {
        if ( !$this->agent ) {
            return [];
        }
        // Get header icon URL if set
        $header_icon_url = '';
        $header_icon_id = ( isset( $this->agent->header_icon_id ) ? (int) $this->agent->header_icon_id : 0 );
        if ( $header_icon_id ) {
            $header_icon_url = wp_get_attachment_image_url( $header_icon_id, 'thumbnail' );
        }
        // Get send button icon URL if set
        $send_button_icon_url = '';
        $send_button_icon_id = ( isset( $this->agent->send_button_icon_id ) ? (int) $this->agent->send_button_icon_id : 0 );
        if ( $send_button_icon_id ) {
            $send_button_icon_url = wp_get_attachment_image_url( $send_button_icon_id, 'thumbnail' );
        }
        return [
            'restUrl'             => rest_url( 'inqyra/v1' ),
            'nonce'               => wp_create_nonce( 'wp_rest' ),
            'agentId'             => $this->agent->id,
            'position'            => ( $this->agent->widget_position ?: 'bottom-right' ),
            'primaryColor'        => ( $this->agent->primary_color ?: '#0d6efd' ),
            'textColor'           => ( $this->agent->text_color ?: '#ffffff' ),
            'greeting'            => ( $this->agent->greeting_message ?: '' ),
            'headerTitle'         => ( $this->agent->header_title ?: 'Chat' ),
            'headerSubtitle'      => ( $this->agent->header_subtitle ?: '' ),
            'buttonText'          => ( $this->agent->button_text ?: '' ),
            'poweredBy'           => $this->agent->powered_by_text ?? '',
            'poweredByUrl'        => '',
            'language'            => ( $this->agent->language ?: 'nl' ),
            'headerIconUrl'       => ( $header_icon_url ?: '' ),
            'showIconInMessages'  => !empty( $this->agent->show_icon_in_messages ),
            'sendButtonIconUrl'   => ( $send_button_icon_url ?: '' ),
            'sendButtonText'      => $this->agent->send_button_text ?? '',
            'mobileEnabled'       => ( isset( $this->agent->widget_mobile_enabled ) ? (bool) $this->agent->widget_mobile_enabled : true ),
            'conversationPersist' => !empty( $this->agent->conversation_persist ),
            'strings'             => $this->get_localized_strings(),
            'browserEmbeddings'   => !defined( 'INQYRA_DISABLE_BROWSER_EMBEDDINGS' ) || !INQYRA_DISABLE_BROWSER_EMBEDDINGS,
            'transformersUrl'     => ( defined( 'INQYRA_TRANSFORMERS_URL' ) ? INQYRA_TRANSFORMERS_URL : INQYRA_URL . 'assets/js/vendor/transformers.min.js' ),
        ];
    }

    /**
     * Get localized strings for the widget.
     *
     * @return array Localized strings.
     */
    private function get_localized_strings(): array {
        $lang = $this->agent->language ?? 'en';

        $placeholders = self::get_placeholder_translations();
        $default_placeholder = $placeholders[$lang] ?? $placeholders['en'];

        // Use custom placeholder if set, empty string if hidden, otherwise language default.
        if (!empty($this->agent->hide_input_placeholder)) {
            $placeholder = '';
        } elseif (($this->agent->input_placeholder ?? '') !== '') {
            $placeholder = $this->agent->input_placeholder;
        } else {
            $placeholder = $default_placeholder;
        }

        if ($lang === 'nl') {
            return [
                'placeholder' => $placeholder,
                'send'        => 'Verstuur',
                'typing'      => 'Aan het typen...',
                'error'       => 'Er is een fout opgetreden. Probeer het opnieuw.',
                'offline'     => 'Geen internetverbinding.',
                'rateLimit'   => 'Te veel berichten. Wacht even.',
            ];
        }

        return [
            'placeholder' => $placeholder,
            'send'        => 'Send',
            'typing'      => 'Typing...',
            'error'       => 'An error occurred. Please try again.',
            'offline'     => 'No internet connection.',
            'rateLimit'   => 'Too many messages. Please wait.',
        ];
    }

    /**
     * Get placeholder translations for all supported languages.
     *
     * @return array Language code => placeholder text.
     */
    public static function get_placeholder_translations(): array {
        return [
            'nl' => 'Stel een vraag...',
            'en' => 'Ask a question...',
            'de' => 'Stellen Sie eine Frage...',
            'fr' => 'Posez une question...',
            'es' => 'Haz una pregunta...',
            'it' => 'Fai una domanda...',
            'pt' => 'Faça uma pergunta...',
            'pl' => 'Zadaj pytanie...',
            'sv' => 'Ställ en fråga...',
            'da' => 'Stil et spørgsmål...',
            'no' => 'Still et spørsmål...',
            'fi' => 'Esitä kysymys...',
            'ja' => '質問してください...',
            'ko' => '질문하세요...',
            'zh' => '请提问...',
            'ar' => 'اطرح سؤالاً...',
            'tr' => 'Bir soru sorun...',
            'ru' => 'Задайте вопрос...',
            'uk' => 'Поставте запитання...',
            'cs' => 'Položte otázku...',
            'ro' => 'Pune o întrebare...',
            'hu' => 'Tegyen fel egy kérdést...',
            'el' => 'Κάντε μια ερώτηση...',
            'he' => 'שאל שאלה...',
            'th' => 'ถามคำถาม...',
            'vi' => 'Đặt câu hỏi...',
            'id' => 'Ajukan pertanyaan...',
            'ms' => 'Tanya soalan...',
            'hi' => 'एक सवाल पूछें...',
        ];
    }

}
