<?php

namespace EasyCriticalCSS;

use WP_Error;

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

class Delete_Handler {
	public static function init() {
		add_action( 'admin_post_easy_cc_delete', [ __CLASS__, 'delete' ] );
	}

	public static function delete_files() {
		$basedir = trailingslashit( wp_upload_dir()['basedir'] ) . 'easy-critical-css';
		$subdirs = [ 'critical', 'secondary', 'remaining' ];

		foreach ( $subdirs as $subdir ) {
			$dir = trailingslashit( $basedir ) . $subdir;

			if ( file_exists( $dir ) ) {
				foreach ( glob( "$dir/*.css" ) as $file ) {
					wp_delete_file( $file );
				}

				// We are deleting from wp-content/uploads which is writable on all standard WordPress installs.
				// WP_Filesystem is not needed here and may cause permission prompts on some hosts.
				// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
				rmdir( $dir );
			}
		}

		if ( is_dir( $basedir ) && count( glob( "$basedir/*" ) ) === 0 ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
			rmdir( $basedir );
		}
	}

	public static function delete() {
		// Nonce check.
		if ( ! isset( $_POST['easy_cc_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['easy_cc_nonce'] ) ), 'easy_cc_delete' ) ) {
			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 from db.
		Database::clear_all_styles();

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

		// Flush rewrite rules.
		flush_rewrite_rules();

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

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

	private static function delete_individual_files( $identifier ) {
		$hash    = Helpers::get_url_hash( $identifier );
		$upload  = wp_upload_dir();
		$base    = trailingslashit( $upload['basedir'] ) . 'easy-critical-css/';
		$subdirs = [ 'critical', 'secondary', 'remaining' ];

		foreach ( $subdirs as $subdir ) {
			$pattern = $base . $subdir . '/' . $hash . '*.css';
			foreach ( glob( $pattern ) as $file ) {
				wp_delete_file( $file );
			}
		}
	}

	public static function delete_one( $identifier ) {
		// Since each of these functions pull a hash, it's better to generate it just one time here.
		$hash = Helpers::get_url_hash( $identifier );

		// Delete from db.
		$result = Database::clear_individual_styles( $hash );

		// Delete files.
		self::delete_individual_files( $hash );

		// Clear cache.
		Compatibility_Cache::clear_cache_single( $hash );

		// Return error if we have one.
		if ( false === $result ) {
			return new WP_Error(
				'delete_failed',
				__( 'Could not delete CSS for that identifier.', 'easy-critical-css' ),
				[ 'status' => 400 ]
			);
		}

		return true;
	}
}
