<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpSalesQuotes\Pages;

use App\Business\Sales\Enums\SalesQuoteStatus;
use App\Business\Sales\SalesQuoteConversionService;
use App\Business\Sales\SalesQuoteService;
use App\Filament\Resources\DberpSalesOrders\DberpSalesOrderResource;
use App\Filament\Resources\DberpSalesQuotes\DberpSalesQuoteResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Models\DberpSalesQuote;
use App\Services\DberpPermissionService;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Notifications\Notification;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class EditDberpSalesQuote extends EditRecord
{
    protected static string $resource = DberpSalesQuoteResource::class;

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        /** @var DberpSalesQuote $record */
        return app(SalesQuoteService::class)->updateQuote($record, $data);
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('submit')
                ->label(__('dberp.actions.submit_quote'))
                ->formWrapper(false)
                ->requiresConfirmation()
                ->modalDescription(__('dberp.hints.sales_quote_submit'))
                ->visible(fn (DberpSalesQuote $record): bool => in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective], true) && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::ACTIVATE_SALES_QUOTE))
                ->action(function (): void {
                    try {
                        $this->save(shouldRedirect: false, shouldSendSavedNotification: false);

                        app(SalesQuoteService::class)->submit($this->record);

                        $this->record->refresh();
                        $this->fillForm();

                        $status = app(SalesQuoteService::class)->resolveCurrentStatus($this->record);

                        Notification::make()
                            ->title((string) __('dberp.notifications.submitted'))
                            ->body((string) __('dberp.messages.sales_quote_submitted_success', [
                                'status' => $status->label(),
                            ]))
                            ->success()
                            ->send();
                    } catch (ValidationException $exception) {
                        Notification::make()
                            ->title((string) __('dberp.notifications.warning'))
                            ->body(collect($exception->errors())->flatten()->first())
                            ->danger()
                            ->send();

                        throw $exception;
                    }
                }),
            Action::make('convert')
                ->label(__('dberp.actions.convert_quote'))
                ->formWrapper(false)
                ->requiresConfirmation()
                ->modalDescription(__('dberp.hints.sales_quote_convert'))
                ->visible(fn (DberpSalesQuote $record): bool => $record->currentStatus() === SalesQuoteStatus::Effective && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::CONVERT_SALES_QUOTE))
                ->action(function (): void {
                    $order = app(SalesQuoteConversionService::class)->convertToSalesOrder($this->record);
                    $this->redirect(DberpSalesOrderResource::getUrl('edit', ['record' => $order]));
                }),
            Action::make('copy')
                ->label(__('dberp.actions.copy_quote'))
                ->visible(fn (): bool => app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::CREATE_SALES_QUOTE))
                ->action(function (): void {
                    $quote = app(SalesQuoteService::class)->copyQuote($this->record);

                    Notification::make()
                        ->title((string) __('dberp.notifications.saved'))
                        ->body((string) __('dberp.messages.sales_quote_copied_success', [
                            'code' => $quote->code,
                        ]))
                        ->success()
                        ->send();

                    $this->redirect(DberpSalesQuoteResource::getUrl('edit', ['record' => $quote]));
                }),
            Action::make('void')
                ->label(__('dberp.actions.void'))
                ->formWrapper(false)
                ->requiresConfirmation()
                ->modalHeading(fn (): string => (string) __('dberp.hints.sales_quote_void_heading'))
                ->modalDescription(__('dberp.hints.sales_quote_void'))
                ->visible(fn (DberpSalesQuote $record): bool => in_array($record->currentStatus(), [SalesQuoteStatus::Draft, SalesQuoteStatus::PendingEffective, SalesQuoteStatus::Effective, SalesQuoteStatus::Expired], true) && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::VOID_SALES_QUOTE))
                ->action(function (): void {
                    app(SalesQuoteService::class)->void($this->record);
                    $this->record->refresh();
                }),
            DeleteAction::make()
                ->visible(fn (DberpSalesQuote $record): bool => $record->currentStatus() === SalesQuoteStatus::Draft && app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::EDIT_SALES_QUOTE)),
        ];
    }
}
