<?php

declare( strict_types=1 );

namespace StrykeWP\Modules\Connector;

use StrykeWP\Modules\AbstractModule;

/**
 * STRYKE Hub Connector Module.
 *
 * Provides secure REST API endpoints for remote WordPress management
 * via the STRYKE Hub dashboard.
 *
 * Migrated from stryke-connector v1.0.0.
 * DB table wp_stryke_logs and option names preserved for backward compatibility.
 *
 * @package StrykeWP\Modules\Connector
 */
class ConnectorModule extends AbstractModule {

	// -----------------------------------------------------------------------
	// Module services (instantiated in boot_module)
	// -----------------------------------------------------------------------

	private Auth           $auth;
	private ApiLogger      $api_logger;
	private ApiManager     $api_manager;
	private ContentManager $content_manager;
	private AutoLogin      $auto_login;
	private Api            $api;
	private ConnectorAdmin $admin;

	// -----------------------------------------------------------------------
	// ModuleInterface metadata
	// -----------------------------------------------------------------------

	public function get_id(): string {
		return 'connector';
	}

	public function get_name(): string {
		return __( 'Hub Connector', 'stryke-wp' );
	}

	public function get_description(): string {
		return __( 'Sicherer REST-API-Endpunkt für das STRYKE Hub Dashboard — Remote-Monitoring, Plugin-Management und System-Health in Echtzeit.', 'stryke-wp' );
	}

	public function get_version(): string {
		return STRYKE_WP_VERSION;
	}

	public function get_icon(): string {
		return 'dashicons-admin-network';
	}

	// -----------------------------------------------------------------------
	// Boot
	// -----------------------------------------------------------------------

	/**
	 * Instantiates all Connector services and registers WordPress hooks.
	 * Called only when the module is enabled.
	 *
	 * @return void
	 */
	protected function boot_module(): void {

		// Build the DI container.
		$this->auth            = new Auth();
		$this->api_logger      = new ApiLogger();
		$this->api_manager     = new ApiManager();
		$this->content_manager = new ContentManager();
		$this->auto_login      = new AutoLogin();
		$this->api             = new Api( $this->auth, $this->api_logger, $this->api_manager, $this->content_manager, $this->auto_login );
		$this->admin           = new ConnectorAdmin( $this->auth );

		// REST API routes — fires on every request type (not just admin).
		add_action( 'rest_api_init', array( $this->api, 'register_routes' ) );

		// Auto-login token redemption — must fire early on every front-end request.
		add_action( 'init', array( $this->auto_login, 'maybe_process_autologin' ), 1 );

		// Audit logging — must run on all requests including REST.
		add_filter(
			'rest_post_dispatch',
			array( $this->api_logger, 'log_rest_request' ),
			99,
			3
		);

		// Daily log pruning cron callback — must be registered on every request.
		add_action( ApiLogger::CRON_HOOK, array( $this->api_logger, 'prune_logs' ) );

		// Admin-only hooks.
		if ( is_admin() ) {
			$this->admin->register_hooks();
		}

		$this->logger->info( 'ConnectorModule booted.' );
	}

	// -----------------------------------------------------------------------
	// Lifecycle
	// -----------------------------------------------------------------------

	/**
	 * Runs when the module is first enabled via the dashboard toggle.
	 * Creates the audit log DB table and schedules the daily pruning cron.
	 *
	 * @return void
	 */
	public function on_enable(): void {
		ApiLogger::create_table();

		if ( ! wp_next_scheduled( ApiLogger::CRON_HOOK ) ) {
			wp_schedule_event( time(), 'daily', ApiLogger::CRON_HOOK );
		}
	}

	/**
	 * Runs when the module is disabled via the dashboard toggle.
	 * Clears the scheduled cron job and the one-time key transient.
	 *
	 * @return void
	 */
	public function on_disable(): void {
		wp_clear_scheduled_hook( ApiLogger::CRON_HOOK );
		delete_transient( Auth::TRANSIENT_RAW_KEY );
	}

	// -----------------------------------------------------------------------
	// Settings UI
	// -----------------------------------------------------------------------

	/**
	 * Renders the Hub Connector settings page inside the STRYKE WP dashboard.
	 *
	 * @return void
	 */
	public function render_settings(): void {
		// Admin object may not be instantiated if called outside boot context.
		if ( isset( $this->admin ) ) {
			$this->admin->render_settings();
		}
	}
}
