<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpPurchaseReturns\Pages;

use App\Business\Purchase\PurchaseReturnReferenceDefaultsResolver;
use App\Filament\Resources\DberpPurchaseReturns\DberpPurchaseReturnResource;
use App\Filament\Resources\Pages\CreateRecord;
use App\Models\DberpPurchaseOrder;
use App\Models\DberpPurchaseReceiptOrder;
use Filament\Notifications\Notification;

class CreateDberpPurchaseReturn extends CreateRecord
{
    protected static string $resource = DberpPurchaseReturnResource::class;

    public function mount(): void
    {
        parent::mount();

        $resolver = app(PurchaseReturnReferenceDefaultsResolver::class);
        $receiptId = request()->integer('purchase_receipt_order_id');

        if ($receiptId > 0) {
            $receipt = DberpPurchaseReceiptOrder::query()->find($receiptId);

            if ($receipt instanceof DberpPurchaseReceiptOrder) {
                $this->form->fill(array_merge(
                    ['business_time' => now()],
                    $resolver->resolveFromPurchaseReceipt($receipt),
                ));

                return;
            }
        }

        $purchaseOrderId = request()->integer('purchase_order_id');

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

        $order = DberpPurchaseOrder::query()->with('items')->find($purchaseOrderId);

        if (! $order instanceof DberpPurchaseOrder) {
            return;
        }

        $this->form->fill(array_merge(
            [
                'purchase_order_id' => $order->getKey(),
                'business_time' => now(),
            ],
            $resolver->resolveFromPurchaseOrder($order),
        ));

        if ($resolver->hasAmbiguousWarehouseForPurchaseOrder($order)) {
            Notification::make()
                ->title((string) __('dberp.notifications.warning'))
                ->body((string) __('dberp.messages.purchase_return_ambiguous_warehouse'))
                ->warning()
                ->send();
        }
    }
}
