<?php

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

require_once ICOMM_SM_PLUGIN_DIR . 'includes/class-icomm-sm-features.php';
require_once ICOMM_SM_PLUGIN_DIR . 'includes/class-icomm-sm-settings.php';
require_once ICOMM_SM_PLUGIN_DIR . 'includes/class-icomm-sm-dates.php';
require_once ICOMM_SM_PLUGIN_DIR . 'includes/class-icomm-sm-db.php';
require_once ICOMM_SM_PLUGIN_DIR . 'includes/class-icomm-sm-remote.php';
require_once ICOMM_SM_PLUGIN_DIR . 'includes/class-icomm-sm-cron.php';
require_once ICOMM_SM_PLUGIN_DIR . 'includes/class-icomm-sm-alerts.php';
require_once ICOMM_SM_PLUGIN_DIR . 'includes/class-icomm-sm-recommendations.php';
require_once ICOMM_SM_PLUGIN_DIR . 'includes/class-icomm-sm-niche-research.php';
require_once ICOMM_SM_PLUGIN_DIR . 'includes/class-icomm-sm-updater.php';
require_once ICOMM_SM_PLUGIN_DIR . 'modules/client/class-sm-client-mailer.php';
require_once ICOMM_SM_PLUGIN_DIR . 'includes/class-icomm-sm-pdf.php';
require_once ICOMM_SM_PLUGIN_DIR . 'admin/class-icomm-sm-admin.php';

final class IComm_Metrix {

	private static ?IComm_Metrix $instance = null;

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

	private function __construct() {}

	public function init(): void {
		if (get_option('icomm_sm_installed_at', '') === '') {
			add_option('icomm_sm_installed_at', current_time('timestamp'), '', false);
		}
		IComm_SM_DB::maybe_upgrade();
		IComm_SM_Remote::ensure_link_token();

		IComm_SM_License::init();
		IComm_SM_License::schedule_if_needed();
		IComm_SM_Cron::init();
		IComm_SM_Cron::schedule_if_needed();
		IComm_SM_Alerts::init();
		IComm_SM_Updater::init();

		if (is_admin()) {
			IComm_SM_Admin::init();
		}
	}

	public static function activate(): void {
		try {
			IComm_SM_DB::install();
		} catch (Throwable $e) {
			if (defined('WP_DEBUG') && WP_DEBUG && function_exists('error_log')) {
				error_log('icomm-metrix activate DB install failed: ' . $e->getMessage());
			}
		}
		if (get_option('icomm_sm_installed_at', '') === '') {
			add_option('icomm_sm_installed_at', current_time('timestamp'), '', false);
		}
		IComm_SM_Remote::ensure_link_token();
		IComm_SM_License::schedule_if_needed();
		IComm_SM_Cron::schedule_if_needed();
		flush_rewrite_rules();
	}

	public static function deactivate(): void {
		IComm_SM_License::unschedule();
		IComm_SM_Cron::unschedule();
	}
}
