<?php

declare(strict_types=1);

namespace App\Filament\Resources\RationReports\Pages;

use App\Filament\Resources\RationReports\RationReportResource;
use App\Models\Report;
use Filament\Actions\Action;
use Filament\Resources\Pages\CreateRecord;

class CreateRationReport extends CreateRecord
{
    protected static string $resource = RationReportResource::class;

    protected function getFormActions(): array
    {
        return [
            Action::make('createDraft')
                ->label('ذخیره پیش‌نویس')
                ->color('gray')
                ->action('createDraft'),
            $this->getCreateFormAction()->label('ویرایش/ذخیره نهایی'),
            ...($this->canCreateAnother() ? [$this->getCreateAnotherFormAction()] : []),
            $this->getCancelFormAction(),
        ];
    }

    public function createDraft(): void
    {
        $this->form->fill(array_merge($this->form->getState(), ['status' => 'draft']));
        $this->create();
    }

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $data['type'] = Report::TYPE_RATION;
        return $data;
    }

    protected function getRedirectUrl(): string
    {
        $record = $this->getRecord();
        if ($record && $record->create_invoice) {
            return \App\Filament\Resources\Invoices\InvoiceResource::getUrl('index')
                .'?report_id='.$record->getKey().'&create_invoice=1';
        }

        return parent::getRedirectUrl();
    }

    protected function getCreatedNotificationTitle(): ?string
    {
        if ($this->getRecord() && $this->getRecord()->status === 'draft') {
            return 'جیره به صورت پیش‌نویس ذخیره شد.';
        }
        return parent::getCreatedNotificationTitle();
    }
}
