<?php
/**
 * Plugin activation handler.
 *
 * @package Carticy\CheckoutShield\Core
 */

declare(strict_types=1);

namespace Carticy\CheckoutShield\Core;

use Carticy\CheckoutShield\Services\StatsService;

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

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

	/**
	 * Run activation tasks.
	 */
	public static function activate(): void {
		// Set default options if they don't exist.
		self::set_default_options();

		// Create database tables.
		Database::create_tables();

		// Flush rewrite rules.
		flush_rewrite_rules();

		// Set activation timestamp.
		update_option( 'carticy_checkout_shield_activated', time() );

		// Log activation.
		if ( function_exists( 'wc_get_logger' ) ) {
			wc_get_logger()->info(
				'Checkout Shield activated',
				array( 'source' => 'carticy-checkout-shield' )
			);
		}
	}

	/**
	 * Set default plugin options.
	 */
	private static function set_default_options(): void {
		$defaults = array(
			'carticy_checkout_shield_enabled'           => 'yes',
			'carticy_checkout_shield_mode'              => 'balanced', // Block if double-submit fails.
			'carticy_checkout_shield_proxy_support'     => 'no',
			'carticy_checkout_shield_whitelisted_ips'   => array(),
			'carticy_checkout_shield_api_keys'          => array(),
			'carticy_checkout_shield_blocklist_enabled' => 'yes', // Fraud prevention blocklist.
			'carticy_checkout_shield_log_level'         => 'basic', // Logging level (off/basic/detailed).
			StatsService::OPTION_KEY                    => array(), // Daily stats storage.
		);

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