<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
function drop_print_handle_delete_assets() {
	$deleted_thumb_status = 'skipped';
	$deleted_afp_status   = 'skipped';
	$reset_staged_status  = 'failed';
	try {
		check_ajax_referer( 'drop_print_nonce', 'nonce' );
		if ( ! current_user_can( 'edit_products' ) || ! current_user_can( 'delete_posts' ) || ! current_user_can( 'upload_files' ) ) {
			throw new Exception( __( 'Insufficient permissions.', 'drop-print' ), 403 );
		}
		$product_id        = isset( $_POST['product_id'] ) ? absint( $_POST['product_id'] ) : 0;
		$thumbnail_id      = isset( $_POST['thumbnail_id'] ) ? absint( $_POST['thumbnail_id'] ) : 0;
		$afp_base_filename = isset( $_POST['afp_base_filename'] ) ? sanitize_file_name( wp_unslash( $_POST['afp_base_filename'] ) ) : null;
		if ( ! $product_id ) {
			throw new Exception( __( 'Missing Product ID.', 'drop-print' ), 400 );
		}
		$meta_data = get_post_meta( $product_id, '_drop_print_meta', true );
		if ( ! is_array( $meta_data ) ) {
			$meta_data = array();
		}
		$meta_data['doing_reset'] = true;
		unset( $meta_data['variations'], $meta_data['variations_processed'] );
		$update_result = update_post_meta( $product_id, '_drop_print_meta', $meta_data );
		$current_meta_after_attempt = get_post_meta( $product_id, '_drop_print_meta', true );
		if ( ($update_result !== false) || (is_array($current_meta_after_attempt) && isset($current_meta_after_attempt['doing_reset']) && $current_meta_after_attempt['doing_reset'] === true) ) {
			$reset_staged_status = 'staged';
		} else {
			throw new Exception( __( 'Failed to stage reset flag in product meta. The meta was not updated as expected.', 'drop-print' ), 500 );
		}
		if ( $thumbnail_id > 0 ) {
			if ( get_post_status( $thumbnail_id ) ) {
				$delete_thumb_result = wp_delete_attachment( $thumbnail_id, true );
				if ( false !== $delete_thumb_result ) {
					$deleted_thumb_status = 'deleted';
				} else {
					$deleted_thumb_status = 'failed';
				}
			} else {
				$deleted_thumb_status = 'not_found';
			}
		}
		if ( ! empty( $afp_base_filename ) ) {
			$should_delete_physical_file = false;
			$reason_file_kept = '';
			$now_unreferenced = function_exists('drop_print_files_remove_product_ref')
				? drop_print_files_remove_product_ref($afp_base_filename, $product_id)
				: true;
			if (!$now_unreferenced) {
				$reason_file_kept = 'kept_refs_exist';
			} elseif (function_exists('drop_print_is_file_in_live_order') && drop_print_is_file_in_live_order($afp_base_filename)) {
				$reason_file_kept = 'kept_live_order';
			} else {
				$should_delete_physical_file = true;
			}
			if ($should_delete_physical_file) {
				$uploads = wp_upload_dir();
				if ( ! empty( $uploads['error'] ) ) {
					$deleted_afp_status = 'failed_dir_error';
				} else {
					$full_path      = function_exists( 'drop_print_container_path' ) ? drop_print_container_path( trailingslashit( $uploads['basedir'] ) . 'drop-print', $afp_base_filename ) : trailingslashit( $uploads['basedir'] ) . 'drop-print/' . $afp_base_filename . '.drop';
					$drop_print_dir = trailingslashit( $uploads['basedir'] ) . 'drop-print';
					$filename       = basename( $full_path );
					$real_base_dir  = realpath( $drop_print_dir );
					$real_file_path = realpath( $full_path );
					if ( $real_base_dir && $real_file_path && 0 === strpos( $real_file_path, untrailingslashit( $real_base_dir ) ) ) {
						if ( file_exists( $full_path ) ) {
							if ( wp_delete_file( $full_path ) ) {
								$deleted_afp_status = 'deleted';
							} else {
								$deleted_afp_status = 'failed_unlink';
							}
						} else {
							$deleted_afp_status = 'not_found';
						}
					} else {
						$deleted_afp_status = 'invalid_path';
					}
				}
				if (in_array($deleted_afp_status, array('deleted', 'not_found'), true) && function_exists('drop_print_files_delete_record')) {
					drop_print_files_delete_record($afp_base_filename);
				}
			} else {
				$deleted_afp_status = $reason_file_kept ?: 'kept_unknown_reason';
			}
		}
		$message_format = __( 'Drop Print reset staged. Thumbnail: %1$s. Container File: %2$s. Please Update/Publish the product to finalize.', 'drop-print' );
		$message = sprintf(
			$message_format,
			esc_html( $deleted_thumb_status ),
			esc_html( $deleted_afp_status )
		);
		wp_send_json_success( array( 'message' => $message ) );
	} catch ( Exception $e ) {
		$error_code    = is_int( $e->getCode() ) && $e->getCode() >= 400 ? $e->getCode() : 500;
		$error_message = $e->getMessage();
		wp_send_json_error(
			array( 'message' => __( 'Reset failed:', 'drop-print' ) . ' ' . $error_message ),
			$error_code
		);
	}
}
add_action( 'wp_ajax_drop_print_delete_assets', 'drop_print_handle_delete_assets' );
