<?php

namespace App\Filament\Resources\Pages\Pages;

use App\Filament\Resources\Pages\PageResource;
use Filament\Resources\Pages\CreateRecord;

class CreatePage extends CreateRecord
{
    protected static string $resource = PageResource::class;

    protected array $tempSections = [];

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $this->tempSections = $data['sections_builder'] ?? [];
        unset($data['sections_builder']);
        return $data;
    }

    protected function afterCreate(): void
    {
        $this->record->sections()->delete();
        foreach ($this->tempSections as $index => $block) {
            $this->record->sections()->create([
                'block_type' => $block['type'],
                'content' => $block['data'],
                'sort_order' => $index,
            ]);
        }
    }
}
