<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Terbilang Helper
 *
 * @package	CodeIgniter
 * @subpackage	Helpers
 * @category	Helpers
 * @author	Gede Lumbung
 * @link	http://gedelumbung.com
 */

if (!function_exists('number_to_words')) {
    function number_to_words($number)
    {
        $before_comma = trim(to_word($number));
        $after_comma = trim(comma($number));
        return ucwords($results = $before_comma . ' koma ' . $after_comma);
        return ucwords($results = $before_comma);
    }

    function number_ke_words($number)
    {
        $before_comma = trim(to_word($number));
        //$after_comma = trim(comma($number));
        //return ucwords($results = $before_comma . ' koma ' . $after_comma);
        return ucwords($results = $before_comma);
    }

    function to_word($number)
    {
        $words = "";
        $arr_number = array(
            "nol",
            "satu",
            "dua",
            "tiga",
            "empat",
            "lima",
            "enam",
            "tujuh",
            "delapan",
            "sembilan",
        );

        if ($number < 10) {
            $words = " " . $arr_number[$number];
        } else if ($number < 100) {
            $words = to_word($number / 10) . to_word($number % 10);
            //$words = to_word($number / 10) . " puluh " . to_word($number % 10);
        } else if ($number < 200) {
            $words = "seratus " . to_word($number - 100);
        } else if ($number < 1000) {
            $words = to_word($number / 100) . " ratus " . to_word($number % 100);
        } else if ($number < 2000) {
            $words = "seribu " . to_word($number - 1000);
        } else if ($number < 1000000) {
            $words = to_word($number / 1000) . " ribu " . to_word($number % 1000);
        } else if ($number < 1000000000) {
            $words = to_word($number / 1000000) . " juta " . to_word($number % 1000000);
        } else {
            $words = "undefined";
        }
        return $words;
    }

    function comma($number)
    {
        $after_comma = stristr($number, '.');
        $arr_number = array(
            "nol",
            "satu",
            "dua",
            "tiga",
            "empat",
            "lima",
            "enam",
            "tujuh",
            "delapan",
            "sembilan"
        );

        $results = "";
        $length = strlen($after_comma);
        $i = 1;
        if ($i < $length) {
            $get = substr($after_comma, $i, 1);
            $results .= " " . $arr_number[$get];
            $i++;
        } else {
            $get = substr($after_comma, $i, 1);
            $results .= " " . $arr_number[$get];
            $i++;
        }
        return $results;
    }
}
