<?php

namespace App\Support;

use Carbon\CarbonInterface;

class LeadContactDeadline
{
    private const WORKING_DAY_START_HOUR = 9;

    private const WORKING_DAY_END_HOUR = 16;

    private const WORKING_DAY_END_MINUTE = 45;

    public static function for(CarbonInterface $leadCreatedAt): CarbonInterface
    {
        $minutesSinceMidnight = ($leadCreatedAt->hour * 60) + $leadCreatedAt->minute;
        $workingDayStartsAt = self::WORKING_DAY_START_HOUR * 60;
        $workingDayEndsAt = (self::WORKING_DAY_END_HOUR * 60) + self::WORKING_DAY_END_MINUTE;

        if ($leadCreatedAt->isWeekday()
            && $minutesSinceMidnight >= $workingDayStartsAt
            && $minutesSinceMidnight < $workingDayEndsAt) {
            return $leadCreatedAt->copy()->addMinutes(15);
        }

        $nextContactWindow = $leadCreatedAt->copy()->setTime(self::WORKING_DAY_START_HOUR, 0);

        // Before 9am on a weekday, today's window is the next one. After
        // 4:45pm, or at any time during a weekend, move to the next weekday.
        if ($leadCreatedAt->isWeekend() || $minutesSinceMidnight >= $workingDayEndsAt) {
            $nextContactWindow = $nextContactWindow->addDay();
        }

        while ($nextContactWindow->isWeekend()) {
            $nextContactWindow = $nextContactWindow->addDay();
        }

        return $nextContactWindow->addMinutes(30);
    }
}
