<?php

namespace App\Filament\Resources\EsgResource\Pages;

use App\Filament\Resources\EsgResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;
use App\Traits\HandlesEsgParagraphs;

class EditEsg extends EditRecord
{
    use HandlesEsgParagraphs;
    protected static string $resource = EsgResource::class;

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

    /**
     * 在填充表單前處理資料 - 手動載入關聯資料
     */
    protected function mutateFormDataBeforeFill(array $data): array
    {

        // ✅ 使用 Trait 方法載入並格式化 paragraphs
        $data['paragraphs'] = $this->loadAndFormatParagraphs($this->record);
        return $data;
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        return $data;
    }

    /**
     * 儲存時的處理
     */
    protected function handleRecordUpdate(Model $record, array $data): Model
    {

        // ✅ 使用 Trait 方法處理表單中的 paragraphs
        $processedParagraphs = $this->processFormParagraphs();
        // 更新主記錄
        $record->update($data);
        // ✅ 使用 Trait 方法處理 paragraphs 關聯
        if ($processedParagraphs) {
            $this->updateParagraphs($record, $processedParagraphs);
        }
        return $record->refresh();
    }
}
