<?php
// app/Helpers/NumberHelper.php

function numberToWords($number)
{
    // Convert the number to a string to avoid null or non-string issues in strpos
    $number = (string)$number;
    $words = '';

    // Check if the number is a float
    if (strpos($number, '.') !== false) {
        list($integerPart, $decimalPart) = explode('.', $number);
        $words = convertToWords($integerPart) . ' and ' . convertToWords($decimalPart) . ' paise';
    } else {
        $words = convertToWords($number);
    }

    return $words;
}

function convertToWords($number)
{
    $words = array(
        0 => '', 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six', 
        7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten', 11 => 'eleven', 12 => 'twelve', 
        13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen', 
        18 => 'eighteen', 19 => 'nineteen', 20 => 'twenty', 30 => 'thirty', 40 => 'forty', 
        50 => 'fifty', 60 => 'sixty', 70 => 'seventy', 80 => 'eighty', 90 => 'ninety'
    );

    $units = ['', 'thousand', 'million', 'billion'];

    if ($number == 0) {
        return 'zero';
    }

    $result = '';
    $unitIndex = 0;

    while ($number > 0) {
        $chunk = $number % 1000;
        if ($chunk > 0) {
            $result = convertThreeDigits($chunk, $words) . ' ' . $units[$unitIndex] . ' ' . $result;
        }
        $number = (int) ($number / 1000);
        $unitIndex++;
    }

    return trim($result);
}

function convertThreeDigits($number, $words)
{
    $hundreds = (int) ($number / 100);
    $remainder = $number % 100;
    $result = '';

    if ($hundreds > 0) {
        $result .= $words[$hundreds] . ' hundred ';
    }

    if ($remainder > 0) {
        if ($remainder < 20) {
            $result .= $words[$remainder];
        } else {
            $tens = (int) ($remainder / 10) * 10;
            $ones = $remainder % 10;
            $result .= $words[$tens] . ' ' . $words[$ones];
        }
    }

    return trim($result);
}
