<?php

namespace CouponsPlus\App\Conditions\BuiltIn\Conditions\Time;

use Carbon\Carbon;
use CouponsPlus\App\Conditions\BuiltIn\Conditions\Time\Abilities\CheckableTime;

class HoursAndMinutesRangeChecker implements CheckableTime
{
    /**
     * @var string 'HH:MM'
     */
    protected string $start;
    /**
     * @var string 'HH:MM'
     */
    protected string $end;

    public function __construct(string $start, string $end)
    {
        $this->start = $start;
        $this->end = $end;
    }

    public function matches(Carbon $date): bool
    {
        $startTime = $this->parseTime($this->start);
        $endTime = $this->parseTime($this->end);

        $currentMinutes = $date->hour * 60 + $date->minute;

        // Handle same day range
        if ($startTime <= $endTime) {
            return $currentMinutes >= $startTime && $currentMinutes <= $endTime;
        }

        // Handle overnight range (crosses midnight)
        return $currentMinutes >= $startTime || $currentMinutes <= $endTime;
    }

    /**
     * Parse time string 'HH:MM' to minutes since midnight
     */
    private function parseTime(string $time): int
    {
        [$hours, $minutes] = explode(':', $time);
        return (int)$hours * 60 + (int)$minutes;
    }
}