<?php
/**
 * Edit product Pre-Order tab options
 *
 * @package YITH\PreOrder\Templates\Admin
 * @since   2.0.0
 * @author  YITH <plugins@yithemes.com>
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Vars used on this template.
 *
 * @var string $post_type The post type used for the current List Table.
 * @var WP_Posts_List_Table $wp_list_table The list table. It could be YITH_Pre_Order_Orders_List or YITH_Pre_Order_Orders_List.
 */
?>

<?php
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
$post_type_object = get_post_type_object( $post_type );
$table_title      = '';
$export_action    = '';

switch ( $post_type ) {
	case 'product':
		$export_action = 'ywpo_export_pre_order_products';
		break;
	case 'shop_order':
		$export_action = 'ywpo_export_pre_orders';
		break;
}

if ( ! $post_type_object ) {
	// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	wp_die( __( 'Invalid post type.' ) );
}

if ( ! current_user_can( $post_type_object->cap->edit_posts ) ) {
	wp_die(
		'<h1>' . __( 'You need a higher level of permission.' ) . '</h1>' . // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		'<p>' . __( 'Sorry, you are not allowed to edit posts in this post type.' ) . '</p>', // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		403
	);
}

$pagenum = $wp_list_table->get_pagenum();

foreach ( array( 'p', 'attachment_id', 'page_id' ) as $_redirect ) {
	if ( ! empty( $_REQUEST[ $_redirect ] ) ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		wp_safe_redirect( admin_url( 'edit-comments.php?p=' . absint( $_REQUEST[ $_redirect ] ) ) );
		exit;
	}
}
unset( $_redirect );

if ( 'post' !== $post_type ) {
	$parent_file   = "edit.php?post_type=$post_type"; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
	$submenu_file  = "edit.php?post_type=$post_type"; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
	$post_new_file = "post-new.php?post_type=$post_type";
} else {
	$parent_file   = 'edit.php'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
	$submenu_file  = 'edit.php'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
	$post_new_file = 'post-new.php';
}
$doaction = $wp_list_table->current_action();

if ( $doaction ) {
	check_admin_referer( 'bulk-posts' );

	$sendback = remove_query_arg( array( 'trashed', 'untrashed', 'deleted', 'locked', 'ids' ), wp_get_referer() );
	if ( ! $sendback ) {
		$sendback = admin_url( $parent_file );
	}
	$sendback = add_query_arg( 'paged', $pagenum, $sendback );
	if ( strpos( $sendback, 'post.php' ) !== false ) {
		$sendback = admin_url( $post_new_file );
	}

	$post_ids = array();

	if ( 'delete_all' === $doaction ) {
		global $wpdb;
		// Prepare for deletion of all posts with a specified post status (i.e. Empty Trash).
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
		$post_status = preg_replace( '/[^a-z0-9_-]+/i', '', $_REQUEST['post_status'] );
		// Validate the post status exists.
		if ( get_post_status_object( $post_status ) ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type=%s AND post_status = %s", $post_type, $post_status ) );
		}
		$doaction = 'delete';
	} elseif ( isset( $_REQUEST['media'] ) ) {
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
		$post_ids = $_REQUEST['media'];
	} elseif ( isset( $_REQUEST['ids'] ) ) {
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
		$post_ids = explode( ',', $_REQUEST['ids'] );
	} elseif ( ! empty( $_REQUEST['post'] ) ) {
		$post_ids = array_map( 'intval', $_REQUEST['post'] );
	}

	if ( empty( $post_ids ) ) {
		wp_safe_redirect( $sendback );
		exit;
	}

	switch ( $doaction ) {
		case 'trash':
			$trashed = 0;
			$locked  = 0;

			// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
			foreach ( (array) $post_ids as $post_id ) {
				if ( ! current_user_can( 'delete_post', $post_id ) ) {
					// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					wp_die( __( 'Sorry, you are not allowed to move this item to the Trash.' ) );
				}

				if ( wp_check_post_lock( $post_id ) ) {
					$locked ++;
					continue;
				}

				if ( ! wp_trash_post( $post_id ) ) {
					// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					wp_die( __( 'There was an error moving the item to the Trash.' ) );
				}

				$trashed ++;
			}

			$sendback = add_query_arg(
				array(
					'trashed' => $trashed,
					'ids'     => implode( ',', $post_ids ),
					'locked'  => $locked,
				),
				$sendback
			);
			break;
		case 'untrash':
			$untrashed = 0;

			if ( isset( $_GET['doaction'] ) && ( 'undo' === $_GET['doaction'] ) ) {
				add_filter( 'wp_untrash_post_status', 'wp_untrash_post_set_previous_status', 10, 3 );
			}

			// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
			foreach ( (array) $post_ids as $post_id ) {
				if ( ! current_user_can( 'delete_post', $post_id ) ) {
					// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					wp_die( __( 'Sorry, you are not allowed to restore this item from the Trash.' ) );
				}

				if ( ! wp_untrash_post( $post_id ) ) {
					// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					wp_die( __( 'There was an error restoring the item from the Trash.' ) );
				}

				$untrashed ++;
			}
			$sendback = add_query_arg( 'untrashed', $untrashed, $sendback );

			remove_filter( 'wp_untrash_post_status', 'wp_untrash_post_set_previous_status', 10, 3 );

			break;
		case 'delete':
			$deleted = 0;

			// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
			foreach ( (array) $post_ids as $post_id ) {
				$post_del = get_post( $post_id );

				if ( ! current_user_can( 'delete_post', $post_id ) ) {
					// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
					wp_die( __( 'Sorry, you are not allowed to delete this item.' ) );
				}

				if ( 'attachment' === $post_del->post_type ) {
					if ( ! wp_delete_attachment( $post_id ) ) {
						// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						wp_die( __( 'There was an error deleting the attachment.' ) );
					}
				} else {
					if ( ! wp_delete_post( $post_id ) ) {
						// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						wp_die( __( 'There was an error deleting the item.' ) );
					}
				}
				$deleted ++;
			}
			$sendback = add_query_arg( 'deleted', $deleted, $sendback );
			break;
		case 'edit':
			if ( isset( $_REQUEST['bulk_edit'] ) ) {
				$done = bulk_edit_posts( $_REQUEST );

				if ( is_array( $done ) ) {
					$done['updated'] = count( $done['updated'] );
					$done['skipped'] = count( $done['skipped'] );
					$done['locked']  = count( $done['locked'] );
					$sendback        = add_query_arg( $done, $sendback );
				}
			}
			break;
		default:
			$screen = get_current_screen()->id;

			/**
			 * Fires when a custom bulk action should be handled.
			 *
			 * The redirect link should be modified with success or failure feedback
			 * from the action to be used to display feedback to the user.
			 *
			 * The dynamic portion of the hook name, `$screen`, refers to the current screen ID.
			 *
			 * @param string $sendback The redirect URL.
			 * @param string $doaction The action being taken.
			 * @param array  $items The items to take the action on. Accepts an array of IDs of posts,
			 *                         comments, terms, links, plugins, attachments, or users.
			 *
			 * @since 4.7.0
			 */
			$sendback = apply_filters( "handle_bulk_actions-{$screen}", $sendback, $doaction, $post_ids ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
			break;
	}

	$sendback = remove_query_arg( array( 'post_type', 'action', 'action2', 'tags_input', 'post_author', 'comment_status', 'ping_status', '_status', 'post', 'bulk_edit', 'post_view' ), $sendback );

	wp_safe_redirect( $sendback );
	exit;
} elseif ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
	// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
	wp_safe_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
	exit;
}

