<?php

namespace Modules\Internal\Transformers;

use Illuminate\Http\Resources\Json\JsonResource;

use function PHPSTORM_META\map;

class DoctorResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        $doctor = [
            'id' => $this->id,
            // 'his_dokter_id' => $this->practitionerRoles->meta,
            'name' => $this->person->name,
            'person_id' => $this->person->id,
            'phone' => $this->person->phone ?? null,
            'email' => $this->person->email ?? null,
            'birth_date' => $this->person->birth_date ?? null,
            'birth_place' => $this->person->birth_place ?? null,
            'gender' => $this->person->gender == "L" || $this->person->gender == "male"  ? 'male' : 'female',
            'address' => $this->person->currentAddress->text ?? null,
            'organizations' => $this->practitionerRoles->unique('organization_id')->map(function ($practitionerRole) {
                return [
                    'organization_id' => $practitionerRole->organization->id,
                    'organization_name' => $practitionerRole->organization->name,
                ];
            })->values(),
            "specialties" => $this->practitionerRoles->unique('speciality_id')->map(function ($practitionerRole) {
                return [
                    'specialty_id' => $practitionerRole->speciality->id,
                    'specialty_name' => $practitionerRole->speciality->name,
                ];
            }),
            // "departemen" => $this->practitionerRoles->map(function ($practitionerRole) {
            //     return [
            //         'departemen_id' => $practitionerRole->meta->DepartemenID ?? null,
            //     ];
            // }) ?? null,
            'education' => $this->meta->education ?? null,
            'experience' => $this->meta->work_experience ?? null,
            'award' => $this->meta->award ?? null,
            'keilmuan' => $this->meta->Keilmuan ?? null,
            'tipe_dokter' => $this->meta->tipeDokter ?? null,

        ];

        $grouped = $this->collection($this->practitionerRoles)->groupBy('organization_id');
        $grouped->transform(function ($items, $key) {
            return [
                'organization_id' => $key,
                'specialities' => $items->map(function ($item) {
                    return [
                        'speciality_id' => $item->speciality->id,
                    ];
                }),
            ];
        });

        $doctor['practices'] = $grouped->toArray();

        return $doctor;
    }
}
