<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class DetailUserCompanyResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray(Request $request): array
    {
        $user       = $this->relationLoaded('user') ? $this->whenLoaded('user') : null;
        $userType   = $this->relationLoaded('userType') ? $this->whenLoaded('userType') : null;
        $privilege   = $this->relationLoaded('privilege') ? $this->whenLoaded('privilege') : null;
        $company    = $this->relationLoaded('company') ? $this->whenLoaded('company') : null;

        return [
            'iddetail_user' => $this->id,
            'id' => $this->iduser,
            $this->mergeWhen($user, fn () => [
                'rut' => $user->rut,
                'username' => $user->username,
                'name' => $user->name,
                'first_surname' => $user->first_surname,
                'second_surname' => $user->second_surname,
                'gender' => $user->gender,
                'type_person' => $user->type_person,
                'age' => $user->age,
                'birthdate' => $user->birthdate,
                'email' => $user->email,
                'phone' => $user->phone,
                'status' => $user->status,
                'birthdate' => $user->birthdate,
            ]),
            'idcompany' => $this->idcompany,
            $this->mergeWhen($company, fn() => [
                'company' => $company->business_name,
                'idmembership' => $company->idmembership,
                'membership' => $company->membership->name
            ]),
            'iduser_type' => $this->iduser_type,
            $this->mergeWhen($userType, fn () => [
                'userType' => $userType->name,
                'role' => $userType->name,
            ]),
            'idprivilege' => $this->idprivilege,
            $this->mergeWhen($privilege, fn () => [
                'privilege' => $privilege->name,
            ]),
            'status' => $this->status,
        ];
    }
}
