<?php
/**
 * Main plugin bootstrap singleton.
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k;

defined( 'ABSPATH' ) || exit;

final class Plugin {

	private static ?Plugin $instance = null;

	private bool $booted = false;

	public static function instance(): Plugin {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {}

	public function boot(): void {
		if ( $this->booted ) {
			return;
		}
		$this->booted = true;

		$this->load_textdomain();
		$this->run_install_check();

		Security\Capabilities::register();
		Security\Capabilities::add_to_administrators();
		Security\Headers::register();

		Compat\WooCommerce_Check::register();

		Admin\Admin_Menu::register();
		Admin\Plugin_List::register();
		Admin\Assets::register();
		Admin\View_Inline_Assets::register();

		Modules\Settings\Settings_Manager::register();
		Modules\Backup\Backup_Manager::register();
		Modules\Subscribers\Subscriber_Manager::register();
		Modules\Subscribers\Unsubscribe_Handler::register();
		Modules\Coupons\Coupon_Manager::register();
		Modules\Coupons\Coupon_Email_Template_Manager::register();
		Modules\Coupons\Coupon_Scheduler::register();
		Modules\Coupons\Coupon_Display::register();
		Modules\Newsletter\Newsletter_Manager::register();
		Modules\Newsletter\Newsletter_Sender::register();
		Modules\Newsletter\Newsletter_Form::register();
		Modules\Cart_Recovery\Cart_Tracker::register();
		Modules\Cart_Recovery\Cart_Recovery_Manager::register();
		Modules\Cart_Recovery\Cart_Recovery_Cron::register();
		Modules\Statistics\Stats_Collector::register();
		Modules\Statistics\Stats_Aggregator::register();
		Modules\Dashboard\Dashboard_Manager::register();

		Email\Mailer::register();
		Email\Smtp::register();

		Tracking\Pixel::register();
		Tracking\Redirector::register();

		Frontend\Frontend::register();
		Frontend\Shortcodes::register();

		Rest\Rest_Router::register();

		/**
		 * Fires after SuiteMkt3k has finished booting all modules.
		 *
		 * @since 1.0.0
		 */
		do_action( 'suitemkt3k/booted' );
	}

	private function load_textdomain(): void {
		Utils\I18n::load_textdomain();
	}

	private function run_install_check(): void {
		$installed_version = get_option( 'suitemkt3k_db_version' );
		$needs_install     = $installed_version !== SUITEMKT3K_DB_VERSION || ! $this->core_tables_exist();
		if ( $needs_install ) {
			Installer::install();
			update_option( 'suitemkt3k_db_version', SUITEMKT3K_DB_VERSION, false );
		}

		// One-time data fixes (no schema change). Safe on Plugins → Update.
		Modules\Cart_Recovery\Cart_Recovery_Manager::maybe_fix_false_recoveries();
	}

	private function core_tables_exist(): bool {
		global $wpdb;
		$table = $wpdb->prefix . 'wmk_coupons';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		return $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table;
	}

}
