<?php
/**
 * PostGate Core Class
 *
 * This file contains the main core class that handles plugin initialization,
 * dependency loading, and class instantiation. Serves as the central bootstrap
 * point for all PostGate functionality, ensuring proper load order and
 * component initialization.
 *
 * @package PostGate
 * @subpackage Core
 * @since 1.0.0
 * @author QodeSphere
 * @license GPL-2.0+
 */

defined( 'ABSPATH' ) || exit;

/**
 * PostGate Core Class
 *
 * Main initializer and bootstrap class for the PostGate plugin. This class is responsible
 * for orchestrating the complete plugin initialization process with the following features:
 *
 * - Sequential dependency loading in correct order
 * - Component initialization following dependency hierarchy
 * - Static initialization pattern for all plugin classes
 * - Centralized loading point for maintainability
 * - Organized component grouping (core, access, Stripe, admin, data, API, bridge, blocks)
 *
 * Component Organization:
 * 1. Core Utility Classes: Price utils, templates, assets, fees
 * 2. Access & Content Management: Access control, content locking, redirects, login
 * 3. Stripe Integration: API operations, payments, redirects, webhooks
 * 4. Admin Interface: Admin pages, settings, meta boxes
 * 5. Data Management: Orders repository and database access
 * 6. REST API: Orders and dashboard endpoints
 * 7. Bridge Integration: Stripe Connect OAuth flow
 * 8. Blocks: Gutenberg lock block
 *
 * Initialization Pattern:
 * Each component follows the static init() pattern, registering WordPress hooks
 * and setting up functionality without instantiation. This provides:
 * - Consistent initialization interface across all classes
 * - No need for dependency injection or global state
 * - Easy testing and component isolation
 * - Memory efficiency through static methods
 *
 * Load Order:
 * Dependencies are loaded before dependents to ensure class availability.
 * For example, Product_Utils is loaded before Access_Manager which depends on it.
 *
 * This class follows a singleton-like pattern where it loads all dependencies
 * once and initializes all plugin components in the correct order during the
 * plugin's bootstrap phase.
 *
 * @since 1.0.0
 */
class PostGate_Core {

	/**
	 * Initialize the PostGate plugin.
	 *
	 * This is the main entry point for the entire plugin. It executes a two-phase
	 * initialization process:
	 * 1. Load Dependencies: Includes all required PHP class files
	 * 2. Initialize Classes: Calls init() on all components to register hooks
	 *
	 * This method is called once from the main plugin file (postgate.php) during
	 * the WordPress plugin loading phase. It ensures all components are loaded
	 * and initialized in the correct order before WordPress starts processing
	 * requests.
	 *
	 * The two-phase approach ensures:
	 * - All classes are available before any init() methods are called
	 * - Components can safely reference other components
	 * - Hooks are registered in proper order
	 * - No race conditions between component initialization
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return void
	 */
	public static function init(): void {
		self::load_dependencies();
		self::init_classes();

		// Register activation redirect handler
		add_action( 'admin_init', [ 'PostGate_Installation', 'maybe_redirect_after_activation' ] );
	}

