<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;

class UiPromoText extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        $content = $this->getContent();
        return [
            'title' => $content->where('slug', 'title')->first()?->content,
            'content' => $content->where('slug', 'content')->first()?->content,
            'buttonText' => $content->where('slug', 'button-text')->first()?->content,
            'buttonLink' => $content->where('slug', 'button-link')->first()?->content,
        ];
    }

    private function getContent(): Collection
    {
        return !empty($this->resource->global_content_id)
            ? collect($this->resource->globalContent->content ?? [])->map(fn (array $content) => (object)$content)
            : $this->resource->subContent;
    }
}
