<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! defined( 'DROP_PRINT_FILE_ISSUE_NOTICE_DISMISSED_META' ) ) {
	define( 'DROP_PRINT_FILE_ISSUE_NOTICE_DISMISSED_META', 'drop_print_file_issue_notice_dismissed_ids' );
}
if ( ! defined( 'DROP_PRINT_FILE_ISSUE_ORDER_IDS_TRANSIENT' ) ) {
	define( 'DROP_PRINT_FILE_ISSUE_ORDER_IDS_TRANSIENT', 'drop_print_file_issue_order_ids' );
}
if ( ! defined( 'DROP_PRINT_FILE_ISSUE_LOOKUP_MINUTES' ) ) {
	define( 'DROP_PRINT_FILE_ISSUE_LOOKUP_MINUTES', 5 );
}
if ( ! defined( 'DROP_PRINT_FILE_ISSUE_LOOKUP_LIMIT' ) ) {
	define( 'DROP_PRINT_FILE_ISSUE_LOOKUP_LIMIT', 20 );
}
if ( ! function_exists( 'drop_print_get_file_issue_order_ids' ) ) {
	function drop_print_get_file_issue_order_ids(): array {
		$cached = get_transient( DROP_PRINT_FILE_ISSUE_ORDER_IDS_TRANSIENT );
		if ( is_array( $cached ) ) {
			return array_filter( array_map( 'absint', $cached ) );
		}
		$order_ids = array();
		if ( function_exists( 'wc_get_orders' ) ) {
			$orders = wc_get_orders(
				array(
					'limit'      => DROP_PRINT_FILE_ISSUE_LOOKUP_LIMIT,
					'orderby'    => 'date',
					'order'      => 'DESC',
					'meta_query' => array(
						array(
							'key'     => '_drop_print_order_details',
							'value'   => 'file_issue_detected',
							'compare' => 'LIKE',
						),
					),
				)
			);
			foreach ( $orders as $order ) {
				if ( ! ( $order instanceof WC_Order ) ) {
					continue;
				}
				$details = $order->get_meta( '_drop_print_order_details', true );
				if ( is_array( $details ) && isset( $details['status'] ) && 'file_issue_detected' === sanitize_key( $details['status'] ) ) {
					$order_ids[] = $order->get_id();
				}
			}
		}
		set_transient( DROP_PRINT_FILE_ISSUE_ORDER_IDS_TRANSIENT, $order_ids, DROP_PRINT_FILE_ISSUE_LOOKUP_MINUTES * MINUTE_IN_SECONDS );
		return $order_ids;
	}
}
if ( ! function_exists( 'drop_print_display_file_issue_notice' ) ) {
	function drop_print_display_file_issue_notice(): void {
		$current_user_id = get_current_user_id();
		if ( $current_user_id === 0 ) {
			return;
		}
		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			return;
		}
		if ( ! function_exists( 'wc_get_order' ) ) {
			return;
		}
		$user_settings = drop_print_get_user_settings( $current_user_id );
		if ( empty( $user_settings['client_user_connection_id'] ) ) {
			return;
		}
		$candidate_ids = drop_print_get_file_issue_order_ids();
		if ( empty( $candidate_ids ) ) {
			return;
		}
		$file_issue_orders = array();
		foreach ( $candidate_ids as $order_id ) {
			$order = wc_get_order( $order_id );
			if ( ! $order ) {
				continue;
			}
			$details = $order->get_meta( '_drop_print_order_details', true );
			if ( is_array( $details ) && isset( $details['status'] ) && 'file_issue_detected' === sanitize_key( $details['status'] ) ) {
				$file_issue_orders[ $order->get_id() ] = $order;
			}
		}
		if ( empty( $file_issue_orders ) ) {
			return;
		}
		$current_ids   = array_keys( $file_issue_orders );
		$dismissed_map = get_user_meta( $current_user_id, DROP_PRINT_FILE_ISSUE_NOTICE_DISMISSED_META, true );
		if ( ! is_array( $dismissed_map ) ) {
			$dismissed_map = array();
		}
		$has_undismissed = false;
		foreach ( $file_issue_orders as $order_id => $order ) {
			if ( ! isset( $dismissed_map[ $order_id ] ) ) {
				$has_undismissed = true;
				break;
			}
			$details            = $order->get_meta( '_drop_print_order_details', true );
			$last_server_update = is_array( $details ) ? absint( $details['last_server_update'] ?? 0 ) : 0;
			if ( $last_server_update > absint( $dismissed_map[ $order_id ] ) ) {
				$has_undismissed = true;
				break;
			}
		}
		if ( ! $has_undismissed ) {
			return;
		}
		$order_links = array();
		foreach ( $file_issue_orders as $order ) {
			$order_links[] = sprintf(
				'<a href="%s">%s</a>',
				esc_url( $order->get_edit_order_url() ),
				esc_html( '#' . $order->get_order_number() )
			);
		}
		$nonce = wp_create_nonce( 'drop_print_dismiss_file_issue_notice' );
		?>
		<div class="notice notice-error is-dismissible drop-print-file-issue-notice" data-dismiss-nonce="<?php echo esc_attr( $nonce ); ?>" data-order-ids="<?php echo esc_attr( implode( ',', $current_ids ) ); ?>">
			<p><strong>
				<?php
				echo esc_html(
					_n(
						'Drop Print detected a file issue with an order. Production is paused until it is resolved.',
						'Drop Print detected file issues with the following orders. Production is paused until they are resolved.',
						count( $file_issue_orders ),
						'drop-print'
					)
				);
				?>
			</strong></p>
			<p>
				<?php
				echo wp_kses(
					sprintf(
						_n( 'Affected order: %s', 'Affected orders: %s', count( $order_links ), 'drop-print' ),
						implode( ', ', $order_links )
					),
					array( 'a' => array( 'href' => array() ) )
				);
				?>
			</p>
			<p class="description"><?php esc_html_e( 'Open the order, then use the "File Issue Detected" link in the Drop Print column of your Orders list to resolve it on the Drop Print server.', 'drop-print' ); ?></p>
		</div>
		<script>
		(function($){
			$(function(){
				$(document).on('click', '.drop-print-file-issue-notice .notice-dismiss', function(){
					var $notice = $(this).closest('.drop-print-file-issue-notice');
					$.post(ajaxurl, {
						action: 'drop_print_dismiss_file_issue_notice',
						nonce: $notice.data('dismiss-nonce'),
						order_ids: String($notice.data('order-ids') || '')
					});
				});
			});
		})(jQuery);
		</script>
		<?php
	}
}
add_action( 'admin_notices', 'drop_print_display_file_issue_notice', 12 );
if ( ! function_exists( 'drop_print_dismiss_file_issue_notice_ajax_handler' ) ) {
	function drop_print_dismiss_file_issue_notice_ajax_handler() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'drop_print_dismiss_file_issue_notice' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'drop-print' ) ), 403 );
			return;
		}
		$user_id = get_current_user_id();
		if ( $user_id <= 0 ) {
			wp_send_json_error( array( 'message' => __( 'Not logged in.', 'drop-print' ) ), 403 );
			return;
		}
		$raw_ids   = isset( $_POST['order_ids'] ) ? sanitize_text_field( wp_unslash( $_POST['order_ids'] ) ) : '';
		$order_ids = array_filter( array_map( 'absint', explode( ',', $raw_ids ) ) );
		if ( empty( $order_ids ) ) {
			wp_send_json_error( array( 'message' => __( 'No orders to dismiss.', 'drop-print' ) ), 400 );
			return;
		}
		update_user_meta( $user_id, DROP_PRINT_FILE_ISSUE_NOTICE_DISMISSED_META, array_fill_keys( $order_ids, time() ) );
		wp_send_json_success();
	}
}
add_action( 'wp_ajax_drop_print_dismiss_file_issue_notice', 'drop_print_dismiss_file_issue_notice_ajax_handler' );
