<?php

namespace App\Helpers;

class NumberToWords
{
    private static $words = [
        0 => 'Zero',
        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',
    ];

    public static function convert($number)
    {
        // Split into integer and decimal parts
        $integerPart = floor($number);
        $decimalPart = round($number - $integerPart, 2) * 100;

        // Convert the integer part
        $integerInWords = self::convertInteger($integerPart);

        // If there's a decimal part, handle it
        if ($decimalPart > 0) {
            $decimalInWords = self::convertInteger($decimalPart);
            return $integerInWords . ' and ' . $decimalInWords . ' Paise only';
        }

        return $integerInWords . ' only';
    }

    private static function convertInteger($number)
    {
        if ($number == 0) {
            return self::$words[0];
        }

        $result = '';

        // Handle Crores
        if ($number >= 10000000) {
            $crores = floor($number / 10000000);
            $result .= self::convertInteger($crores) . ' Crore ';
            $number %= 10000000;
        }

        // Handle Lakhs
        if ($number >= 100000) {
            $lakhs = floor($number / 100000);
            $result .= self::convertInteger($lakhs) . ' Lakh ';
            $number %= 100000;
        }

        // Handle Thousands
        if ($number >= 1000) {
            $thousands = floor($number / 1000);
            $result .= self::convertInteger($thousands) . ' Thousand ';
            $number %= 1000;
        }

        // Handle Hundreds
        if ($number >= 100) {
            $hundreds = floor($number / 100);
            $result .= self::$words[$hundreds] . ' Hundred ';
            $number %= 100;
        }

        // Handle Tens and Ones
        if ($number > 0) {
            if ($number <= 20) {
                $result .= self::$words[$number];
            } else {
                $tens = floor($number / 10) * 10;
                $ones = $number % 10;
                $result .= self::$words[$tens];
                if ($ones > 0) {
                    $result .= '-' . self::$words[$ones];
                }
            }
        }

        return trim($result);
    }
}
