<?php

declare(strict_types=1);

namespace Macopedia\OrlenShipping\Model\Api;

use Exception;
use Macopedia\OrlenShipping\Helper\Data;
use DateTime;

class Pickup
{
    /**
     * @param Client $client
     * @param Data $helper
     */
    public function __construct(
        protected readonly Client $client,
        protected readonly Data $helper
    ) {
    }

    /**
     * Get available windows
     *
     * @return array
     * @throws OrlenApiException
     * @throws Exception
     */
    public function getAvailableWindows(): array
    {
        $params = [
            'PartnerID' => $this->helper->getPartnerId(),
            'PartnerKey' => $this->helper->getPartnerKey(),
            'PostCode' => $this->helper->getAddressPostcode()
        ];

        $availablePickupWindows = $this->client->getAvailablePickupWindows($params);

        return $this->calculatePickupTimes($availablePickupWindows->AvailablePickupDay);
    }

    /**
     *  Calculate pickup time windows
     *
     * @param array $availablePickupWindows
     * @return array
     * @throws Exception
     */
    protected function calculatePickupTimes(array $availablePickupWindows): array
    {
        $result = [];
        $now = new DateTime();

        foreach ($availablePickupWindows as $window) {
            $date = $window->Date;
            $minReadyDate = new DateTime($window->MinReadyDate);
            $maxPickupDate = new DateTime($window->MaxPickupDate);
            $minimumIntervalMinutes = (int) $window->MinimumInterval;

            $latestStartTime = clone $maxPickupDate;
            $latestStartTime->modify("-{$minimumIntervalMinutes} minutes");

            $currentStart = clone $minReadyDate;

            while ($currentStart <= $latestStartTime) {
                $currentEnd = clone $currentStart;
                $currentEnd->modify("+{$minimumIntervalMinutes} minutes");

                if ($currentEnd > $maxPickupDate) {
                    break;
                }

                if ($now->format('Y-m-d') === $date && $now >= $currentStart) {
                    $currentStart = $currentEnd;
                    continue;
                }

                $result[$date][] = $currentStart->format('H:i') . '-' . $currentEnd->format('H:i');
                $currentStart = $currentEnd;
            }
        }

        return $result;
    }
}
