<?php
class Core_Twig_Extensions_Extension_Date extends Twig_Extension
{
    /**
     * Returns a list of filters.
     *
     * @return array
     */
    public function getFilters()
    {
        return array(
            'fuzzytime'         => new Twig_Filter_Function('core_twig_string_fuzzytime'),
            'datetime'          => new Twig_Filter_Function('core_twig_string_datetime'),
            'localedate'        => new Twig_Filter_Function('core_twig_string_localedate'),
        );
    }

    /**
     * Name of this extension
     *
     * @return string
     */
    public function getName()
    {
        return 'Core_Twig_Date';
    }
}

function core_twig_string_localedate($str, $format = '%d.%m.%Y.')
{
    $timestamp = strtotime($str);
    return strftime($format, $timestamp);
}

function core_twig_string_datetime($str)
{
    return format_date($str, 'd.m.Y. H:i');
}

function core_twig_string_fuzzytime ($date, $before_string = 'prije')
{
    if (is_numeric($date)) {
        $s = time() - $date;
    } else {
        $s = time() - strtotime($date);
    }
    if ($s < 0) {
        // vrijeme je u buduÄ‡nosti, sluÄŤaj kod submitanja njuza kod kojeg provjeravamo za koliko se smije postati sljedeci njuz
        $s = abs($s);
        $before_string = 'za ';
    }
    $m = intval($s/60);
    $s = $s % 60;

    $h = intval($m/60);
    $m = $m % 60;

    $d = intval($h/24);
    $h = $h % 24;
    if ($d > 31) {
        return format_date($date);
        // retun (is_numeric($date) ? date('Y-m-d h:m', $date) : $date);
    } elseif ($d >= 1) {
        /**
        * zyt: 30.03.2007.
        * if hour is 0, just increment the hours by 1
        * The 0h:XXmin thing is kinda silly for stuff older than 1 day anyways, right?
        * At least for coolinarika?
        */
        if ($h == 0) {
            $h = $h + 1;
        }
        // return $before_string . ' ' . $d . ((preg_match('/.*1$/', $d) && !preg_match('/.*11$/', $d)) ? ' dan' : ' dana') . ', ' . $h . 'h';
        return $before_string . ' ' . $d . ((preg_match('/.*1$/', $d) && !preg_match('/.*11$/', $d)) ? ' dan' : ' dana');
    } elseif ($h > 0) {
        if ($d >= 1) {
            // return $before_string . ' ' . $d . ' dan, ' . $h . 'h:' . $m . 'min';
            return $before_string . ' ' . $d . ' dan, ' . $h . 'h';
        } else {
            // return $before_string . ' ' . $h . 'h:' . $m . 'min';
            return $before_string . ' ' . $h . 'h';
        }
    } elseif ($m > 0) {
        // return $before_string . ' ' . $m . 'min:' . $s . 'sec';
        return $before_string . ' ' . $m . 'min';
    } else {
        // return $before_string . ' ' . $s . 'sec';
        return $before_string . ' manje od minute';
    }
}