<?php

namespace App\Filament\Resources\PackageResource\Pages;

use App\Filament\Resources\PackageResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;

class EditPackage extends EditRecord
{
    protected static string $resource = PackageResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\DeleteAction::make(),
        ];
    }

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

    public function mutateFormDataBeforeFill(array $data): array
    {
        $data['tests_display_mode'] = $this->record->sections()->exists() ? 'sections' : 'flat';
        return $data;
    }

    protected function afterSave(): void
    {
        $mode = $this->form->getState()['tests_display_mode'] ?? 'sections';
        if ($mode === 'flat') {
            $this->record->sections()->delete();
        } else {
            $this->record->tests()->sync([]);
        }
    }
}
