<?php

namespace App\Http\Resources;

use App\Classes\Modules\Orders\Services\ListsOrderHistory;
use App\Classes\Modules\Steps\GetStep;
use App\Classes\Modules\Steps\StepAttachments;
use App\Models\OrderStep;
use App\Http\Resources\OrderStep as OrderStepResource;
use App\Models\OrderWarehouse;
use App\Models\TrackingNumber;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Models\AddressBook as AddressBookModel;
use App\Models\DeliveryArrangement as DeliveryArrangementModel;
use App\Models\Package as PackagesModel;
use App\Models\ShippingArrangement as ShippingArrangementModel;
use App\Models\Warehouse as WarehouseModel;
use App\Models\Company as CompanyModel;

class Order extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $warehouseId =  OrderWarehouse::where('order_id', $this->id)->where('type', 0)->pluck('warehouse_id');
        $warehouse = $warehouseId ? WarehouseModel::where('id', $warehouseId)->first() : null;
        $receiveDate = OrderStep::where('order_id', $this->id)->where('reference_id', 'MS_WAREHOUSE_RECEIVING')->pluck('complete_date')->first();
        return [
            'id' => $this->id,
            'marking' => $this->marking,
            'company' => CompanyModel::where('id', $this->company_id)->first(),
            'forwarder_id' => $this->forwarder_id,
            'supplier_id' => $this->supplier_id,
            'warehouse_id' => $this->warehouse_id,
            'address' => new AddressBook(AddressBookModel::where('id', $this->address_id)->first()),
            'complete' => (int)$this->complete,
            'date' => $this->created_at->format('d/m/Y'),
            'current_step' => [
                'reference_id' => $this->current_step,
                'details' => (new GetStep())->execute($this->current_step),
                'attachments' => (new StepAttachments())->execute($this->id, $this->current_step)
            ],
            'steps' => OrderStepResource::collection(OrderStep::where('order_id', $this->id)->orderBy('sequence')->get()),
            'details' => (new ListsOrderHistory())->execute($this->id, $this->created_at),
            'receive_note' => [
                'warehouse_name' => $warehouse ? $warehouse->name : null,
                'tracking_number' => TrackingNumber::Where('order_id', $this->id)->where('type', 0)->pluck('tracking_no')->first(),
                'receive_date' => $receiveDate ? Carbon::parse($receiveDate)->format('d-m-Y') : null
            ],
            'packages' => Package::collection(PackagesModel::where('order_id', $this->id)->get()),
            'shipping_arrangement' => [],
            'delivery_arrangement' => new DeliveryArrangement(DeliveryArrangementModel::where('order_id', $this->id)->first())
        ];
    }

}
