<?php
/**
 * FinalPOS - Custom Refund Restock Handling
 *
 * This file extends WooCommerce's refund functionality to track restock decisions
 * at the line item level within each refund.
 *
 * @package FinalPOS
 */

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

/**
 * FinalPOS Refund Restock Handler Class
 *
 * Handles custom restock tracking for refunds.
 */
class FinalPOS_Refund_Restock {
	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'woocommerce_refund_created', array( $this, 'save_restock_data' ), 10, 2 );
		add_filter( 'woocommerce_hidden_order_itemmeta', array( $this, 'hide_restock_item_meta' ) );
	}

	/**
	 * Save restock data for each line item in the refund.
	 *
	 * @param int   $refund_id The refund ID.
	 * @param array $args The refund arguments.
	 */
	public function save_restock_data( $refund_id, $args ) {
		$refund = wc_get_order( $refund_id );
		if ( ! $refund || ! is_a( $refund, 'WC_Order_Refund' ) ) {
			return;
		}

		$restock_requested = ! empty( $args['restock_items'] );

		if ( $restock_requested && ! empty( $args['line_items'] ) && is_array( $args['line_items'] ) ) {
			$refund_items = $refund->get_items();

			foreach ( $refund_items as $refund_item ) {
				$original_id = $refund_item->get_meta( '_refunded_item_id' );

				if ( isset( $args['line_items'][ $original_id ] ) &&
					isset( $args['line_items'][ $original_id ]['qty'] ) &&
					$args['line_items'][ $original_id ]['qty'] > 0 ) {

					$refund_item->add_meta_data( FINALPOS_META_KEY_RESTOCK, true, true );
					$refund_item->save_meta_data();
				}
			}
		}
	}

	/**
	 * Hide restock metadata from order item display.
	 *
	 * @param array $hidden_meta Array of meta keys to hide.
	 * @return array Modified array.
	 */
	public function hide_restock_item_meta( $hidden_meta ) {
		$hidden_meta[] = FINALPOS_META_KEY_RESTOCK;
		return $hidden_meta;
	}
}

new FinalPOS_Refund_Restock();
