<?php

namespace App\Filament\Resources\TestCategoryResource\Pages;

use App\Filament\Resources\TestCategoryResource;
use App\Models\Test;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;

class EditTestCategory extends EditRecord
{
    protected static string $resource = TestCategoryResource::class;

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

    public function mutateFormDataBeforeFill(array $data): array
    {
        $data['test_ids'] = $this->record->tests()->pluck('id')->toArray();
        return $data;
    }

    protected function afterSave(): void
    {
        $data = $this->form->getState();
        $testIds = $data['test_ids'] ?? [];
        Test::where('test_category_id', $this->record->id)->update(['test_category_id' => null]);
        if (!empty($testIds)) {
            Test::whereIn('id', $testIds)->update(['test_category_id' => $this->record->id]);
        }
    }
}
