<?php

if ( ! function_exists( 'wc_get_dimension' ) ) {
	/**
	 * Normalise dimensions, unify to cm then convert to wanted unit value.
	 *
	 * Usage:
	 * wc_get_dimension( 55, 'in' );
	 * wc_get_dimension( 55, 'in', 'm' );
	 *
	 * @param int|float $dimension Dimension.
	 * @param string $to_unit Unit to convert to.
	 *                                Options: 'in', 'm', 'cm', 'm'.
	 * @param string $from_unit Unit to convert from.
	 *                                Defaults to ''.
	 *                                Options: 'in', 'm', 'cm', 'm'.
	 *
	 * @return float
	 */
	function wc_get_dimension( $dimension, $to_unit, $from_unit = '' ) {
		$to_unit = strtolower( $to_unit );

		if ( empty( $from_unit ) ) {
			$from_unit = strtolower( get_option( 'woocommerce_dimension_unit' ) );
		}

		// Unify all units to cm first.
		if ( $from_unit !== $to_unit ) {
			switch ( $from_unit ) {
				case 'in':
					$dimension *= 2.54;
					break;
				case 'm':
					$dimension *= 100;
					break;
				case 'mm':
					$dimension *= 0.1;
					break;
				case 'yd':
					$dimension *= 91.44;
					break;
			}

			// Output desired unit.
			switch ( $to_unit ) {
				case 'in':
					$dimension *= 0.3937;
					break;
				case 'm':
					$dimension *= 0.01;
					break;
				case 'mm':
					$dimension *= 10;
					break;
				case 'yd':
					$dimension *= 0.010936133;
					break;
			}
		}

		return ( $dimension < 0 ) ? 0 : $dimension;
	}
}

if ( ! function_exists( 'wc_get_weight' ) ) {
	/**
	 * Normalise weights, unify to kg then convert to wanted unit value.
	 *
	 * Usage:
	 * wc_get_weight(55, 'kg');
	 * wc_get_weight(55, 'kg', 'lbs');
	 *
	 * @param int|float $weight Weight.
	 * @param string $to_unit Unit to convert to.
	 *                             Options: 'g', 'kg', 'lbs', 'oz'.
	 * @param string $from_unit Unit to convert from.
	 *                             Defaults to ''.
	 *                             Options: 'g', 'kg', 'lbs', 'oz'.
	 *
	 * @return float
	 */
	function wc_get_weight( $weight, $to_unit, $from_unit = '' ) {
		$weight  = (float) $weight;
		$to_unit = strtolower( $to_unit );

		if ( empty( $from_unit ) ) {
			$from_unit = strtolower( get_option( 'woocommerce_weight_unit' ) );
		}

		// Unify all units to kg first.
		if ( $from_unit !== $to_unit ) {
			switch ( $from_unit ) {
				case 'g':
					$weight *= 0.001;
					break;
				case 'lbs':
					$weight *= 0.453592;
					break;
				case 'oz':
					$weight *= 0.0283495;
					break;
			}

			// Output desired unit.
			switch ( $to_unit ) {
				case 'g':
					$weight *= 1000;
					break;
				case 'lbs':
					$weight *= 2.20462;
					break;
				case 'oz':
					$weight *= 35.274;
					break;
			}
		}

		return ( $weight < 0 ) ? 0 : $weight;
	}
}