<?php

namespace App\Filament\Resources\ServiceResource\Pages;

use App\Filament\Resources\ServiceResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;

class EditService extends EditRecord
{
    protected static string $resource = ServiceResource::class;

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

    protected function mutateFormDataBeforeFill(array $data): array
    {
        $record = $this->getRecord();

        if ($record) {
            $nameTranslations = $record->getTranslations('name');
            $descTranslations = $record->getTranslations('description');

            // Filament dot-notation fields expect NESTED arrays
            $data['name'] = [
                'ar' => $nameTranslations['ar'] ?? '',
                'en' => $nameTranslations['en'] ?? '',
            ];

            $data['description'] = [
                'ar' => $descTranslations['ar'] ?? null,
                'en' => $descTranslations['en'] ?? null,
            ];
        }

        return $data;
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        if (isset($data['name']) && is_array($data['name'])) {
            $data['name'] = [
                'ar' => $data['name']['ar'] ?? '',
                'en' => $data['name']['en'] ?? '',
            ];
        }

        if (isset($data['description']) && is_array($data['description'])) {
            $data['description'] = [
                'ar' => $data['description']['ar'] ?? null,
                'en' => $data['description']['en'] ?? null,
            ];
        }

        return $data;
    }
}
