<?php

namespace Limb_Chatbot\Includes\Api;

use Limb_Chatbot\Includes\Api\V1\Controllers\Rest_Controller;
use Limb_Chatbot\Includes\Services\Chatbot_Parameter_Manager;
use WP_REST_Request;
use WP_REST_Server;


/**
 * Singleton Server class to initialize and register REST API controllers.
 *
 * Handles REST API routes registration and suppresses debug output for JSON responses.
 *
 * @since 1.0.0
 */
class Server {

	/**
	 * The single instance of the class.
	 *
	 * @var self|null
	 * @since 1.0.0
	 */
	private static $_instance = null;

	/**
	 * Array of controller instances.
	 *
	 * @var Rest_Controller[]
	 * @since 1.0.0
	 */
	protected $controllers = [];

	/**
	 * Get the singleton instance of Server.
	 *
	 * @return self Instance of Server.
	 * @since 1.0.0
	 */
	public static function get_instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}

		return self::$_instance;
	}

	/**
	 * Initialize the server: add necessary hooks.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function init() {
		add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) );
		add_filter( 'rest_pre_dispatch', array($this, 'inject_flag_params'), 10, 3 );

		// Initialize the parameter manager for handling parameter-related services
		Chatbot_Parameter_Manager::instance()->boot();
	}

	/**
	 * Register REST API routes from all controllers.
	 *
	 * Instantiates each controller class and calls its register_routes() method.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function register_rest_routes() {
		foreach ( $this->get_controllers() as $key => $controller ) {
			$this->controllers[ $key ] = new $controller;
			$this->controllers[ $key ]->register_routes();
		}
	}

	/**
	 * Inject from_admin and current_tab flags to requests, to understand from where the request came from
	 *
	 * @param  mixed  $result  Response to replace the requested version with. Can be anything
	 *                                 a normal endpoint can return, or null to not hijack the request.
	 * @param  WP_REST_Server  $server  Server instance.
	 * @param  WP_REST_Request  $request  Request used to generate the response.
	 *
	 * @return mixed
	 */
	public function inject_flag_params( $result, $server, $request ) {
		if ( ! str_contains( $request->get_route(), 'limb/chatbot/v1' ) ) {
			return $result;
		}
		$from_admin  = false;
		$current_tab = '';

		$referer = ! empty( $_SERVER['HTTP_REFERER'] ) ? sanitize_url( $_SERVER['HTTP_REFERER'] ) : null;

		if ( current_user_can( 'manage_options' ) && ! empty( $referer ) ) {
			$parsed_path = wp_parse_url( $referer, PHP_URL_PATH );
			// 1. Check where the request came from
			if ( strpos( $parsed_path, '/wp-admin' ) !== false ) {
				$from_admin = true;
			}
			// 2. Inject the tab info
			$parsed_query = wp_parse_url( $referer, PHP_URL_QUERY );
			wp_parse_str( $parsed_query, $query_params );
			if ( $from_admin && ! empty( $query_params['tab'] ) ) {
				$current_tab = sanitize_text_field( $query_params['tab'] );
			}
		}

		$request->set_param( '_from_admin', $from_admin );
		$request->set_param( '_current_tab', $current_tab );

		return $result;
	}

	/**
	 * Get list of REST API controller class names.
	 *
	 * Can be filtered or extended if needed.
	 *
	 * @return string[] Array of controller class names keyed by route slug.
	 * @since 1.0.0
	 * @since 1.0.11 Added Telegram controller.
	 */
	public function get_controllers() {
		// Filtering could be applied here
		return [
			'configs'             => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Configs_Controller',
			'chats'               => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Chats_Controller',
			'chatbot_metas'       => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Chatbot_Metas_Controller',
			'chat_messages'       => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Chat_Messages_Controller',
			'vectors'             => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Vectors_Controller',
			'vector_indexes'      => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Vector_Indexes_Controller',
			'vector_index_metas'  => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Vector_Index_Metas_Controller',
			'settings'            => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Settings_Controller',
			'datasets'            => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Datasets_Controller',
			'dataset_entries'     => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Dataset_Entries_Controller',
			'dataset_metas'       => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Dataset_Metas_Controller',
			'models'              => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\AI_Models_Controller',
			'chatbots'            => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Chatbots_Controller',
			'chatbot_users'       => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Chatbot_Users_Controller',
			'model_metas'         => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\AI_Model_Metas_Controller',
			'files'               => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Files_Controller',
			'chat_metas'          => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Chat_Metas_Controller',
			'plugin'              => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Plugin_Controller',
			'post_types'          => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Post_Types_Controller',
			'actions'             => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Actions_Controller',
			'parameters'          => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Parameters_Controller',
			'action_callbacks'    => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Action_Callbacks_Controller',
			'action_submissions'  => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Action_Submissions_Controller',
			'slack'               => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Integrations\\Slack_Controller',
			'telegram'            => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Integrations\\Telegram_Controller',
			'live_agent_messages' => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Live_Agent_Messages_Controller',
			'leads'               => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Leads_Controller',
			'lead_fields'         => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Lead_Fields_Controller',
			'jobs'                => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Jobs_Controller',
			'widgets'             => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Widgets_Controller',
			'chatbot_analytics'   => 'Limb_Chatbot\\Includes\\Api\\V1\\Controllers\\Chatbot_Analytics_Controller',
		];
	}
}