<?php

namespace App\Http\Resources\Competitions;

use App\Helpers\DateHelper;
use Illuminate\Http\Resources\Json\JsonResource;

class CompetitionResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'waId' => $this->wa_id,
            'slug' => $this->slug,
            'title' => $this->title,
            'country' => $this->locationCountry ? $this->locationCountry->common_name : '',
            'countryCode' => $this->locationCountry ? $this->locationCountry->iso2 : '',
            'city' => $this->location_city,
            'publicationDate' => DateHelper::formatDateTimeCET($this->publication_date),
            'submissionUntil' => DateHelper::formatDateTimeCET($this->submission_until),
            'departments' => $this->_getDepartments(),
            'procedureType' => $this->procedureTypes->first()?->title ?? '',
            'procedureTypes' => $this->procedureTypes->map(fn ($pt) => ['id' => $pt->id, 'title' => $pt->title]),
            'procedureTypeText' => $this->procedure_type_text,
            'watchlistsIds' => $this->watchlists->pluck('id')->toArray(),
            'isWatchlisted' => $this->watchlists->isNotEmpty(),
            'promoter' => nl2br($this->promoter),
            'officialNumber' => $this->official_number,
            'isPublic' => $this->is_public,
            'isOpenToStudents' => $this->is_public || $this->procedureTypes->contains(fn ($pt) => $pt->is_open_to_students),
            'isUpdate' => !!$this->updated_competition_id,
        ];
    }

    protected function _getDepartments()
    {
        $departments = [];
        foreach ($this->cpvs as $cpv) {
            foreach ($cpv->departments as $department) {
                $departments[$department->id] = $department->full_name ? $department->full_name : $department->title;
            }
        }
        return $departments;
    }
}
