<?php
/**
 * Activation handler.
 *
 * @package Carticy\Conversions\Core
 */

declare(strict_types=1);

namespace Carticy\Conversions\Core;

use Carticy\Conversions\Storage\SchemaManager;
use Carticy\Conversions\Privacy\PrivacyService;
use Carticy\Conversions\Settings\ConsentPostureSettings;

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

/**
 * Handles activation tasks.
 */
final class Activator {

	/**
	 * Run activation tasks.
	 */
	public static function activate(): void {
		self::set_default_options();
		SchemaManager::install();
		PrivacyService::schedule_retention();

		flush_rewrite_rules();

		// Write-once: this marks when tracking STARTED existing on the site.
		// Diagnostics clamp their scans to it so orders paid before the plugin
		// was installed are never reported as "missed" - a deactivate/
		// reactivate cycle must not move that boundary forward.
		if ( 0 === (int) get_option( 'carticy_conversions_activated_at', 0 ) ) {
			update_option( 'carticy_conversions_activated_at', time() );
		}

		if ( function_exists( 'wc_get_logger' ) ) {
			wc_get_logger()->info(
				'Carticy Conversions activated',
				array( 'source' => 'carticy-conversions' )
			);
		}
	}

	/**
	 * Seed defaults without overwriting existing merchant settings.
	 */
	private static function set_default_options(): void {
		$defaults = array(
			'carticy_conversions_enabled'                  => 'yes',
			'carticy_conversions_delete_data_on_uninstall' => 'no',
			'carticy_conversions_db_version'               => '0',
		);

		foreach ( $defaults as $option_name => $default_value ) {
			if ( false === get_option( $option_name ) ) {
				add_option( $option_name, $default_value );
			}
		}

		ConsentPostureSettings::add_default_options();
	}
}
