<?php

namespace App\Helpers;

setlocale(LC_ALL, 'nl_NL'); 
date_default_timezone_set('Europe/Amsterdam');
define('ONE_DAY', 86400);

class FormatterHelper
{
    private static $weekdays = ["Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"];
    private static $months = ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"];

    public static function fullDate(/*\DateTime or \DateTimeImmutable*/ $date, $format)
    {
        $weekday = self::$weekdays[$date->format('N') - 1];
        $month = $date->format('m') - 1;
        $year = $date->format('Y');
	return str_replace(['d', 'M', 'm', 'y?', 'y', 'W', 'w'],
          [$date->format('d'), ($month < 9 ? "0" : "") . ($month + 1), self::$months[$month], $year == date('Y') ? "" : $year, $year, $weekday, strtolower($weekday)],
          $format);
    }

    public static function relativeDate($date, $capitalize = true, $fullFormat = 'W d m y?')
    {
        $today = strtotime("00:00");
        $timestamp = $date->getTimestamp();
        
        if($timestamp == 0) 
        {
          return $capitalize ? "Nooit" : "nooit";
        } 

        if($timestamp >= $today + 2 * ONE_DAY && $timestamp < $today + 7 * ONE_DAY) 
        {
          return ($capitalize ? "Aanstaande" : "aanstaande") . " " . strtolower(self::$weekdays[$date->format('N') - 1]);
        }

        if($timestamp >= $today + ONE_DAY && $timestamp < $today + 2 * ONE_DAY)
        {
          return $capitalize ? "Morgen" : "morgen";
        }

        if($timestamp >= $today && $timestamp < $today + ONE_DAY) 
        { 
          return $capitalize ? "Vandaag" : "vandaag";
        }
      
        if($timestamp >= $today - ONE_DAY && $timestamp < $today + ONE_DAY) 
        {
            return $capitalize ? "Gisteren" : "gisteren";
        } 
    
        if($timestamp >= $today - 6 * ONE_DAY && $timestamp < $today + ONE_DAY) 
        {
          return ($capitalize ? "Afgelopen" : "afgelopen") . " " . strtolower(self::$weekdays[$date->format('N') - 1]);
        }
    
        return self::fullDate($date, $fullFormat);
    }

    public static function excerpt($text, $maxLength)
    {
	$allowed = '<mark>';
        if(strlen($text) < $maxLength) 
        {
            return $text;
        }
  
        $matches = [];
        if(preg_match('/\W/', $text, $matches, PREG_OFFSET_CAPTURE, $maxLength)) 
        {
          return substr(strip_tags($text, $allowed), 0, $matches[0][1]) . "...";
        } 
    
        return substr(strip_tags($text, $allowed), $maxLength) . "...";
    }
}
/*
function formatFullDate($date, $includeWeekday) {
}
*/
