<?php

/**
 * 05.05.2015 (20:17)
 * TheNumbers.php
 * PhpStorm
 */

error_reporting(-1);
mb_internal_encoding('utf-8');
header("Content-Type: text/plain; charset=utf-8");

/* Делает первую букву предложения заглавной */
function makeFirstLetterUppercase($input)
{
    $firstLetter = mb_substr($input, 0, 1);
    $firstLetter = mb_strtoupper($firstLetter);
    $otherLetters = mb_substr($input, 1);
    $result = $firstLetter . $otherLetters;
    return $result;
}

/* Возвращает соответствующую числу форму слова: 1 рубль, 2 рубля, 5 рублей */
function inclineWord($input)
{
    $lastSymbol = $input % 10;
    if ($lastSymbol == 1) {
        $result = ' рубль.';
    } elseif (($lastSymbol >= 2) && ($lastSymbol <= 4)) {
        $result = ' рубля.';
    } else {
        $result = ' рублей.';
    }
    return $result;
}

/**
 * Преобразует числа от 0 до 999 в текст. Параметр $isFemale равен нулю,
 * если мы считаем число для мужского рода (один рубль),
 * и 1 — для женского (одна тысяча)
 */
function smallNumberToText($input, $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 => 'две',
    );
    /* Заменим значения в массиве spelling (для женского рода) */
    if ($isFemale == 1) {
        $spelling = array_replace($spelling, $femaleSpelling);
    }

    $input = ltrim($input, 0); /* Удалим в начале все нули, если они есть */
    $flipped = array_flip($spelling); /* Поменяем ключи и значения ключей местами, чтобы использовать функцию array_search */

    if (($input >= 0) && ($input <= 20)) {
        $result = array_search($input, $flipped);
    } elseif (($input >= 21) && ($input <= 99)) {
        if ($input % 10 == 0) {
            $result = array_search($input, $flipped);
        } else {
            $singleDigits = mb_substr($input, 1, 1); /* Выделяем из числа послению цифру (число 89, то $singleDigits = 9) */
            $tens = $input - $singleDigits; /* Вычитаем из начального числа значение переменной $singleDigits (число 89 - $singleDigits, то $tens = 80) */
            $tens = array_search($tens, $flipped);
            $singleDigits = array_search($singleDigits, $flipped);
            $result = $tens . " " . $singleDigits;
        }
    } elseif (($input >= 100) && ($input <= 999)) {
        if ($input % 100 == 0) {
            $result = array_search($input, $flipped);
        } else {
            $tens = mb_substr($input, 1, 2); /* Выделяем из числа посление две цифры (число 989, то $tens = 89) */
            $hundreds = $input - $tens; /* Вычитаем из начального числа значение переменной $tens (число 989 - $tens, то $hundreds = 900) */
            $singleDigits = mb_substr($tens, 1, 1); /* Выделяем последениею цифру из перемееной $tens (число 89, то $singleDigits = 9) */
            if (($tens % 10 == 0) || (($tens >= 0) && ($tens <= 20))) {
                $hundreds = array_search($hundreds, $flipped);
                $tens = array_search($tens, $flipped);
                $result = $hundreds . " " . $tens;
            } else {
                $tens = $tens - $singleDigits;
                $hundreds = array_search($hundreds, $flipped);
                $tens = array_search($tens, $flipped);
                $singleDigits = array_search($singleDigits, $flipped);
                $result = $hundreds . " " . $tens . " " . $singleDigits;
            }
        }
    }
    return $result;
}

