<?php

namespace App\Http\Resources;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\ContentManager\Contracts\GlobalContent;

class GlobalContentElementList extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        if ($this->resource instanceof LengthAwarePaginator) {
            $this->resource
                ->through(fn(GlobalContent $content) => $this->mapRecord($content));
        } else {
            $this->resource = $this->resource
                ->map(fn(GlobalContent $content) => $this->mapRecord($content));
        }
        return parent::toArray($request);
    }

    /**
     * Map global content record
     *
     * @param GlobalContent $content
     * @return array
     */
    protected function mapRecord(GlobalContent $content)
    {
        return [
            'id' => $content->id,
            'title' => $content->name,
            'link' => '/manage-content/global/edit/' . $content->id,
            'metaItems' => [
                $content->updated_at->diffForHumans(),
                $content->type,
                $content->users
                    ->map(fn ($user) => [
                        'alt' => $user->name,
                        'src' => $user->profile_photo_url
                    ]),
            ],
        ];
    }
}
