<?php

namespace App\Filament\Resources\ProductResource\Pages;

use App\Filament\Resources\ProductResource;
use App\Models\ProductImage;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;

class EditProduct extends EditRecord
{
    protected static string $resource = ProductResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\DeleteAction::make(),
        ];
    }

    protected function mutateFormDataBeforeFill(array $data): array
    {
        // Load existing images for the form
        $data['images'] = $this->record->images()->orderBy('sort_order')->pluck('image_path')->toArray();
        return $data;
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        // Store images for processing after save
        $this->pendingImages = $data['images'] ?? [];
        unset($data['images']);
        
        return $data;
    }

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

        $newImages = $this->pendingImages;
        $existingImages = $this->record->images()->pluck('image_path')->toArray();
        
        // Find images to delete (in existing but not in new)
        $imagesToDelete = array_diff($existingImages, $newImages);
        foreach ($imagesToDelete as $imagePath) {
            $this->record->images()->where('image_path', $imagePath)->delete();
        }
        
        // Add new images and update sort order
        foreach ($newImages as $index => $imagePath) {
            ProductImage::firstOrCreate(
                [
                    'product_id' => $this->record->id,
                    'image_path' => $imagePath,
                ],
                [
                    'sort_order' => $index,
                ]
            )->update(['sort_order' => $index]);
        }
    }
}
