<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! function_exists( 'drop_print_split_package_by_drop_print_items' ) ) {
	function drop_print_split_package_by_drop_print_items( array $package ): array {
		if ( empty( $package['contents'] ) || ! is_array( $package['contents'] ) || ! function_exists( 'drop_print_cart_item_is_drop_print_item' ) ) {
			return array( $package );
		}
		$dp_contents  = array();
		$rest_contents = array();
		foreach ( $package['contents'] as $key => $cart_item ) {
			if ( drop_print_cart_item_is_drop_print_item( $cart_item ) ) {
				$dp_contents[ $key ] = $cart_item;
			} else {
				$rest_contents[ $key ] = $cart_item;
			}
		}
		if ( ! empty( $dp_contents ) && empty( $rest_contents ) ) {
			$package['drop_print_only'] = true;
			return array( $package );
		}
		if ( empty( $dp_contents ) ) {
			return array( $package );
		}
		$dp_package                     = $package;
		$dp_package['contents']         = $dp_contents;
		$dp_package['contents_cost']    = array_sum( wp_list_pluck( $dp_contents, 'line_total' ) );
		$dp_package['drop_print_only']  = true;
		$rest_package                  = $package;
		$rest_package['contents']      = $rest_contents;
		$rest_package['contents_cost'] = array_sum( wp_list_pluck( $rest_contents, 'line_total' ) );
		return array( $dp_package, $rest_package );
	}
}
if ( ! function_exists( 'drop_print_split_cart_shipping_packages' ) ) {
	function drop_print_split_cart_shipping_packages( array $packages ): array {
		$split = array();
		foreach ( $packages as $package ) {
			if ( ! is_array( $package ) ) {
				$split[] = $package;
				continue;
			}
			foreach ( drop_print_split_package_by_drop_print_items( $package ) as $part ) {
				$split[] = $part;
			}
		}
		return $split;
	}
}
add_filter( 'woocommerce_cart_shipping_packages', 'drop_print_split_cart_shipping_packages', 20 );
if ( ! function_exists( 'drop_print_enforce_exclusive_rate_on_drop_print_package' ) ) {
	function drop_print_enforce_exclusive_rate_on_drop_print_package( array $rates, array $package ): array {
		if ( empty( $package['drop_print_only'] ) ) {
			return $rates;
		}
		$filtered = array();
		foreach ( $rates as $rate_id => $rate ) {
			$method_id = is_object( $rate ) && method_exists( $rate, 'get_method_id' ) ? $rate->get_method_id() : '';
			if ( 'drop_print_live_postage' === $method_id ) {
				$filtered[ $rate_id ] = $rate;
			}
		}
		return $filtered;
	}
}
add_filter( 'woocommerce_package_rates', 'drop_print_enforce_exclusive_rate_on_drop_print_package', 20, 2 );
