<?php

namespace App\Http\Resources;

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

class SalesBookResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $customer   = $this->relationLoaded('customer') ? $this->whenLoaded('customer') : null;
        $company    = $this->relationLoaded('company') ? $this->whenLoaded('company') : null;
        $typeDocument = $this->relationLoaded('typeDocument') ? $this->whenLoaded('typeDocument') : null;

        return [
            'id'                    => $this->id,
            'idcompany'             => $this->idcompany,
            $this->mergeWhen($company, fn() => [
                'company'           => $company->business_name,
                'rut_company'       => $company->rut
            ]),
            'date'                  => $this->date,
            'date_format'           => Carbon::parse($this->date)->isoFormat('D [de] MMMM [de] YYYY'),
            'nro_ticket'            => $this->nro_ticket,
            'url_invoice'           => $this->url_invoice,
            'folio'                 => $this->folio,
            'idtype_document'       => $this->idtype_document,
            $this->mergeWhen($typeDocument, fn() => [
                'type_document'     => $typeDocument->name,
            ]),
            'idcustomer'            => $this->idcustomer,
            $this->mergeWhen($customer, fn() => [
                'name_customer'     => $customer->name_rz,
                'rut_customer'      => $customer->rut
            ]),
            'status'                => $this->status
        ];
    }
}
