<?php
/**
 * Clean up export files generated by H5P caretaker.
 *
 * @package ndla-h5p-caretaker
 */

namespace NDLAH5PCARETAKER;

use Ndlano\H5PCaretaker\H5PCaretaker;

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

/**
 * Clean up export files generated by H5P caretaker.
 * This should currently never be called, because the H5P plugin for WordPress
 * always creates export files regardless of what the author or admin set for
 * allowing downloads. We could also query the admin settings for "Allow download" and
 * the author settings for "Allow users to download the content", but we just keep
 * everything like we found it.
 */
function clean_up_export_file() {
	if ( ! isset( $_SERVER['REQUEST_METHOD'] ) || 'POST' !== $_SERVER['REQUEST_METHOD'] ) {
		wp_die();
	}

	// Using 'h5p-caretaker-upload' nonce here, since this is not supposed to be used separately.
	if (
		! isset( $_POST['h5pCaretakerNonce'] ) ||
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['h5pCaretakerNonce'] ) ), 'h5p-caretaker-upload' )
	) {
		wp_die( esc_html( __( 'Invalid nonce verification.', 'ndla-h5p-caretaker' ) ) );
	}

	// Capability is registered in ndla-h5p-caretaker.php.
	// phpcs:ignore WordPress.WP.Capabilities.Unknown
	if ( ! current_user_can( 'use-h5p-caretaker' ) ) {
		// Redirect to the dashboard or display an error message.
		wp_die( esc_html( __( 'You do not have sufficient permissions to access this page.', 'ndla-h5p-caretaker' ) ) );
	}

	if ( ! isset( $_POST['action'] ) || 'remove' !== $_POST['action'] ) {
		wp_die();
	}

	$h5p_id = filter_input( INPUT_POST, 'id', FILTER_SANITIZE_SPECIAL_CHARS ) ?? '';
	if ( empty( $h5p_id ) ) {
		wp_die();
	}

	$core    = \H5P_Plugin::get_instance()->get_h5p_instance( 'core' );
	$content = $core->loadContent( $h5p_id );

	$export_file_name = $content['slug'] . '-' . $content['id'] . '.h5p';
	$core->fs->deleteExport( $export_file_name );

	exit();
}
