<?php

namespace Mautic\CoreBundle\Helper\Chart;

use DateTimeInterface;

trait DateRangeUnitTrait
{
    /**
     * Returns appropriate time unit from a date range so the line/bar charts won't be too full/empty.
     *
     * @return string
     */
    public function getTimeUnitFromDateRange(DateTimeInterface $dateFrom, DateTimeInterface $dateTo)
    {
        $dayDiff = $dateTo->diff($dateFrom)->format('%a');
        $unit    = 'd';

        if ($dayDiff <= 1) {
            $unit = 'H';

            $sameDay    = $dateTo->format('d') === $dateFrom->format('d');
            $hourDiff   = $dateTo->diff($dateFrom)->format('%h');
            $minuteDiff = $dateTo->diff($dateFrom)->format('%i');
            if ($sameDay && !intval($hourDiff) && intval($minuteDiff)) {
                $unit = 'i';
            }
            $secondDiff = $dateTo->diff($dateFrom)->format('%s');
            if (!intval($minuteDiff) && intval($secondDiff)) {
                $unit = 'i';
            }
        }
        if ($dayDiff > 31) {
            $unit = 'W';
        }
        if ($dayDiff > 100) {
            $unit = 'm';
        }
        if ($dayDiff > 1000) {
            $unit = 'Y';
        }

        return $unit;
    }
}
