<?php

namespace App\Filament\Resources\ProductResource\Pages;

use App\Filament\Resources\ProductResource;
use App\Models\ProductImage;
use Filament\Resources\Pages\CreateRecord;

class CreateProduct extends CreateRecord
{
    protected static string $resource = ProductResource::class;

    protected function mutateFormDataBeforeSave(array $data): array
    {
        // Store images in a temporary property
        if (isset($data['images']) && is_array($data['images'])) {
            $this->pendingImages = $data['images'];
        }
        unset($data['images']);
        
        return $data;
    }

    protected function afterSave(): void
    {
        if (!isset($this->pendingImages)) {
            return;
        }

        foreach ($this->pendingImages as $index => $imagePath) {
            ProductImage::create([
                'product_id' => $this->record->id,
                'image_path' => $imagePath,
                'sort_order' => $index,
            ]);
        }
    }
}
