<?php

namespace EasyCriticalCSS;

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

class Uninstall_Handler {
	public static function init() {
		add_action( 'admin_post_easy_cc_uninstall', [ __CLASS__, 'uninstall' ] );
	}

	public static function uninstall() {
		// Nonce check.
		if ( ! isset( $_POST['easy_cc_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['easy_cc_nonce'] ) ), 'easy_cc_uninstall' ) ) {
			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' ) );
		}

		// Delete db table.
		global $wpdb;
		$table_name = $wpdb->prefix . 'easy_critical_css';
		$wpdb->query( 'DROP TABLE IF EXISTS ' . esc_sql( $table_name ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Dropping plugin table during uninstall requires direct database query.

		// Delete any static files.
		Delete_Handler::delete_files();

		// Delete log file.
		Debug::clear_log();

		// Remove options.
		delete_option( 'easy_cc_version' );
		delete_option( 'easy_cc_db_version' );
		Reset_Handler::reset_settings();

		// Remove Freemius-related options
		easy_cc_fs()->add_action( 'after_uninstall', 'easy_cc_fs_uninstall_cleanup' );

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

		// Deactivate Easy Critical CSS plugin.
		deactivate_plugins( Plugin::get_plugin_file() );

		// Flush rewrite rules.
		flush_rewrite_rules();

		// Redirect w/success message.
		wp_safe_redirect( admin_url( 'plugins.php?deleted=true' ) );
		exit;
	}
}
