<?php
/**
 * Apply barcodes template
 *
 * @package YITH\Barcodes
 */

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

$action = isset( $option['action'] ) ? $option['action'] : 'apply_barcode_to_products'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride
$desc   = isset( $option['desc'] ) ? $option['desc'] : '';
$name   = isset( $option['name'] ) ? $option['name'] : '';

$post_types = array( 'product', 'product_variation' );

$meta_query = 'regenerate' === get_option( 'ywbc_tool_regenerate_barcodes', 'generate' ) ? array() :
	array(
		array(
			'key'     => YITH_Barcode::YITH_YWBC_META_KEY_BARCODE_DISPLAY_VALUE,
			'compare' => 'NOT EXISTS',
		),
	);

/** APPLY_FILTERS: yith_barcode_query_args_get_products
*
* Filter the default query args when retrieving products in the apply-barcodes view.
*
* @param array $post_type, $post_status, $posts_per_page, $fields, $meta_query.
*/
$query_args = apply_filters(
	'yith_barcode_query_args_get_products',
	array(

		/** APPLY_FILTERS: yith_barcode_query_post_type
		*
		* Filter the default post_types in the apply-barcodes view.
		*
		* @param array $post_types ('product', 'product_variation') by default.
		*/
		'post_type'      => apply_filters( 'yith_barcode_query_post_type', $post_types ),
		'post_status'    => 'publish',
		'posts_per_page' => -1,
		'fields'         => 'ids',
		'meta_query'     => $meta_query, // phpcs:ignore slow query ok.
	)
);



$products = get_posts( $query_args );

$json_product_ids = array();

foreach ( $products as $product ) {
	$json_product_ids[] = $product;
}
$json_product_ids = wp_json_encode( $json_product_ids );
?>

<tr valign="top" class="ywbc-regenerate-tr">
	<th scope="row" class="titledesc"><?php echo wp_kses_post( $name ); ?></th>
	<td class="forminp" colspan="1">
		<div class="yith-plugin-fw__panel__option__content" style="margin-bottom: 10px;">
		<input type="button" class="button button-primary ywbc_apply_barcode"
			data-barcode_action="<?php echo esc_attr( $action ); ?>" data-item_ids="<?php echo esc_attr( $json_product_ids ); ?>"
			value="<?php echo esc_html__( 'Generate barcodes', 'yith-woocommerce-barcodes' ); ?>">
		</div>

		<div class="yith-plugin-fw__panel__option__description"><?php echo esc_html( $desc ); ?></div>

		<br>

		<div class="ywbc_apply_messages">
			<span class="ywbc_apply_icon"></span>
			<span class="ywbc_apply_text"></span>
		</div>

		<div class="ywbc_apply_progressbar" id="ywbc_apply_progressbar_all">
			<div class="ywbc_apply_progressbar_percent" id="ywbc_apply_progressbar_percent_all"></div>
		</div>
	</td>
</tr>
