<?php

namespace Ig\IgReservations\Utility;

class EventUtility
{
    public static function intToTime($seconds)
    {
        $hours = floor($seconds / 3600);
        $minutes = round($seconds / 60) % 60;
        return sprintf('%02d:%02d:00', $hours, $minutes);
    }

    public static function getStartDateTimeWithBuffer($startDateTime, $calendar)
    {
        $startDate = clone $startDateTime;
        $timeslotStartTime = $calendar->getTimeslotStartTime();
        $timeslotBuffer = $calendar->getTimeslotBuffer();

        if ($timeslotBuffer) {
            $startDateTime->modify('-' . $timeslotBuffer);
            $timeslotStartTime = self::intToTime($calendar->getTimeslotStartTime());
            $timeslotStartDateTime = new \DateTime($startDate->format('Y-m-d') . 'T' . $timeslotStartTime);

            if ($startDateTime < $timeslotStartDateTime) {
                $startDateTime = $timeslotStartDateTime;
            }
        }

        return $startDateTime;
    }

    public static function getEndDateTimeWithBuffer($startDateTime, $endDateTime, $calendar)
    {
        $startDate = clone $startDateTime;
        $endDate = clone $endDateTime;
        $timeslotBuffer = $calendar->getTimeslotBuffer();

        $startDateString = $startDateTime->format('Y-m-d');
        $endDateString = $endDateTime->format('Y-m-d');

        if ($timeslotBuffer) {
            $endDateTime->modify($timeslotBuffer);

            if ($startDateString == $endDateString) {
                $timeslotEndTime = self::intToTime($calendar->getTimeslotEndTime());
                $timeslotEndDateTime = new \DateTime($startDate->format('Y-m-d') . 'T' . $timeslotEndTime);

                if ($endDateTime > $timeslotEndDateTime) {
                    $endDateTime = $timeslotEndDateTime;
                }
            } else {
                $timeslotStartTime = self::intToTime($calendar->getTimeslotStartTime());
                $timeslotStartDateTime = new \DateTime($endDate->format('Y-m-d') . 'T' . $timeslotStartTime);

                if ($endDateTime < $timeslotStartDateTime) {
                    $endDateTime = $timeslotStartDateTime;
                } else {
                    $timeslotEndTime = self::intToTime($calendar->getTimeslotEndTime());
                    $timeslotEndDateTime = new \DateTime($endDate->format('Y-m-d') . 'T' . $timeslotEndTime);

                    if ($endDateTime > $timeslotEndDateTime) {
                        $endDateTime = $timeslotEndDateTime;
                    }
                }
            }
        }

        return $endDateTime;
    }
}
