<?php

namespace App\Filament\Resources\EsgResource\Pages;

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

class CreateEsg extends CreateRecord
{
    use HandlesEsgParagraphs;
    protected static string $resource = EsgResource::class;

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }
    protected function handleRecordCreation(array $data): Model
    {
        \Log::info("=== 開始建立流程 ===");

        // ✅ 使用 Trait 方法處理表單中的 paragraphs
        $processedParagraphs = $this->processFormParagraphs();

        if ($processedParagraphs) {
            \Log::info("預處理後的 paragraphs:", $processedParagraphs);
        }

        // 建立主記錄
        $record = static::getModel()::create($data);
        \Log::info("主記錄已建立:", ['id' => $record->id]);

        // ✅ 使用 Trait 方法建立 paragraphs 關聯
        if ($processedParagraphs) {
            $this->createParagraphs($record, $processedParagraphs);
        }

        return $record->refresh();
    }

}
