<?php

namespace Limb_Chatbot\Includes\Frontend;

use Limb_Chatbot\Includes\Data_Objects\Chatbot;
use Limb_Chatbot\Includes\Services\Session_Manager;
use Limb_Chatbot\Includes\Traits\SingletonTrait;

/**
 * Handles the frontend integration of the chatbot plugin.
 *
 * @since 1.0.0
 */
class Frontend {

	use SingletonTrait;

    /**
     * Chatbots required object localized
     *
     * @var bool Flag of chatbots required object localized info
     * @since 1.0.0
     */
    private static $chatbots_object_localized = false;

    /**
     * Flag to track if general chatbot hooks have been initialized
     *
     * @var bool
     * @since 1.0.0
     */
    private static $general_hooks_initialized = false;

	/**
	 * Initialize frontend hooks if there are published chatbots or a default published chatbot.
	 *
	 * @since 1.0.0
	 * @return void
	 */
    public function init() {
        // TODO condition can be moved to Chatbot_Service or Repository. Only
        if ( Chatbot::count( [ 'status' => Chatbot::STATUS_PUBLISHED ] ) || Chatbot::is_default_published() ) {
            // Hooks
            add_action( 'wp_footer', array( $this, 'add_chatbot_element_to_content' ) );
            add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_chatbots_assets' ), PHP_INT_MAX );
            // General hooks
            $this->init_general_chatbot_hooks();
        }
    }

	/**
	 * Initialize general chatbot hooks (headers, emoji disabling, etc.)
	 * Only runs once even if called multiple times.
	 *
	 * @since 1.0.0
	 * @return void
	 */
    private function init_general_chatbot_hooks() {
        // Only initialize once
        if ( self::$general_hooks_initialized ) {
            return;
        }

        // Add chatbot-related headers
        add_action( 'wp_head', array( $this, 'add_chatbot_related_headers' ) );

        // Add icons utilities
        add_action( 'wp_footer', array( $this, 'add_icons_utilities_to_content' ) );

        // Disable the emoji CDN to not have conflicts
        add_filter( 'emoji_svg_url', '__return_false' );

        // Disable the scripts to solve the emoji problem
        remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); // JS
        remove_action( 'wp_print_styles', 'print_emoji_styles' ); // CSS

        // Mark as initialized
        self::$general_hooks_initialized = true;
    }

	/**
	 * Output chatbot-related meta tags in the page head.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function add_chatbot_related_headers() {
        // Viewport
		?>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
		<?php
	}

	/**
	 * Output the chatbot container element in the footer.
	 *
	 * For logged-in users, the nonce is rendered inline as a data attribute.
	 * This is safe because WordPress doesn't cache pages for logged-in users.
	 *
	 * For non-logged-in users, no nonce is rendered. The frontend JavaScript
	 * will fetch a fresh nonce via the public API endpoint to avoid cache issues.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function add_chatbot_element_to_content() {
		// Check if user is logged in
		// For logged-in users, render the nonce inline to avoid an extra API call
		// WordPress doesn't cache pages for logged-in users, so this is safe
		if ( is_user_logged_in() ) {
			$session_manager = Session_Manager::instance();
			$nonce           = $session_manager->get_nonce();
			$expires         = $session_manager->get_nonce_expiration();
			?>
            <div id="lbaic-chatbot"
                 data-nonce="<?php echo esc_attr( $nonce ); ?>"
                 data-nonce-expires="<?php echo esc_attr( $expires ); ?>">
            </div>
			<?php
		} else {
			// For non-logged-in users, render without nonce
			// The frontend will fetch it via API to avoid cache issues
			?>
            <div id="lbaic-chatbot"></div>
			<?php
		}
	}

	/**
	 * Output the icons utilities SVG in the footer.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function add_icons_utilities_to_content() {
		$plugin_dir_path = Limb_Chatbot()->get_plugin_dir_path();

		include_once $plugin_dir_path . 'templates/chatbot/lbaic-chatbot-icons.php';
	}

    /**
     * Localize chatbots required data
     *
     * Note: The nonce is NOT localized here to avoid caching issues.
     * Instead, it's handled dynamically:
     * - For logged-in users: rendered inline in the chatbot element
     * - For guests: fetched via API on page load
     *
     * @param string $handle Script handler
     *
     * @since 1.0.0
     * @return void
     */
    public function localize_chatbots_object( $handle ) {
        if ( ! self::$chatbots_object_localized ) {
            wp_localize_script( $handle, 'LimbChatbot', array(
                'rest'    => array(
                    'url'   => get_rest_url() . 'limb/chatbot/v1/',
                ),
                'version' => Limb_Chatbot()->get_version(),
                'pageContext' => Page_Context::instance()->get_context()
            ) );
            // Localized
            self::$chatbots_object_localized = true;
        }
    }

    /**
     * Enqueue chatbots related styles
     *
     * @since 1.0.0
     * @return void
     */
    public function enqueue_chatbots_styles() {
        $plugin_dir_url = Limb_Chatbot()->get_plugin_dir_url();
        $handle = 'lbaic-chatbot';

        if ( ! wp_style_is( $handle, 'registered' ) ) {
            wp_register_style( $handle, $plugin_dir_url . 'dist/css/chatbot/lbaic-chatbot.css', array(), Limb_Chatbot()->get_version() );
        }
        if ( ! wp_style_is( $handle, 'enqueued' ) ) {
            wp_enqueue_style( $handle );
        }
    }

	/**
	 * Enqueue chatbot frontend scripts and styles.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function enqueue_chatbots_assets() {
		$plugin_dir_path    = Limb_Chatbot()->get_plugin_dir_path();
		$plugin_dir_url     = Limb_Chatbot()->get_plugin_dir_url();
		$plugin_version     = Limb_Chatbot()->get_version();
		$hooks_script_asset = include( $plugin_dir_path . 'dist/js/public/lbaic-chatbot.asset.php' );
		// Script
        $handle = 'lbaic-chatbot';
		wp_register_script(
			$handle,
			$plugin_dir_url . 'dist/js/public/lbaic-chatbot.js',
			$hooks_script_asset['dependencies'],
            $plugin_version,
			array(
				'strategy'  => 'defer',
				'in_footer' => true,
			)
		);
        wp_enqueue_script( $handle );
        // Localize
        $this->localize_chatbots_object( $handle );
        // Style
        $this->enqueue_chatbots_styles();
	}
}
