<?php

// Staring straight up into the sky ... oh my my
error_reporting(-1);
mb_internal_encoding('utf-8');
header("Content-Type: text/plain; charset=UTF-8");

/* Возвращает соответствующую числу форму слова: 1 рубль, 2 рубля, 5 рублей */
function inclineWord($number, $word1, $word2, $word5) {
    $numLastDigits = $number % 100;
    if (!($numLastDigits > 10 && $numLastDigits < 20)) {
        if (($numLastDigits % 10) == 1) {
            return $word1;
        } elseif (($numLastDigits % 10) > 1 && ($numLastDigits % 10) < 5) {
            return $word2;
        } else {
            return $word5;
        }
    } else {
        return $word5;
    }
}

/* 
    Преобразует числа от 0 до 999 в текст. Параметр $isFemale равен нулю, 
    если мы считаем число для мужского рода (один рубль), 
    и 1 — для женского (одна тысяча) 
*/
function smallNumberToText($number, $isFemale) {

    $spelling = array(
        0   =>  'ноль',                                     10  =>  'десять',       100 =>  'сто',
        1   =>  'один',         11  =>  'одиннадцать',      20  =>  'двадцать',     200 =>  'двести',
        2   =>  'два',          12  =>  'двенадцать',       30  =>  'тридцать',     300 =>  'триста',
        3   =>  'три',          13  =>  'тринадцать',       40  =>  'сорок',        400 =>  'четыреста',
        4   =>  'четыре',       14  =>  'четырнадцать',     50  =>  'пятьдесят',    500 =>  'пятьсот',
        5   =>  'пять',         15  =>  'пятнадцать',       60  =>  'шестьдесят',   600 =>  'шестьсот',
        6   =>  'шесть',        16  =>  'шестнадцать',      70  =>  'семьдесят',    700 =>  'семьсот',    
        7   =>  'семь',         17  =>  'семнадцать',       80  =>  'восемьдесят',   800 =>  'восемьсот',
        8   =>  'восемь',       18  =>  'восемнадцать',     90  =>  'девяносто',     900 =>  'девятьсот',
        9   =>  'девять',       19  =>  'девятнадцать'    
    );
    
    $femaleSpelling = array(
        1   =>  'одна',        2   =>  'две'
    );

    $number = intval($number);

    $result = array();

    if ($number == 0) {
        return $spelling[0];
    }

    if ($number < 20) {
        if ($isFemale && $number <= 2) {
        $result[] = $femaleSpelling[$number];
        } else {
        $result[] = $spelling[$number];
        }
    } else {
            $numberLastDigit = $number % 10;
            $numberTens = $number % 100;

            $numberTensRound = $numberTens - $numberLastDigit;
            $numberHunsRound = $number - $numberTens;

        if ($number >= 20 && $number < 100) {
            $result[] = $spelling[$numberTensRound];

            if ($numberLastDigit != 0) {
                if ($isFemale && $numberLastDigit <= 2) {
                $result[] = $femaleSpelling[$numberLastDigit];
                } else {
                $result[] = $spelling[$numberLastDigit];
                }
            }   
        } elseif ($number >= 100) {
            $result[] = $spelling[$numberHunsRound];
            if ($numberTens != 0 ) {
                if ($numberTens < 20 || ($numberTens % 10) == 0) {
                    $result[] = $spelling[$numberTens];
                } else {
                    $result[] = $spelling[$numberTensRound];
                    if ($isFemale && $numberLastDigit <= 2) {
                    $result[] = $femaleSpelling[$numberLastDigit];
                    } else {
                    $result[] = $spelling[$numberLastDigit];
                    }  
                }
            }
        }
    }
    $result = implode(" ", $result);
    return $result;
}

function numberToText($number) {
    $number = number_format($number);
    $numberSplit = preg_split('/,/', $number);

    $i = count($numberSplit);

    $result = array();

    foreach($numberSplit as $num) {
        $fem = 0;
        if ($i == 3) {
            $add = inclineWord($num, "миллион", "миллиона", "миллионов");
        } elseif ($i == 2) {
            $fem = 1;
            $add = inclineWord($num, "тысяча", "тысячи", "тысяч");
        } else {
            $add = "($number) " . inclineWord($num, "рубль", "рубля", "рублей");
        }

        $i--;

        $result[] = smallNumberToText($num, $fem) . " $add";


    }
    $result = implode(" ", $result);
    return $result;
}

/* Вызовем функцию несколько раз */
$amount1 = mt_rand(1,99999999);
$text1 = numberToText($amount1);

echo "На вашем счету {$text1}\n";

$amount2 = mt_rand(1,99999999);
$text2 = numberToText($amount2);

echo "На вашем счету {$text2}\n";

$amount3 = mt_rand(1,99999999);
$text3 = numberToText($amount3);

echo "На вашем счету {$text3}\n";

$amount4 = mt_rand(1,99999999);
$text4 = numberToText($amount4);

echo "На вашем счету {$text4}\n";

echo numberToText(0);