<?php
// 🔧 Universal UOM Converter for Width, Height & Quantity
function convertUOM($value, $from, $to) {
    if ($value === '' || $value === null) return 0;

    $from = strtolower(trim($from));
    $to   = strtolower(trim($to));

    // --- Length Conversion (m, cm, mm, inch, yd) ---
    $lengthUnits = ['m', 'cm', 'mm', 'inch', 'yd'];
    if (in_array($from, $lengthUnits) && in_array($to, $lengthUnits)) {
        // Step 1: convert to meters
        switch ($from) {
            case 'inch': $base = $value * 0.0254; break;
            case 'cm':   $base = $value * 0.01; break;
            case 'mm':   $base = $value * 0.001; break;
            case 'yd':   $base = $value * 0.9144; break;
            default:     $base = $value; // already m
        }

        // Step 2: convert from meters to target
        switch ($to) {
            case 'inch': return $base / 0.0254;
            case 'cm':   return $base / 0.01;
            case 'mm':   return $base / 0.001;
            case 'yd':   return $base / 0.9144;
            default:     return $base; // m
        }
    }

    // --- Weight Conversion (kg, ton, tonne) ---
    $weightUnits = ['kg', 'ton', 'tonne'];
    if (in_array($from, $weightUnits) && in_array($to, $weightUnits)) {
        // convert to kilograms first
        switch ($from) {
            case 'ton':
            case 'tonne':
                $base = $value * 1000; break;
            default:
                $base = $value; // kg
        }

        // convert to target
        switch ($to) {
            case 'ton':
            case 'tonne':
                return $base / 1000;
            default:
                return $base; // kg
        }
    }

    // If no match, return original
    return $value;
}
?>
