<?php

namespace App\Classes\Modules\Exports\Services;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\Container;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
use Illuminate\Http\Request;

class ExportsContainerPackingList implements FromQuery, WithHeadingRow, WithMapping
{
    use Exportable;

    protected $id;

    public function headings(): array
    {
        return [
            'Marking',
            'Refrence',
            'Quantity',
            'CBM',
            'Status',
            'Delivery Phone',
            'Delivery Refrence',
            'Delivery Address',
            'Remark',
            'Delivery Date'
        ];
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function query()
    {   
        return Container::find($this->id)->packingLists();
    }

    /**
     * @param Company $container
     *
     * @return array
     */
    public function map($packing_list): array
    {
        $order = $packing_list->owner()->first();
        $address = $order->addresses()->first();
        $company = $order->companyModule()->first();
        $connection = $company->inviters()->withPivot('invitee_reference')->first();
        $marking = $connection ? $connection->pivot->invitee_reference:'';

        $quantity = 0;
        $cbm = 0;
        foreach ($packing_list->packages()->get() as $key => $row) {
            $quantity += $row->quantity;
            $cbm += (($row->width / 100) * ($row->height / 100) * ($row->length / 100)) * $row->quantity;
        }

        $status = '';
        if ($packing_list->transports()->count() > 0) {
            $status = 'Delivery';
        }
        elseif ($packing_list->status == ApprovalStatus::SUSPENDED) {
            $status = 'On Hold';
        }
        elseif ($packing_list->status != ApprovalStatus::SUSPENDED) {
            $status = 'Release';
        }

        return [
            $marking,
            $order->reference,
            $quantity,
            $cbm,
            $status,
            $address->contacts()->first() ? $address->contacts()->first()->phone : 'n/a',
            $address->contacts()->first() ? $address->contacts()->first()->reference : 'n/a',
            $address->street_one . ' ' . $address->street_two . ' ' . $address->district->name . ' ' . $address->post_code . ' ' . $address->state->name . ' ' . $address->country->name,
            $address->remarks()->first() ? $address->remarks()->first()->content : 'n/a',
            $packing_list->transports()->first() ?  $packing_list->transports()->current_schedule->eta : 'n/a'
        ];
    }
}