$wp_list_table->prepare_items();
?>

<?php if ( $wp_list_table->has_items() ) : ?>
	<div class="ywpo-export" style="display: none;">
		<a class="button-primary" style="vertical-align: baseline;"
		href="<?php echo esc_url( add_query_arg( array( 'action' => $export_action ), admin_url( 'admin.php' ) ) ); ?>">
			<?php esc_html_e( 'Export CSV', 'yith-pre-order-for-woocommerce' ); ?>
		</a>
	</div>
<?php endif; ?>

<?php  if ( 'shop_order' === $post_type ) : ?>
	<div class="yith-plugin-ui--classic-wp-list-style"><?php  $wp_list_table->views(); ?></div>
<?php endif;

$admin_url = admin_url( 'admin.php' );
$args_url  = array(
	'page'    => 'yith_wcpo_panel',
	'tab'     => 'pre-orders',
	'sub_tab' => 'product' === $post_type ? 'products' : 'orders',
);

$admin_url = add_query_arg( $args_url, $admin_url );
?>

<form id="posts-filter" class="ywpo-list-table ywpo-list-table_<?php echo esc_attr( $post_type ); ?> post-type-<?php echo esc_attr( $post_type ); ?>" method="get" action="<?php echo esc_url( $admin_url ); ?>">
	<?php if ( 'product' === $post_type || 'shop_order' === $post_type ) : ?>
		<?php $wp_list_table->search_box( $post_type_object->labels->search_items, 'post' ); ?>
	<?php endif; ?>
	<input type="hidden" name="page" value="yith_wcpo_panel"/>
	<input type="hidden" name="tab" value="pre-orders"/>
	<input type="hidden" name="sub_tab" value="<?php echo 'product' === $post_type ? 'products' : 'orders'; ?>"/>

	<?php if ( ! empty( $_REQUEST['author'] ) ) { ?>
		<?php // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash ?>
		<input type="hidden" name="author" value="<?php echo esc_attr( $_REQUEST['author'] ); ?>"/>
	<?php } ?>

	<?php if ( ! empty( $_REQUEST['show_sticky'] ) ) { ?>
		<input type="hidden" name="show_sticky" value="1"/>
	<?php } ?>

	<?php $wp_list_table->display(); ?>

</form>
<?php do_action( 'ywpo_list_table_after_form', $post_type, $wp_list_table ); ?>

<div id="ajax-response"></div>
<div class="clear"/></div>
