<?php

namespace EasyCriticalCSS;

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

class Reset_Handler {
	public static function init() {
		add_action( 'admin_post_easy_cc_reset', [ __CLASS__, 'reset' ] );
	}

	public static function reset_settings() {
		$settings = [
			'critical_css_mode',
			'secondary_css_behavior',
			'forced_critical_selectors',
			'forced_secondary_selectors',
			'default_critical_css',
			'exclude_css_files',
			'ignore_cross_domain_css',
			'serve_css_from_files',
			'regenerate_triggers',
			'expired_css_behavior',
			'cloudflare_email',
			'cloudflare_api_key',
			'cloudflare_zone_id',
			'debug_mode',
		];
		foreach ( $settings as $setting ) {
			delete_option( "easy_cc_$setting" );
		}
	}

	public static function reset() {
		// Nonce check.
		if ( ! isset( $_POST['easy_cc_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['easy_cc_nonce'] ) ), 'easy_cc_reset' ) ) {
			wp_die( esc_html__( 'Invalid request.', 'easy-critical-css' ) );
		}

		// User authorized?
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'easy-critical-css' ) );
		}

		// Reset each setting.
		self::reset_settings();

		// Flush rewrite rules.
		flush_rewrite_rules();

		// Clear all cache.
		Compatibility_Cache::clear_cache_all();

		// Remove transients.
		Timed_Option::delete_all();

		// Remove old transients.
		delete_transient( 'easy_cc_is_local_site' );
		delete_transient( 'easy_cc_is_rest_api_reachable' );

		// Redirect w/success message.
		wp_safe_redirect( add_query_arg( 'settings-reset', 'true', admin_url( 'options-general.php?page=easy-critical-css-settings' ) ) );
		exit;
	}
}
