<?php

declare(strict_types=1);

namespace App\Support;

use App\Models\DberpCustomer;
use App\Models\DberpSalesOrder;
use Carbon\Carbon;
use Filament\Schemas\Components\Utilities\Get;

final class DberpSalesOrderFormSupport
{
    public static function formatProjectedDueDate(Get $get, ?DberpSalesOrder $record): ?string
    {
        $businessTime = $get('business_time') ?? $record?->business_time;

        if ($businessTime === null || $businessTime === '') {
            return null;
        }

        $paymentTermDays = self::resolvePaymentTermDays($get, $record);

        try {
            return Carbon::parse((string) $businessTime)
                ->startOfDay()
                ->addDays($paymentTermDays)
                ->toDateString();
        } catch (\Throwable) {
            return null;
        }
    }

    public static function resolvePaymentTermDays(Get $get, ?DberpSalesOrder $record): int
    {
        $raw = $get('payment_term_days');

        if ($raw !== null && $raw !== '') {
            return max(0, (int) $raw);
        }

        if ($record?->payment_term_days !== null) {
            return max(0, (int) $record->payment_term_days);
        }

        $customerId = (int) ($get('customer_id') ?? $record?->customer_id ?? 0);

        if ($customerId <= 0) {
            return 0;
        }

        $default = DberpCustomer::query()->whereKey($customerId)->value('default_payment_term_days');

        return $default !== null ? max(0, (int) $default) : 0;
    }
}
