<?php

namespace App\Filament\Resources\TransmittalResource\Pages;

use App\Filament\Resources\TransmittalResource;
use Filament\Actions\Action;
use Filament\Resources\Pages\CreateRecord;
use Throwable;

class CreateTransmittal extends CreateRecord
{
    protected static string $resource = TransmittalResource::class;

    public bool $willExport = false;

    /**
     * @throws Throwable
     */
    public function createAndExport(): void
    {
        $this->willExport = true;
        $this->create();
    }

    public function afterCreate()
    {
        if ($this->willExport) {
            TransmittalResource::exportTransmittal([$this->record->id]);
        }
    }

    public function getCreatedNotificationMessage(): ?string
    {
        if ($this->willExport) {
            return 'Transmittal Was Created Successfully!, Check your notification for file download link';
        }

        return 'Transmittal Was Created Successfully!';
    }

    protected function getFormActions(): array
    {
        return [
            $this->getCreateFormAction(),
            $this->getCreateAnotherFormAction(),
            Action::make('Create and Export')->action('createAndExport')->color('success'),
            $this->getCancelFormAction(),
        ];
    }

    protected function getRedirectUrl(): string
    {
        return $this->previousUrl ?? $this->getResource()::getUrl('index');
    }
}
