<?php

namespace Autogedal\Labels\Model;

use Magento\Framework\Stdlib\DateTime\TimezoneInterface;

class DateWindowMatcher
{
    private $timezone;

    public function __construct(TimezoneInterface $timezone)
    {
        $this->timezone = $timezone;
    }

    public function isCurrentWithin(?string $fromValue, ?string $toValue, ?\DateTimeInterface $now = null): bool
    {
        $from = $this->createDate($fromValue, false);
        $to = $this->createDate($toValue, true);
        $current = $now ? $this->timezone->date($now) : $this->timezone->date();

        if ($from && $current < $from) {
            return false;
        }

        if ($to && $current > $to) {
            return false;
        }

        return $from !== null || $to !== null;
    }

    public function createDate($value, bool $isEndDate): ?\DateTime
    {
        if ($value === null || $value === '') {
            return null;
        }

        if (is_string($value)) {
            $value = $this->normalizeBoundaryString($value, $isEndDate);
            return new \DateTime($value);
        }

        return $this->timezone->date($value);
    }

    private function normalizeBoundaryString(string $value, bool $isEndDate): string
    {
        $value = trim($value);
        if (!$isEndDate) {
            return $value;
        }

        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
            return $value . ' 23:59:59';
        }

        if (substr($value, -8) === '00:00:00') {
            return substr($value, 0, -8) . '23:59:59';
        }

        return $value;
    }
}
