<?php

namespace App\Http\Resources;

use App\ElementRepository;
use App\Traits\RetrievesFieldData;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\App;
use Mtc\ContentManager\CommentRepository;
use Mtc\ContentManager\Contracts\Template;
use Mtc\ContentManager\Traits\ContentMetaValues;
use Mtc\MercuryDataModels\GlobalContent;

class TemplateViewResource extends JsonResource
{
    use ContentMetaValues;
    use RetrievesFieldData;

    public static $wrap = '';

    /**
     * @var LengthAwarePaginator
     */
    public $resource;

    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        $this->resource->load('elements.element');
        $elements = $this->resource->elements->map(fn ($content) => $this->mapElements($content));
        $resource = $this->resource->toArray();
        $resource['elements'] = $elements;
        $resource['meta'] = $this->getMetaValues([ 'flexible' => false ]);
        $resource['seo_defaults'] ??= [];
        $resource['status'] = $resource['status'] === 'published';
        $blockResource = config('pages.content_element_block_resource');

        return [
            'template' => $resource,
            'global_content' => new $blockResource(GlobalContent::query()->paginate(10)),
            'elements' => new $blockResource(App::make(ElementRepository::class)
                ->getList(null, null, 10, true, true, false)),
            'comments' => App::make(CommentRepository::class)->getForModel($this->resource)
        ];
    }

    /**
     * Map template record
     *
     * @param Template $template
     * @return array
     */
    protected function mapElements($element)
    {
        return array_merge([
            'id' => $element->id,
            'element_id' => $element->element_id,
            'field_type' => $element->field_type,
            'global_content_id' => $element->global_content_id,
            'name' => $element->name,
            'order' => $element->order,
            'fieldId' => 'group',
            'icon' => $this->getFieldIcon($element),
            'nestable' => $field->data['nestable'] ?? false,
            'component' => $this->getField($element->field_type)?->getComponent(),
            'componentName' => $this->getField($element->field_type)?->getComponent(),
            'nestedLimit' => $field->data['nestedLimit'] ?? false,
            'editable' => true,
            'repeatable' => $field->data['repeatable'] ?? false,
            'optionsMenuVisible' => false,
            'isGroup' => ($element->data['fieldId'] ?? 'group') === 'group',
            'error' => null,
            'children' => [],

        ], $element->data ?? []);
    }
}
