<?php
function normalizeMeasurementUnit($unit) {
    $unit = strtolower(trim((string)$unit));

    $aliases = [
        'kgs' => 'kg',
        'kilogram' => 'kg',
        'kilograms' => 'kg',
        'gram' => 'g',
        'grams' => 'g',
        'litre' => 'liter',
        'litres' => 'liter',
        'liters' => 'liter',
        'l' => 'liter',
        'ltr' => 'liter',
        'milliliter' => 'ml',
        'milliliters' => 'ml',
        'millilitre' => 'ml',
        'millilitres' => 'ml',
        'pcs' => 'pieces',
        'piece' => 'pieces',
    ];

    return $aliases[$unit] ?? $unit;
}

function convertMeasurementQuantity($quantity, $fromUnit, $toUnit) {
    $quantity = (float)$quantity;
    $fromUnit = normalizeMeasurementUnit($fromUnit);
    $toUnit = normalizeMeasurementUnit($toUnit);

    if ($fromUnit === $toUnit) {
        return $quantity;
    }

    $massUnits = ['kg' => 1000, 'g' => 1];
    $volumeUnits = ['liter' => 1000, 'ml' => 1];
    $countUnits = ['dozen' => 12, 'pieces' => 1];

    if (isset($massUnits[$fromUnit], $massUnits[$toUnit])) {
        return ($quantity * $massUnits[$fromUnit]) / $massUnits[$toUnit];
    }

    if (isset($volumeUnits[$fromUnit], $volumeUnits[$toUnit])) {
        return ($quantity * $volumeUnits[$fromUnit]) / $volumeUnits[$toUnit];
    }

    if (isset($countUnits[$fromUnit], $countUnits[$toUnit])) {
        return ($quantity * $countUnits[$fromUnit]) / $countUnits[$toUnit];
    }

    return null;
}

function calculateIngredientAvailability($currentStock, $ingredientUnit, $requiredQuantity, $requiredUnit) {
    $currentStock = (float)$currentStock;
    $requiredQuantity = (float)$requiredQuantity;
    $ingredientUnit = normalizeMeasurementUnit($ingredientUnit);
    $requiredUnit = normalizeMeasurementUnit($requiredUnit);

    $requiredInIngredientUnit = convertMeasurementQuantity($requiredQuantity, $requiredUnit, $ingredientUnit);
    $unitsConvertible = $requiredInIngredientUnit !== null;

    if (!$unitsConvertible) {
        $requiredInIngredientUnit = $requiredQuantity;
    }

    return [
        'ingredient_unit' => $ingredientUnit,
        'required_unit' => $requiredUnit,
        'required_quantity_original' => $requiredQuantity,
        'required_quantity_in_stock_unit' => $requiredInIngredientUnit,
        'current_stock' => $currentStock,
        'in_stock' => $currentStock >= $requiredInIngredientUnit,
        'shortage_amount' => max(0, $requiredInIngredientUnit - $currentStock),
        'units_convertible' => $unitsConvertible
    ];
}
