<?php

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

class W2W_Auto_Stock_Restore {

	public function __construct() {
		
		// 后台设置项
		add_action( 'w2w_settings_advanced_tab_content_end', array( $this, 'auto_restore_stock_setting' ) );
		
		add_action( 'woocommerce_order_status_cancelled', array( $this, 'restore_order_stock' ) );
	}
	
	public function auto_restore_stock_setting( $settings ) {
	?>
	<tr><th >自动恢复库存</th><td>
	<label for="w2w-settings[auto_restore_stock]">
	<input type="checkbox" id="w2w-settings[auto_restore_stock]" name="w2w-settings[auto_restore_stock]" <?php checked( isset( $settings['auto_restore_stock'] ) ) ?>>开启
	<p class="description">当订单从任何状态变为“已取消”时，恢复订单中物品的库存</p>
	</label>
	</td></tr>
	<?php
	}

	public function restore_order_stock( $order_id ) {
		
		$settings = get_option( 'w2w-settings' );
		if( ! isset( $settings['auto_restore_stock'] ) ) return;
		
		$order = new WC_Order( $order_id );

		if ( ! get_option('woocommerce_manage_stock') == 'yes' && ! sizeof( $order->get_items() ) > 0 ) {
			return;
		}

		foreach ( $order->get_items() as $item ) {

			if ( $item['product_id'] > 0 ) {
				$_product = $order->get_product_from_item( $item );

				if ( $_product && $_product->exists() && $_product->managing_stock() ) {

					$old_stock = $_product->stock;

					$qty = apply_filters( 'woocommerce_order_item_quantity', $item['qty'], $this, $item );

					$new_quantity = $_product->increase_stock( $qty );

					do_action( 'woocommerce_auto_stock_restored', $_product, $item );

					$order->add_order_note( sprintf( '#%s 库存从 %s 恢复为 %s', $item['product_id'], $old_stock, $new_quantity) );

					$order->send_stock_notifications( $_product, $new_quantity, $item['qty'] );
				}
			}
		}
	}
}

$GLOBALS['w2w_auto_stock_restore'] = new W2W_Auto_Stock_Restore();