<?php

namespace PortalPeople\virtualstock\helpers;

class DateTimeHelper
{
    public const API_FORMAT     = 'Y-m-d\TH:i:s\Z'; // ISO 8601 UTC as expected by VirtualStock API
    public const API_FORMAT_TZ  = \DateTimeInterface::ATOM;

    /**
     * Format a date/time value to the ISO 8601 UTC string expected by the VirtualStock API.
     *
     * Accepts a Unix timestamp (int), DateTimeInterface, or a parseable date string.
     */
    public static function toApiFormat(int|\DateTimeInterface|string $value, string $timezone = 'UTC'): string
    {
        $dt = self::toDateTime($value, $timezone);
        $dt = $dt->setTimezone(new \DateTimeZone('UTC'));
        return $dt->format(self::API_FORMAT);
    }

    /**
     * Parse an API date/time string into a DateTimeImmutable.
     * Returns null if the string is empty or unparseable.
     */
    public static function fromApiFormat(?string $value, string $timezone = 'UTC'): ?\DateTimeImmutable
    {
        if ($value === null || $value === '') {
            return null;
        }

        try {
            $dt = new \DateTimeImmutable($value, new \DateTimeZone($timezone));
            return $dt;
        } catch (\Exception) {
            return null;
        }
    }

    /**
     * Return a date string suitable for the API from "today + N days" in UTC.
     */
    public static function daysFromNow(int $days, string $timezone = 'UTC'): string
    {
        $dt = new \DateTimeImmutable('now', new \DateTimeZone($timezone));
        $dt = $dt->modify('+' . $days . ' days');
        $dt = $dt->setTimezone(new \DateTimeZone('UTC'));
        return $dt->format(self::API_FORMAT);
    }

    /**
     * Check whether an API datetime string is in the past.
     */
    public static function isPast(?string $value): bool
    {
        $dt = self::fromApiFormat($value);
        if ($dt === null) {
            return false;
        }
        return $dt < new \DateTimeImmutable('now', new \DateTimeZone('UTC'));
    }

    private static function toDateTime(int|\DateTimeInterface|string $value, string $timezone): \DateTimeImmutable
    {
        if ($value instanceof \DateTimeImmutable) {
            return $value;
        }

        if ($value instanceof \DateTime) {
            return \DateTimeImmutable::createFromMutable($value);
        }

        if (is_int($value)) {
            return new \DateTimeImmutable('@' . $value);
        }

        return new \DateTimeImmutable($value, new \DateTimeZone($timezone));
    }
}