function numberToText($input)
{
    $thousandSpelling = array(
        '1' => 'тысяча',
        '2' => 'тысячи',
        '3' => 'тысячь',
    );

    $millionSpelling = array(
        '1' => 'миллион',
        '2' => 'миллиона',
        '3' => 'миллионов',
    );

    $lengthNum = mb_strlen($input); /* Найдем длинну числа */
    $result = '';
    if  (($lengthNum <= 8) && ($lengthNum >= 7)) {
        /* Разбиваем число */
        if ($lengthNum == 8) {
            $a = mb_substr($input, 0, 2);
            $b = mb_substr($input, 2, 3);
            $c = mb_substr($input, 5, 3);
        } elseif ($lengthNum == 7) {
            $a = mb_substr($input, 0, 1);
            $b = mb_substr($input, 1, 3);
            $c = mb_substr($input, 4, 3);
        }
        /* Преобразуем разбитые числа в текст */
        $aText = smallNumberToText($a, 0);
        $bText = smallNumberToText($b, 1);
        $cText = smallNumberToText($c, 0);
        /* Преобразуем миллионы в текст */
        $millions = '';
        if (($a >= 11) && ($a <= 14)) {
            $millions .= $aText . " " . $millionSpelling[3] . " " . $bText;
        } else {
            $lastDigits = $a % 10;
            if ($lastDigits == 1) {
                $millions .= $aText . " " . $millionSpelling[1] . " " . $bText;
            } elseif (($lastDigits >= 2) && ($lastDigits <= 4)) {
                $millions .= $aText . " " . $millionSpelling[2] . " " . $bText;
            } else {
                $millions .= $aText . " " . $millionSpelling[3] . " " . $bText;
            }
        }
        /* Преобразуем тысячи в текст */
        $b = $b % 10;
        if ($b == 1) {
            $thousand = $thousandSpelling[1];
        } elseif (($b > 1) && ($b <= 4)) {
            $thousand = $thousandSpelling[2];
        } else {
            $thousand = $thousandSpelling[3];
        }
        /* Соединяем миллионы и тысячи */
        $result = $millions . " " . $thousand . " " . $cText;
    } elseif (($lengthNum <= 6) && ($lengthNum >= 4)) {
        /* Разбиваем число */
        if ($lengthNum == 6) {
            $a = mb_substr($input, 0, 3);
            $b = mb_substr($input, 3, 3);
        } elseif ($lengthNum == 5) {
            $a = mb_substr($input, 0, 2);
            $b = mb_substr($input, 2, 3);
        } elseif ($lengthNum == 4) {
            $a = mb_substr($input, 0, 1);
            $b = mb_substr($input, 1, 3);
        }
        /* Преобразуем разбитые числа в текст */
        $aText = smallNumberToText($a, 1);
        $bText = smallNumberToText($b, 0);
        /* Преобразуем тысячи в текст */
        if ($a % 10 == 1) {
            $thousand = $thousandSpelling[1];
        } elseif (($a % 10 > 1) && ($a % 10 <= 4)) {
            $thousand = $thousandSpelling[2];
        } else {
            $thousand = $thousandSpelling[3];
        }
        /* Соединяем тысячи и сотни */
        $result = $aText . " " . $thousand . " " . $bText;
    } elseif ($lengthNum <= 3) {
        $result = smallNumberToText($input, 0);
    }
    $result = makeFirstLetterUppercase($result);
    $ending = inclineWord($input);
    $result .= $ending;
    return $result;
}

$amount = 11011011;
$text = numberToText($amount);
echo "На вашем счету: {$text} ({$amount})\n";

$amount = mt_rand(1000, 9999);
$text = numberToText($amount);
echo "На вашем счету: {$text} ({$amount})\n";

$amount = mt_rand(10000, 99999);
$text = numberToText($amount);
echo "На вашем счету: {$text} ({$amount})\n";

$amount = mt_rand(100000, 999999);
$text = numberToText($amount);
echo "На вашем счету: {$text} ({$amount})\n";

$amount = mt_rand(1000000, 9999999);
$text = numberToText($amount);
echo "На вашем счету: {$text} ({$amount})\n";

$amount = mt_rand(10000000, 99999999);
$text = numberToText($amount);
echo "На вашем счету: {$text} ({$amount})\n";