<?php

declare(strict_types=1);

namespace Core\General\Helper;

use Carbon\Carbon;

class DateTimeHelper
{
    public const YMDHIS = 'Y-m-d H:i:s';
    public const HIS = 'H:i:s';
    public const YMD = 'Y-m-d';
    public const ISO8601 = 'Y-m-d\TH:i:sP';

    public const VALID_FORMATS = [
        self::HIS,
        self::ISO8601,
        self::YMD,
        self::YMDHIS,
    ];

    public const DEFAULT_FORMAT = self::ISO8601;

    public static function buildCarbonObject(mixed $dateTime, ?string $format = null): Carbon|false
    {
        if (!\is_string($dateTime)) {
            return false;
        }

        if ($format !== null) {
            if (!\in_array($format, self::VALID_FORMATS)) {
                return false;
            }
            $dateTime = \DateTime::createFromFormat($format, $dateTime);
            if ($dateTime instanceof \DateTime) {
                return Carbon::instance($dateTime);
            }

            return false;
        }

        $dateTime = \DateTime::createFromFormat(self::DEFAULT_FORMAT, $dateTime);
        if ($dateTime instanceof \DateTime) {
            return Carbon::instance($dateTime);
        }

        return false;
    }
}
