<?php
/**
 * Fired during plugin activation.
 *
 * @package RawTypeOE
 */

namespace RawTypeOE\Free;

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

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

	/**
	 * Minimum WooCommerce version supported.
	 *
	 * @var string
	 */
	const MIN_WC_VERSION = '8.2';

	/**
	 * Run activation tasks.
	 *
	 * @return void
	 */
	public static function activate() {
		$compatibility_error = self::get_compatibility_error();

		if ( '' !== $compatibility_error ) {
			update_option( 'rawtype_oe_activation_error', $compatibility_error );
			self::deactivate_plugin();
			return;
		}

		delete_option( 'rawtype_oe_activation_error' );

		$defaults = self::get_default_settings();
		$current  = get_option( 'rawtype_oe_settings', array() );

		if ( ! is_array( $current ) ) {
			$current = array();
		}

		$settings = wp_parse_args( $current, $defaults );

		if ( false === get_option( 'rawtype_oe_settings' ) ) {
			add_option( 'rawtype_oe_settings', $settings );
		} else {
			update_option( 'rawtype_oe_settings', $settings );
		}

		update_option( 'rawtype_oe_version', RAWTYPE_OE_VERSION );

		// Ensure export upload directory exists.
		if ( class_exists( 'RawTypeOE\\Free\\File_Manager' ) ) {
			$file_manager = new File_Manager();
			$file_manager->ensure_upload_dir();
			$file_manager->schedule_cleanup();
		}
	}

	/**
	 * Get default plugin settings.
	 *
	 * @return array
	 */
	public static function get_default_settings() {
		return array(
			'default_format' => 'csv',
			'date_format'    => 'Y-m-d',
		);
	}

	/**
	 * Validate WooCommerce compatibility.
	 *
	 * @return string Error key or empty string when valid.
	 */
	private static function get_compatibility_error() {
		if ( ! class_exists( 'WooCommerce' ) ) {
			return 'missing_wc';
		}

		if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, self::MIN_WC_VERSION, '<' ) ) {
			return 'unsupported_wc_version';
		}

		return '';
	}

	/**
	 * Deactivate plugin after failed activation check.
	 *
	 * @return void
	 */
	private static function deactivate_plugin() {
		if ( ! function_exists( 'deactivate_plugins' ) && defined( 'ABSPATH' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		if ( function_exists( 'deactivate_plugins' ) ) {
			deactivate_plugins( RAWTYPE_OE_PLUGIN_BASENAME );
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( isset( $_GET['activate'] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			unset( $_GET['activate'] );
		}
	}
}
