<?php
/**
 * Shois Chat Button — Main Plugin Class
 *
 * Orchestrates all plugin functionality, loads required files,
 * and registers WordPress hooks.
 *
 * @package ShoisChatButton
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class SHCB_Plugin
 *
 * Singleton main plugin orchestrator.
 */
class SHCB_Plugin {

	/**
	 * Singleton instance.
	 *
	 * @var SHCB_Plugin|null
	 */
	private static $instance = null;

	/**
	 * Get the singleton instance.
	 *
	 * @return SHCB_Plugin
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor. Sets up all hooks and loads dependencies.
	 */
	private function __construct() {
		$this->check_upgrade();
		$this->init_hooks();
		$this->load_dependencies();
	}

	/**
	 * Check if a schema upgrade is needed.
	 *
	 * @return void
	 */
	private function check_upgrade() {
		SHCB_Activator::maybe_upgrade();
	}

	/**
	 * Register WordPress hooks.
	 *
	 * @return void
	 */
	private function init_hooks() {
		// Activation redirect.
		add_action( 'admin_init', array( $this, 'maybe_redirect_on_activation' ) );
	}

	/**
	 * Load plugin dependencies based on context.
	 *
	 * @return void
	 */
	private function load_dependencies() {
		// Always: CPT and REST API.
		SHCB_Template_CPT::init();
		SHCB_Rest_API::init();

		if ( is_admin() ) {
			$this->load_admin();
		}

		if ( ! is_admin() || wp_doing_ajax() ) {
			$this->load_frontend();
		}
	}

	/**
	 * Load admin-specific functionality.
	 *
	 * @return void
	 */
	private function load_admin() {
		require_once SHCB_PLUGIN_DIR . 'admin/admin.php';
	}

	/**
	 * Load frontend-specific functionality.
	 *
	 * @return void
	 */
	private function load_frontend() {
		SHCB_Widget_Renderer::init();
	}

	/**
	 * Redirect to plugin dashboard after first activation.
	 *
	 * @return void
	 */
	public function maybe_redirect_on_activation() {
		if ( ! get_transient( 'shcb_activation_redirect' ) ) {
			return;
		}

		delete_transient( 'shcb_activation_redirect' );

		// Don't redirect on multi-activate or network activate.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only checking existence of 'activate-multi' flag, not processing form data.
		if ( wp_doing_ajax() || is_network_admin() || isset( $_GET['activate-multi'] ) ) {
			return;
		}

		wp_safe_redirect(
			admin_url( 'admin.php?page=shois-chat-button' )
		);
		exit;
	}
}
