<?php

namespace App\Http\Resources;

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

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

        return [
            'id' => $this->id,
            'iduser_created' => $this->iduser_created,
            'idsupplier' => $this->idsupplier,
            $this->mergeWhen($supplier, fn() => [
                'supplier' => $supplier->name_rz
            ]),
            'cost_total' => $this->cost_total,
            'idcompany' => $this->idcompany,
            'status_entry' => $this->status_entry,
            'status' => $this->status,
            $this->mergeWhen($details, fn() => [
                'details' => ProductEntryDetailResource::collection($details)
            ]),
            'created_at' => $this->created_at ? Carbon::parse($this->created_at)->format('Y-m-d H:i:s') : '',
        ];
    }
}
