<?php

namespace App\Http\Resources;

use App\Classes\ValueObjects\Constants\ContainerTypes;
use App\Models\Remark;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\DB;

class ContainerResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'container_reference' => $this->reference,
            'container_specification' => ContainerTypes::CONTAINER_SPECIFICATION[$this->container_type],
            'container_number' => $this->container_number,
            'seal_reference' => $this->seal_reference,
            'loading_date' => optional($this->loading_date)->format('d-m-Y'),
            'transport' => new TransportResource($this->transports()->first()),
            'packages_count' => $this->packages()->where('packages.type', '!=', 2)->sum('quantity'),
            'total_cbm' => $this->packages()->sum(DB::raw('(width/100) * (height/100) * (length/100) * quantity')),
            'remarks' => RemarkResource::collection($this->remarks),
            'status' => $this->status,
            'packing_lists' => $this->shouldIncludePackingListData($request) ? $this->getSortedPackingLists() : null,
        ];
    }

    protected function shouldIncludePackingListData($request)
    {
        return (isset($request->all()['with_packing_list_data']) && ($request->all()['with_packing_list_data'] == false)) ? false : true;
    }

    protected function getSortedPackingLists()
    {
        return $this->whenLoaded('packingLists', PackingListResource::collection(
            $this->packingLists()->get()->sortBy(fn ($packingList) => $packingList->owner->company_module_id)
        ));
    }
}
