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

namespace SuiteMkt3k;

defined( 'ABSPATH' ) || exit;

final class Activator {

	public static function activate(): void {
		Installer::install();

		Security\Capabilities::register();
		Security\Capabilities::add_to_administrators();

		self::schedule_cron( 'suitemkt3k_cron_5min', 'suitemkt3k_5min', 60 );
		self::schedule_cron( 'suitemkt3k_cron_15min', 'suitemkt3k_15min', 120 );
		self::schedule_cron( 'suitemkt3k_cron_hourly', 'hourly', 300 );
		self::schedule_cron( 'suitemkt3k_cron_daily', 'daily', 600 );

		if ( ! get_option( 'suitemkt3k_secret_key' ) ) {
			add_option( 'suitemkt3k_secret_key', wp_generate_password( 64, true, true ), '', false );
		}

		self::ensure_uploads_dir();
		\SuiteMkt3k\Modules\Backup\Backup_Manager::ensure_backup_dir();

		if ( ! get_option( 'suitemkt3k_settings' ) ) {
			self::seed_defaults();
		}

		update_option( 'suitemkt3k_db_version', SUITEMKT3K_DB_VERSION, false );
		update_option( 'suitemkt3k_activated_at', time(), false );
		set_transient( 'suitemkt3k_show_welcome', 1, MINUTE_IN_SECONDS * 30 );

		flush_rewrite_rules();

		wp_cache_delete( 'active_plugins', 'options' );
		wp_cache_delete( 'alloptions', 'options' );
	}

	private static function schedule_cron( string $hook, string $schedule, int $offset ): void {
		if ( wp_next_scheduled( $hook ) ) {
			return;
		}
		$schedules = wp_get_schedules();
		if ( ! isset( $schedules[ $schedule ] ) ) {
			$schedule = 'hourly';
		}
		wp_schedule_event( time() + max( 30, $offset ), $schedule, $hook );
	}

	private static function ensure_uploads_dir(): void {
		$uploads = wp_upload_dir();
		if ( ! empty( $uploads['error'] ) ) {
			return;
		}
		$dir = trailingslashit( $uploads['basedir'] ) . 'suitemkt3k';
		if ( ! file_exists( $dir ) ) {
			wp_mkdir_p( $dir );
		}
		$index    = $dir . '/index.php';
		$htaccess = $dir . '/.htaccess';
		if ( ! file_exists( $index ) ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
			file_put_contents( $index, "<?php\n// Silence is golden.\n" );
		}
		if ( ! file_exists( $htaccess ) ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
			file_put_contents(
				$htaccess,
				"# SuiteMkt3k\nOptions -Indexes\n<FilesMatch \"\\.(log|json|sql|env)$\">\n  Require all denied\n</FilesMatch>\n"
			);
		}
	}

	private static function seed_defaults(): void {
		add_option(
			'suitemkt3k_settings',
			array(
				'company'    => array(
					'name'     => '',
					'email'    => get_option( 'admin_email' ),
					'reply_to' => get_option( 'admin_email' ),
					'logo_id'  => 0,
					'address'  => '',
					'website'  => home_url(),
					'phone'    => '',
				),
				'coupons'    => array(
					'default_bg'   => '#2AB2E5',
					'default_text' => '#FFFFFF',
					'popup_delay'  => 4,
					'cookie_days'  => 7,
				),
				'newsletter' => array(
					'batch_size'     => 50,
					'batch_interval' => 60,
					'default_footer' => '',
				),
				'subscribers' => array(
					'unsubscribe_success' => '',
					'unsubscribe_already' => '',
				),
				'cart'       => array(
					'auto_send_enabled' => false,
					'auto_send_hours'   => 1,
					'purge_days'        => 30,
				),
				'smtp'       => array(
					'enabled'    => false,
					'host'       => '',
					'port'       => 587,
					'encryption' => 'tls',
					'auth'       => true,
					'username'   => '',
					'password'   => '',
					'from_email' => get_option( 'admin_email' ),
					'from_name'  => get_bloginfo( 'name' ),
				),
				'language'   => array(
					'default' => 'es_ES',
				),
				'advanced'   => array(
					'enable_logs'   => true,
					'enable_pixel'  => true,
					'enable_clicks' => true,
				),
				'backup'     => array(
					'auto_enabled'  => false,
					'interval_days' => 7,
				),
			),
			'',
			false
		);
	}
}
