<?php
/**
 * Core bootstrap class for Solomon Schema
 *
 * Initializes the plugin, loads dependencies, and registers hooks.
 *
 * @package BW_Schema
 * @since 3.0.0-babel
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class BW_Schema_Core {

	/**
	 * Instance of this class
	 *
	 * @var BW_Schema_Core
	 */
	private static $instance = null;

	/**
	 * Get instance of this class (singleton)
	 *
	 * @return BW_Schema_Core
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor
	 */
	private function __construct() {
		$this->init_hooks();
		$this->load_dependencies();
	}

	/**
	 * Initialize WordPress hooks
	 *
	 * @return void
	 */
	private function init_hooks() {
		// Frontend hooks
		add_action( 'wp_head', array( $this, 'output_schema_markup' ), 1 );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_scripts' ) );

		// Admin initialization - call directly since we're in plugins_loaded
		// (registering on plugins_loaded again won't fire since we're already in that action)
		$this->init_admin();

		// Third-party compatibility (e.g. suppress Yoast's duplicate schema graph)
		BW_Schema_Compat::init();

		// Per-post metabox (registers on add_meta_boxes / save_post)
		BW_Schema_Metabox::init();
	}

	/**
	 * Load plugin dependencies
	 *
	 * Includes service classes via autoloader.
	 *
	 * @return void
	 */
	private function load_dependencies() {
		// Services are auto-loaded via the spl_autoload_register in main plugin file
		// They will load on demand when referenced
	}

	/**
	 * Output schema markup on frontend
	 *
	 * Called early in wp_head to output JSON-LD schema before other content.
	 *
	 * @return void
	 */
	public function output_schema_markup() {
		// Only output on frontend
		if ( is_admin() || is_feed() ) {
			return;
		}

		// Output cached or generated schema.org JSON-LD markup
		try {
			$schema = BW_Schema_Cache::get_schema();
			if ( ! empty( $schema ) ) {
				?>
				<!-- Solomon Schema markup -->
				<script type="application/ld+json">
				<?php echo wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				</script>
				<?php
			}
		} catch ( Throwable $e ) {
			// Silently fail - schema output is not critical
			return;
		}
	}

	/**
	 * Enqueue frontend scripts and styles
	 *
	 * @return void
	 */
	public function enqueue_frontend_scripts() {
		// Stub: No frontend dependencies yet
	}

	/**
	 * Initialize admin interface
	 *
	 * Loads service classes and sets up admin pages.
	 * Called from init_hooks() to run during plugins_loaded.
	 *
	 * @return void
	 */
	public function init_admin() {
		// Always preload services (they're needed in admin, frontend, and WP-CLI contexts)
		$this->preload_services();

		// Preload form builder classes (needed for all admin forms)
		$this->preload_form_builder();

		// Only load admin UI if we're actually in the admin
		if ( ! is_admin() ) {
			return;
		}

		// Load admin class
		require_once BW_SCHEMA_PLUGIN_DIR . 'admin/class-admin.php';

		// Initialize admin system
		new BW_Schema_Admin();
	}

	/**
	 * Preload form builder classes
	 *
	 * Explicitly load form classes so they're available when admin pages render forms.
	 *
	 * @return void
	 */
	private function preload_form_builder() {
		$form_files = array(
			'class-form-fields.php',
			'class-form-validator.php',
			'class-form-builder.php',
		);

		foreach ( $form_files as $file ) {
			$path = BW_SCHEMA_PLUGIN_DIR . 'includes/' . $file;
			if ( file_exists( $path ) ) {
				require_once $path;
			}
		}
	}

	/**
	 * Preload service classes for admin
	 *
	 * Explicitly load service classes so they're available when admin pages render.
	 *
	 * @return void
	 */
	private function preload_services() {
		// Admin services
		$service_files = array(
			'class-service-organization.php',
			'class-service-locations.php',
			'class-service-people.php',
			'class-service-survey.php',
			'class-service-cache.php',
			'class-service-health.php',
			'class-service-conflicts.php',
			'class-service-content.php',
		);

		foreach ( $service_files as $file ) {
			$path = BW_SCHEMA_PLUGIN_DIR . 'admin/services/' . $file;
			if ( file_exists( $path ) ) {
				require_once $path;
			}
		}

		// Phase 5: Advanced schema services
		$phase5_files = array(
			'class-location.php',
			'class-rating.php',
			'class-contact.php',
			'class-media.php',
			'class-hours.php',
		);

		foreach ( $phase5_files as $file ) {
			$path = BW_SCHEMA_PLUGIN_DIR . 'includes/' . $file;
			if ( file_exists( $path ) ) {
				require_once $path;
			}
		}

		// Phase 6: Advanced features
		$phase6_files = array(
			'class-faq.php',
			'class-review.php',
			'class-webpage.php',
		);

		foreach ( $phase6_files as $file ) {
			$path = BW_SCHEMA_PLUGIN_DIR . 'includes/' . $file;
			if ( file_exists( $path ) ) {
				require_once $path;
			}
		}

		// Schema generator and cache
		$core_files = array(
			'class-generator.php',
			'class-cache.php',
		);

		foreach ( $core_files as $file ) {
			$path = BW_SCHEMA_PLUGIN_DIR . 'includes/' . $file;
			if ( file_exists( $path ) ) {
				require_once $path;
			}
		}
	}

	/**
	 * Plugin activation hook
	 *
	 * @return void
	 */
	public static function activate() {
		// First admin page load after activation redirects to the setup wizard
		// (skipped automatically if setup was already completed)
		set_transient( 'bw_schema_activation_redirect', 1, 60 );
	}

	/**
	 * Plugin deactivation hook
	 *
	 * @return void
	 */
	public static function deactivate() {
		// Clean up transients, clear caches
		if ( class_exists( 'BW_Schema_Service_Cache' ) ) {
			BW_Schema_Service_Cache::clear_all();
		}
	}
}

/**
 * Activation function (called by register_activation_hook)
 *
 * @return void
 */
function bw_schema_activate() {
	BW_Schema_Core::activate();
}

/**
 * Deactivation function (called by register_deactivation_hook)
 *
 * @return void
 */
function bw_schema_deactivate() {
	BW_Schema_Core::deactivate();
}

/**
 * Uninstall function (called by register_uninstall_hook)
 *
 * @return void
 */
function bw_schema_uninstall() {
	// TODO: Clean up all options, post meta, custom tables
}