	/**
	 * Load all required PHP files for the plugin's functionality.
	 *
	 * Includes all class files in dependency order, organized by functional area.
	 * Files are loaded sequentially to ensure that dependent classes are available
	 * when needed by other components.
	 *
	 * Component Groups:
	 *
	 * Helper Classes:
	 * - Icons: SVG icon management and base64 encoding for admin menu
	 * - Product_Utils: Product data fetching and formatting
	 *
	 * Core Utility Classes:
	 * - Template_Renderer: Gate template loading and rendering
	 * - Assets_Loader: CSS/JS asset enqueueing
	 * - Fee_Manager: Platform fee calculation and validation
	 *
	 * Access & Content Management:
	 * - Product_Content_Resolver: Maps products to accessible content
	 * - Access_Manager: User access validation and grants
	 * - Content_Lock: Content filtering and gate rendering
	 * - Access_Redirect_Handler: Post-purchase redirect management
	 * - Login_Handler: Login redirects with purchase intent
	 *
	 * Stripe Integration:
	 * - Stripe_API: Stripe API operations (products, prices, currency formatting)
	 * - Stripe_Payment: REST endpoints for checkout initiation
	 * - Stripe_Redirector: Stripe Checkout session creation
	 * - Stripe_Webhooks: Webhook event processing
	 *
	 * Admin & Settings:
	 * - Admin: Admin menu and page structure
	 * - Settings: Plugin settings and REST endpoints
	 * - Post_Meta: Post-level meta boxes
	 * - Term_Meta: Term-level meta boxes
	 *
	 * Data Management:
	 * - Orders_Repo: Database access for orders table
	 *
	 * REST API:
	 * - Orders_Controller: Order management endpoints
	 * - Dashboard_Controller: Dashboard data endpoints
	 *
	 * Bridge Integration:
	 * - Bridge_Config: Bridge server configuration
	 * - Bridge_Signer: Request signing for bridge communication
	 * - Bridge_Connect: Stripe Connect OAuth flow
	 * - Merchant_Auth: Credential management
	 *
	 * Blocks:
	 * - Lock_Block: Gutenberg block for content-level locks
	 *
	 * All files are loaded regardless of admin/frontend context to ensure
	 * REST API and AJAX endpoints work correctly in both contexts.
	 *
	 * @since 1.0.0
	 * @access private
	 *
	 * @return void
	 */
	private static function load_dependencies(): void {
		// Helper classes
		require_once POSTGATE_PATH . '/includes/helpers/class-icons.php';
		require_once POSTGATE_PATH . '/includes/helpers/class-product-utils.php';
		require_once POSTGATE_PATH . '/includes/helpers/class-template-utils.php';

		// Core utility classes
		require_once POSTGATE_PATH . '/includes/class-logger.php';
		require_once POSTGATE_PATH . '/includes/core/class-template-renderer.php';
		require_once POSTGATE_PATH . '/includes/core/class-assets-loader.php';
		require_once POSTGATE_PATH . '/includes/core/class-fee-manager.php';

		// Access and content management
		require_once POSTGATE_PATH . '/includes/access/class-product-content-resolver.php';
		require_once POSTGATE_PATH . '/includes/access/class-access-manager.php';
		require_once POSTGATE_PATH . '/includes/access/class-content-lock.php';
		require_once POSTGATE_PATH . '/includes/access/class-access-redirect-handler.php';
		require_once POSTGATE_PATH . '/includes/access/class-login-handler.php';

		// Stripe integration
		require_once POSTGATE_PATH . '/includes/stripe/class-stripe-api.php';
		require_once POSTGATE_PATH . '/includes/stripe/class-stripe-payment.php';
		require_once POSTGATE_PATH . '/includes/stripe/class-stripe-redirector.php';
		require_once POSTGATE_PATH . '/includes/stripe/class-stripe-webhooks.php';
		require_once POSTGATE_PATH . '/includes/stripe/class-stripe-return-handler.php';

		// Admin and settings
		require_once POSTGATE_PATH . '/includes/admin/class-admin.php';
		require_once POSTGATE_PATH . '/includes/admin/class-settings.php';
		require_once POSTGATE_PATH . '/includes/admin/class-post-meta.php';
		require_once POSTGATE_PATH . '/includes/admin/class-term-meta.php';
		require_once POSTGATE_PATH . '/includes/admin/class-email-notification.php';

		// Data management
		require_once POSTGATE_PATH . '/includes/data/class-orders-repo.php';

		// REST API endpoints
		require_once POSTGATE_PATH . '/includes/api/class-orders-controller.php';
		require_once POSTGATE_PATH . '/includes/api/class-dashboard-controller.php';

		// Bridge-related classes for Stripe Connect OAuth
		require_once POSTGATE_PATH . '/includes/bridge/class-bridge-config.php';
		require_once POSTGATE_PATH . '/includes/bridge/class-bridge-signer.php';
		require_once POSTGATE_PATH . '/includes/bridge/class-bridge-connect.php';
		require_once POSTGATE_PATH . '/includes/bridge/class-merchant-auth.php';

		// Blocks
		require_once POSTGATE_PATH . '/includes/blocks/class-lock-block.php';
	}

	/**
	 * Initialize all plugin classes using their static init() methods.
	 *
	 * Calls the static init() method on each component class to register WordPress
	 * hooks and set up functionality. Classes are initialized in a specific order
	 * to ensure that dependent components are initialized after their dependencies.
	 *
	 * Initialization Order:
	 *
	 * 1. Core Functionality:
	 *    - Assets_Loader: Must run early to register asset hooks
	 *    - Product_Content_Resolver: Required by Access_Manager
	 *    - Access_Manager: Core access validation, used by many components
	 *
	 * 2. Content & Access Control:
	 *    - Content_Lock: Filters content based on access
	 *    - Access_Redirect_Handler: Handles post-purchase redirects
	 *    - Login_Handler: Manages login flow with purchase intent
	 *
	 * 3. Stripe & Payments:
	 *    - Stripe_Payment: REST endpoints for checkout
	 *    - Stripe_Webhooks: Webhook processing (depends on Orders_Repo)
	 *    - Bridge_Connect: OAuth flow for Stripe Connect
	 *
	 * 4. Admin Interface:
	 *    - Admin: Menu structure
	 *    - Settings: Settings registration and REST endpoints
	 *    - Post_Meta: Post edit screen meta boxes
	 *    - Term_Meta: Term edit screen meta boxes
	 *    - Lock_Block: Gutenberg block registration
	 *
	 * 5. REST API:
	 *    - Orders_Controller: Order management endpoints
	 *    - Dashboard_Controller: Analytics and metrics endpoints
	 *
	 * Each init() method typically:
	 * - Registers WordPress action/filter hooks
	 * - Sets up REST API endpoints
	 * - Registers meta boxes or blocks
	 * - Does NOT perform immediate operations (hooks only)
	 *
	 * This approach allows WordPress to control execution timing while ensuring
	 * all components are properly registered before the request is processed.
	 *
	 * @since 1.0.0
	 * @access private
	 *
	 * @return void
	 */
	private static function init_classes(): void {
		// Core functionality classes
		PostGate_Assets_Loader::init();
		PostGate_Product_Content_Resolver::init();
		PostGate_Access_Manager::init();

		// Content and access control
		PostGate_Content_Lock::init();
		PostGate_Access_Redirect_Handler::init();
		PostGate_Login_Handler::init();

		// Stripe integration and payments
		PostGate_Stripe_Payment::init();
		PostGate_Stripe_Webhooks::init();
		PostGate_Stripe_Return_Handler::init();
		PostGate_Bridge_Connect::init();

		// Admin interface and settings
		PostGate_Admin::init();
		PostGate_Settings::init();
		PostGate_Post_Meta::init();
		PostGate_Term_Meta::init();
		PostGate_Lock_Block::init();

		// REST API endpoints
		PostGate_Orders_Controller::init();
		PostGate_Dashboard_Controller::init();
	}
}

