<?php

namespace App\Http\Resources;

use App\Traits\RetrievesFieldData;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\PropertyCategoryField;

class PropertyCategoryView extends JsonResource
{
    use RetrievesFieldData;

    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        $resource = $this->resource->toArray();
        $this->resource->load('fields');
        $resource['fields'] = $this->resource->fields->map(fn($field) => $this->formField($field));
        return $resource;
    }


    private function formField(PropertyCategoryField $field): array
    {
        $content = $this->getField($field->type);
        return [
            'id' => $field->id,
            'name' => $field->name,
            'slug' => $field->slug,
            'element_id' => null,
            'global_content_id' => null,
            'content' => [],
            'fieldId' => $content::TYPE,
            'icon' => $content->getIcon(),
            'nestable' => $field->data['nestable'] ?? false,
            'componentName' => $content->getComponent(),
            'component' => $content->getComponent(),
            'nestedLimit' => $field->data['nestedLimit'] ?? false,
            'editable' => true,
            'globalContent' => false,
            'repeatable' => $field->data['repeatable'] ?? false,
            'optionsMenuVisible' => false,
            'type' => $field->type,
            'field_type' => $field->type,
            'isGroup' => ($content::TYPE ?? 'group') === 'group',
            'error' => null,
            'children' => [],

        ];
    }
}
