<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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;
    }
}
