<?php

use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Contexts;

/**
 * Smarty {format_date_locale_pretty} modifier.
 *
 * @param      $date        DateTime|string Date to format
 * @param null $format      Format to use - in ICU style http://www.icu-project.org/apiref/icu4c/classSimpleDateFormat.html#details
 * @param null $locale      string Locale to use. Ef empty, use current locale
 * @param null $prepend_day
 *
 * @return string
 */
function smarty_modifier_format_date_locale_pretty($date, $format = null, $locale = null, $prepend_day = null)
{
    if (!$date) {
        return '';
    }

    if (empty($locale)) {
        $language = Contexts::get(LanguageContext::class)->getActive();
        $locale = $language->getLocale() ?: $language->getId();
    }

    if ($locale == 'czech') {
        $locale = 'cs';
    }

    if (!($date instanceof DateTime)) {
        $new_date = DateTime::createFromFormat('Y-m-d H:i:s', $date);
        if (!$new_date) {
            $php_format = Settings::getDateFormat().' '.Settings::getTimeFormat();
            $new_date = DateTime::createFromFormat($php_format, $date);
        }
        $date = $new_date;
    }

    $today = new DateTime('midnight');
    $tomorrow = new DateTime('+1 day midnight');
    $dayAfterTomorrow = new DateTime('+2 day midnight');

    if ($date > $today && $date < $tomorrow) {
        return translate('today', 'datetime');
    }

    if ($date > $tomorrow && $date < $dayAfterTomorrow) {
        return translate('tomorrow', 'datetime');
    }

    if ($prepend_day && ($locale == 'cs' || $locale == 'cs_CZ') && strpos($format, 'eee') === false) {
        $days = ['v pondělí', 'v úterý', 've středu', 've čtvrtek', 'v pátek', 'v sobotu', 'v neděli'];
        $day_number = IntlDateFormatter::formatObject($date, 'e', $locale);
        $day_name = $days[$day_number - 1];

        return $day_name.' '.IntlDateFormatter::formatObject($date, $format, $locale);
    }

    return IntlDateFormatter::formatObject($date, $format, $locale);
}
