<?php

namespace App\Helpers;

class NumberToWords
{
    private static $units = [
        '', 'UN', 'DEUX', 'TROIS', 'QUATRE', 'CINQ', 'SIX', 'SEPT', 'HUIT', 'NEUF',
        'DIX', 'ONZE', 'DOUZE', 'TREIZE', 'QUATORZE', 'QUINZE', 'SEIZE', 'DIX-SEPT', 'DIX-HUIT', 'DIX-NEUF'
    ];

    private static $tens = [
        '', '', 'VINGT', 'TRENTE', 'QUARANTE', 'CINQUANTE', 'SOIXANTE', 'SOIXANTE', 'QUATRE-VINGT', 'QUATRE-VINGT'
    ];

    public static function convert($number)
    {
        $number = round($number, 2);
        $dirhams = floor($number);
        $centimes = round(($number - $dirhams) * 100);

        $result = '';
        
        if ($dirhams == 0) {
            $result = 'ZÉRO DIRHAM';
        } else {
            $result = self::convertInteger($dirhams) . ' DIRHAM' . ($dirhams > 1 ? 'S' : '');
        }

        if ($centimes > 0) {
            $result .= ' ET ' . self::convertInteger($centimes) . ' CENTIME' . ($centimes > 1 ? 'S' : '');
        }

        return $result;
    }

    private static function convertInteger($number)
    {
        if ($number == 0) return '';
        if ($number < 20) return self::$units[$number];
        if ($number < 100) {
            $tens = intval($number / 10);
            $units = $number % 10;
            
            if ($tens == 7) return 'SOIXANTE-' . self::$units[10 + $units];
            if ($tens == 9) return 'QUATRE-VINGT-' . self::$units[10 + $units];
            
            return self::$tens[$tens] . ($units > 0 ? '-' . self::$units[$units] : '');
        }
        if ($number < 1000) {
            $hundreds = intval($number / 100);
            $remainder = $number % 100;
            $result = ($hundreds == 1 ? 'CENT' : self::$units[$hundreds] . ' CENT');
            if ($remainder > 0) $result .= ' ' . self::convertInteger($remainder);
            return $result;
        }
        if ($number < 1000000) {
            $thousands = intval($number / 1000);
            $remainder = $number % 1000;
            $result = ($thousands == 1 ? 'MILLE' : self::convertInteger($thousands) . ' MILLE');
            if ($remainder > 0) $result .= ' ' . self::convertInteger($remainder);
            return $result;
        }
        
        return 'NOMBRE TROP GRAND';
    }
}