<?php

namespace App\Classes\Modules\Exports\Services;

use App\Models\Order;
use App\Models\PackingList;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;

class ExportsArrivedParcel implements WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize, FromQuery
{

    use Exportable;

    public function headings(): array
    {
        return [
            'ORDER NUMBER',
            'Marking',
            'Warehouse',
            'Cbm',
            'Description',
            'quantity',
            'Received Date',
            'Remarks'
        ];
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function query()
    {
        return PackingList::where('type', '=', 1)->where('status', '=', 2)->where('owner_type', Order::class);
    }

    /**
     * @param $packingList
     * @return array
     */
    public function map($packingList): array
    {
        $order = $packingList->owner;

        $connection = $order->companyModule()->first()->inviters()->withPivot('invitee_reference')->first();
        $marking = $connection ? $connection->pivot->invitee_reference:'';

        $warehouse = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_WAREHOUSE)->first()->appointee;

        $cbm = $packingList->packages->sum(function($package){
           return (($package->width / 100) * ($package->height / 100) * ($package->length / 100)) * $package->quantity;
        });

        $arrival_date = $packingList->transports()->first()->drop_date->format('d-m-Y');

        return [
            $packingList->owner->reference,
            $marking,
            $warehouse->reference,
            $cbm,
            $packingList->packages->implode('description', ', '),
            $packingList->packages->sum('quantity'),
            $arrival_date,
            ''
        ];
    }
}