<?php

namespace App\Filament\Resources\SubCategoryResource\Pages;

use App\Filament\Resources\SubCategoryResource;
use App\Models\Catalog\SubCategory;
use App\Services\AuditLog;
use Filament\Resources\Pages\EditRecord;

class EditSubCategory extends EditRecord
{
    protected static string $resource = SubCategoryResource::class;

    /**
     * @var array<string, mixed>
     */
    protected array $originalValues = [];

    protected function mutateFormDataBeforeSave(array $data): array
    {
        $this->originalValues = $this->record->only(['name', 'description', 'is_active', 'main_category_id']);

        return $data;
    }

    protected function afterSave(): void
    {
        /** @var SubCategory $category */
        $category = $this->record;

        $changes = [];
        foreach ($this->originalValues as $field => $old) {
            if ($old !== $category->{$field}) {
                $changes[$field] = ['from' => $old, 'to' => $category->{$field}];
            }
        }

        AuditLog::record('sub_category.updated', $category, [
            'name' => $category->name,
            'changed' => array_keys($changes),
            'changes' => $changes,
            'description' => 'Updated sub category "'.$category->name.'"'
                .($changes !== [] ? ' — changed: '.implode(', ', array_keys($changes)) : '').'.',
        ]);
    }

    protected function getRedirectUrl(): string
    {
        return SubCategoryResource::getUrl('index');
    }
}
