<?php

namespace Modules\Activity\Transformers;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Modules\Activity\Entities\Activity;

class ActivityResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'activity_type_id' => $this->activity_type_id,
            'activity_type' => new ActivityTypeResource($this->whenLoaded('activityType')),
            'title' => $this->title,
            'reference_number' => $this->reference_number,
            'description' => $this->description,
            'start_datetime' => $this->start_datetime?->toISOString(),
            'end_datetime' => $this->end_datetime?->toISOString(),
            'organizer' => $this->organizer,
            'location' => $this->location,
            'is_active' => $this->is_active,
            'documents' => $this->when(
                $this->relationLoaded('documents'),
                fn () => ActivityDocumentResource::collection($this->attachmentDocuments())
            ),
            'gallery_images' => $this->when(
                $this->relationLoaded('documents'),
                fn () => ActivityGalleryImageResource::collection($this->galleryDocuments())
            ),
            'reports' => ActivityReportResource::collection($this->whenLoaded('reports')),
            'created_at' => $this->created_at?->toISOString(),
            'updated_at' => $this->updated_at?->toISOString(),
        ];
    }

    protected function galleryDocuments()
    {
        return $this->documents
            ->where('type', Activity::GALLERY_DOCUMENT_TYPE)
            ->values();
    }

    protected function attachmentDocuments()
    {
        return $this->documents
            ->where('type', '!=', Activity::GALLERY_DOCUMENT_TYPE)
            ->values();
    }
}
