<?php

namespace App\Http\Resources;

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

class DetailTicketResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $product = $this->relationLoaded('product') ? $this->whenLoaded('product') : null;
        $productOrigin = $this->relationLoaded('productOrigin') ? $this->whenLoaded('productOrigin') : null;

        return [
            'id'                    => $this->id,
            'idticket'              => $this->idticket,
            'idpricelist_product'   => $this->idpricelist_product,
            $this->mergeWhen($product, fn() => [
                'code_system'  => $product->product->code_system,
                'product'      => $product->product->name
            ]),
            'idproduct'             => $this->idproduct,
            $this->mergeWhen(!$product, function () use ($product, $productOrigin) {
                $result = [];

                # Agregar $productOrigin cuando $product es inválido
                if (!$product && $productOrigin) {
                    $result = [
                        'code_system' => $productOrigin->code_system,
                        'product' => optional($productOrigin)->name,
                    ];
                }
                return $result;
            }),
            'idproduct'             => $this->idproduct,
            $this->mergeWhen($productOrigin, fn() => [
                'idunitmeasure'  => $productOrigin->idunitmeasure,
                'unitmeasure_abr'    => $productOrigin->unitMeasure->abbreviation
            ]),
            'amount'                => $this->amount,
            'price'                 => $this->price,
            'discount'              => $this->discount,
            'discounttype'          => $this->discounttype,
            'gross_subtotal'        => $this->gross_subtotal,
            'net_subtotal'          => $this->net_subtotal,
            'status'                => $this->status
        ];
    }
}
