<?php

namespace SpaethTech\UCRM\SDK\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class TimeDiffExtension extends AbstractExtension
{
  public function getFilters(): array
  {
    return [
      new TwigFilter('time_diff', [$this, 'timeDiff']),
    ];
  }

  public function timeDiff(string $date): string
  {
    $now = new \DateTime();
    $target = new \DateTime($date);
    $diff = $now->diff($target);

    if ($diff->days == 0) {
      if ($diff->h == 0) {
        return $diff->i == 1 ? '1 minute ago' : $diff->i . ' minutes ago';
      }
      return $diff->h == 1 ? '1 hour ago' : $diff->h . ' hours ago';
    } elseif ($diff->days == 1) {
      return '1 day ago';
    } elseif ($diff->days < 7) {
      return $diff->days . ' days ago';
    } elseif ($diff->days < 30) {
      $weeks = floor($diff->days / 7);
      return $weeks == 1 ? '1 week ago' : $weeks . ' weeks ago';
    } elseif ($diff->days < 365) {
      $months = floor($diff->days / 30);
      return $months == 1 ? '1 month ago' : $months . ' months ago';
    } else {
      $years = floor($diff->days / 365);
      return $years == 1 ? '1 year ago' : $years . ' years ago';
    }
  }
}