<?php
/**
 * The plugin activation class.
 *
 * @package Storeplugin\PDFInvoice
 * @since 1.0.0
 */

namespace Storeplugin\PDFInvoice;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Contracts\ServiceInterface;
use Storeplugin\PDFInvoice\Framework\Abstracts\Autowire;
use Storeplugin\PDFInvoice\App\Settings\SettingsSchema;
use Storeplugin\PDFInvoice\Framework\Utils\Utils;
use Storeplugin\PDFInvoice\App\Utils as AppUtils;
use Storeplugin\PDFInvoice\App\TempDir;

/**
 * The plugin activation class.
 *
 * @since 1.0.0
 */
class Activate implements ServiceInterface {
	/**
	 * Register the activation hook.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function register(): void {
		register_activation_hook(NXTPDF_PATH, [$this, 'activate']);
	}

	/**
	 * Plugin activation handler.
	 *
	 * Stores activation metadata to help with tracing and diagnostics, including
	 * plugin version, activation date/time, site URL, PHP version, and WordPress version.
	 * Also clears the autowire class cache to ensure fresh discovery of services.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function activate(): void {
		TempDir::path(); // Ensure temp directory is created on activation

		$editorDefaults = SettingsSchema::editorDefaults();
		$settingsDefaults = SettingsSchema::settingsDefaults();

		if (empty(AppUtils::getOptions(AppUtils::GROUP_INVOICE_EDITOR))) {
			AppUtils::updateOptions(AppUtils::GROUP_INVOICE_EDITOR, $editorDefaults);
		}

		if (empty(AppUtils::getOptions(AppUtils::GROUP_SETTINGS))) {
			AppUtils::updateOptions(AppUtils::GROUP_SETTINGS, $settingsDefaults);
		}

		if (!get_option(SettingsSchema::WIZARD_COMPLETED_OPTION)) {
			set_transient(SettingsSchema::WIZARD_REDIRECT_TRANSIENT, true, 30);
		}

		Utils::updateOption('activation_info', [
			'version'       => Config::version(),
			'date'          => gmdate('Y-m-d H:i:s'),
			'site_url'      => get_site_url(),
			'php_version'   => PHP_VERSION,
			'wp_version'    => get_bloginfo('version'),
			'user_id'       => get_current_user_id(),
		], 'nxtpdf_plugin_info');

		// Clear autowire cache to ensure all services are discovered fresh
		$this->clearAutowireCache();

		// Uncomment if plugin registers custom post types or taxonomies
		// flush_rewrite_rules();
	}

	/**
	 * Clear the autowire class discovery cache.
	 *
	 * This ensures that after plugin activation or update, all services
	 * are discovered fresh from the filesystem.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	private function clearAutowireCache(): void {
		// Get composer autoloader to fetch PSR-4 prefixes
		$autoloader = require NXTPDF_DIR . '/vendor/autoload.php';
		$psr4Prefixes = $autoloader->getPrefixesPsr4();

		// Clear the cache using the static method
		Autowire::clearCache(__NAMESPACE__, $psr4Prefixes);
	}
}
