<?php
/**
* Re-creates price per unit prices for all concerned products
*
* @package PricePerUnit/Admin
*/

delete_post_meta_by_key( '_mcmp_ppu_recalculated_price_num' );
delete_post_meta_by_key( '_mcmp_ppu_recalculated_price_text' );
delete_post_meta_by_key( '_mcmp_ppu_price' );
delete_post_meta_by_key( '_mcmp_ppu_price_text' );
delete_post_meta_by_key( '_mcmp_ppu_price_min' );
delete_post_meta_by_key( '_mcmp_ppu_price_max' );
$args = array(
    'post_type'         => 'product',
    'posts_per_page'    => -1,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ){ 
    while ( $query->have_posts() ){
        $query->the_post();
        $postid = $query->post->ID;
        if($this->should_recalc($postid, true)){
			$prices = array();
            $product_to_inspect = wc_get_product($postid);
            if($product_to_inspect->get_type() ==='variable'){
                $children = $product_to_inspect->get_children();
            }else{
                $children = array($postid);
            }
            foreach ($children as $value) {
                $price = $this->calculate_product_price($value, true);
                if(!empty($price)){
					$prices[] = $price;
                    $text_price = $this->mcmp_format_plain_price($price);
                    $text_price = $this->render_recalc_text($value, $text_price, false, false);
                    //$text_price = html_entity_decode($text_price);
                    update_post_meta($value ,'_mcmp_ppu_price', $price);
                    update_post_meta($value ,'_mcmp_ppu_price_text', $text_price);
                }
			}
			if ($prices) {
				asort($prices);
				$price_min = reset($prices);
				$price_max = end($prices);
				update_post_meta( $postid, '_mcmp_ppu_price_min', $price_min );
				update_post_meta( $postid, '_mcmp_ppu_price_max', $price_max );
			}
        }
    }
    wp_reset_postdata();
}
esc_html_e('Prices Re-creation finished successfully!', 'woo-price-per-unit-pro');
wp_die();