<?php

namespace App\Support;

use Carbon\Carbon;
use Carbon\CarbonInterface;
use Morilog\Jalali\Jalalian;

final class ExpenseDates
{
    public static function formatDate(CarbonInterface|string|null $value): ?string
    {
        if ($value === null || $value === '') {
            return null;
        }

        return Jalalian::fromCarbon(Carbon::parse($value))->format('Y/m/d');
    }

    public static function formatDateTime(CarbonInterface|string|null $value): ?string
    {
        if ($value === null || $value === '') {
            return null;
        }

        $carbon = Carbon::parse($value);

        return Jalalian::fromCarbon($carbon)->format('Y/m/d').' '.$carbon->format('H:i');
    }

    public static function formatDateLong(CarbonInterface|string|null $value): ?string
    {
        if ($value === null || $value === '') {
            return null;
        }

        $carbon = Carbon::parse($value);
        $jalali = Jalalian::fromCarbon($carbon);

        return $jalali->format('l، d F Y');
    }

    public static function jalaliYear(CarbonInterface|string $value): int
    {
        return Jalalian::fromCarbon(Carbon::parse($value))->getYear();
    }

    public static function jalaliYearMonth(CarbonInterface|string $value): string
    {
        $jalali = Jalalian::fromCarbon(Carbon::parse($value));

        return sprintf('%04d-%02d', $jalali->getYear(), $jalali->getMonth());
    }

    public static function formatPeriodLabel(string $periodType, string $key): string
    {
        return match ($periodType) {
            'year' => $key,
            'month' => self::formatMonthKey($key),
            default => self::formatDate($key) ?? $key,
        };
    }

    private static function formatMonthKey(string $jalaliYearMonth): string
    {
        [$year, $month] = array_pad(explode('-', $jalaliYearMonth, 2), 2, '1');
        $carbon = (new Jalalian((int) $year, (int) $month, 1))->toCarbon();

        return SalaryMonth::displayLabel($carbon);
    }
}
