<?php

namespace App\Classes\Modules\Exports\Services;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\Order;
use App\Models\PackingList;
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 Carbon\Carbon;

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

    use Exportable;

    public function headings(): array
    {
        return [
            'Container Ref.',
            'ETA',
            'Unstuffing',
            'Marking',
            'Order Number'
        ];
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function query()
    {
        return PackingList::where('type', '=', 2)->whereIn('status', [4, 5])->whereHas('containers');
    }

    /**
     * @param PackingList $packingList
     *
     * @return array
     */
    public function map($packingList): array
    {
        $container = $packingList->containers()->first();
        $ContainerTransport = $container->transports()->first();
        $order = $packingList->owner;
        if(!$order instanceof Order)return [];
        $marking = $order->companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;

        return [
            $container->reference,
            $ContainerTransport ? $ContainerTransport->schedules()->where('status', '=', ApprovalStatus::APPROVED)->first() ? $ContainerTransport->schedules()->where('status', '=', ApprovalStatus::APPROVED)->first()->eta : 'n/a' : 'n/a',
            $ContainerTransport ? $ContainerTransport->drop_date : 'n/a',
            $marking,
            $order->reference,
        ];
    }
}