<?php

namespace App\Http\Resources;

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

class SalesmanBranchOfficeResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $salesman = $this->relationLoaded('salesman') ? $this->whenLoaded('salesman') : null;
        $branchOffice = $this->relationLoaded('branchOffice') ? $this->whenLoaded('branchOffice') : null;
        $company = $this->relationLoaded('company') ? $this->whenLoaded('company') : null;

        return [
            'id' => $this->id,
            'idsalesman' => $this->idsalesman,
            $this->mergeWhen($salesman, fn() => [
                'rut_salesman' => $salesman->rut,
                'name_salesman' => $salesman->name,
                'surname_salesman' => $salesman->surname,
                'email_salesman' => $salesman->email,
                'phone_salesman' => $salesman->phone,
                'address_salesman' => $salesman->address,
                'idchannel_salesman' => $salesman->idchannel
            ]),
            'idbranchoffice' => $this->idbranchoffice,
            $this->mergeWhen($branchOffice, fn() => [
                'branchOffice' => $branchOffice->name,
                'assignmenttype' => $branchOffice->assignmenttype,
                'idproductlist' => $branchOffice->idproductlist,
                'idofficetype' => $branchOffice->idofficetype,
                'officetype' => $branchOffice->typeOffice->name,
                'iddistrict' => $branchOffice->iddistrict,
                'district' => $branchOffice->district->name,
                'idprovince' => $branchOffice->idprovince,
                'province' => $branchOffice->province->name,
                'iddepartment' => $branchOffice->iddepartment,
                'department' => $branchOffice->department->name,
                'idcountry' => $branchOffice->idcountry,
                'country' => $branchOffice->country->name
            ]),
            'idcompany' => $this->idcompany,
            $this->mergeWhen($company, fn() => [
                'company' => $company->business_name,
                'rut_company' => $company->rut
            ]),
            'status' => $this->status
        ];
    }
}
