<?php
/**
 * Plugin activation handler.
 *
 * @package Donatico
 */

declare(strict_types=1);

namespace Donatico;

use Donatico\Database\Schema;

/**
 * Runs once when the plugin is activated via the WP admin.
 * Creates database tables and seeds default options.
 */
class Activator {

	/**
	 * Run all activation routines.
	 *
	 * Called by register_activation_hook() in the bootstrap file.
	 *
	 * @return void
	 */
	public static function activate(): void {
		self::checkRequirements();
		Schema::createTables();
		self::seedDefaultOptions();
		self::scheduleEvents();
		flush_rewrite_rules();
	}

	/**
	 * Abort activation if server requirements are not met.
	 *
	 * @return void
	 */
	private static function checkRequirements(): void {
		if ( version_compare( PHP_VERSION, '7.4', '<' ) ) {
			wp_die(
				esc_html__(
					'Donatico requires PHP 7.4 or higher. Please upgrade your PHP version.',
					'donatico'
				),
				esc_html__( 'Plugin Activation Error', 'donatico' ),
				array( 'back_link' => true )
			);
		}
	}

	/**
	 * Write default plugin options when activating for the first time.
	 *
	 * @return void
	 */
	private static function seedDefaultOptions(): void {
		$defaults = array(
			'donatico_version'          => DONATICO_VERSION,
			'donatico_currency'         => 'USD',
			'donatico_preset_amounts'   => array( 5, 10, 25, 50, 100 ),
			'donatico_stripe_test_mode' => true,
			'donatico_form_layout'      => 'stacked',
			'donatico_goal_amount'      => 0,
			'donatico_notify_admin'     => true,
			'donatico_notify_donor'     => true,
		);

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

	/**
	 * Register any recurring WP-Cron events the plugin needs.
	 *
	 * @return void
	 */
	private static function scheduleEvents(): void {
		if ( ! wp_next_scheduled( 'donatico_daily_cleanup' ) ) {
			wp_schedule_event( time(), 'daily', 'donatico_daily_cleanup' );
		}
	}
}
