<?php

namespace App\Filament\Resources\Pages\Pages;

use App\Filament\Resources\Pages\PageResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;

class EditPage extends EditRecord
{
    protected static string $resource = PageResource::class;

    protected array $tempSections = [];

    protected function getHeaderActions(): array
    {
        return [
            \Filament\Actions\Action::make('preview')
                ->label('Preview Page')
                ->icon('heroicon-o-eye')
                ->url(fn () => route('pages.show', ['slug' => $this->record->slug]) . '?preview=1')
                ->openUrlInNewTab(),
            DeleteAction::make(),
        ];
    }

    protected function mutateFormDataBeforeFill(array $data): array
    {
        $data['sections_builder'] = $this->record->sections->map(function ($section) {
            return [
                'type' => $section->block_type,
                'data' => $section->content,
            ];
        })->toArray();

        return $data;
    }

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

    protected function afterSave(): 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,
            ]);
        }
    }
}
