<?php

namespace App\Classes\Modules\Exports\Services;

use App\Classes\ValueObjects\Constants\PackingListType;
use App\Models\CompanyModule;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;

class ExportsCustomersOrderLatestDate implements FromQuery, WithHeadingRow, WithMapping
{

    use Exportable;

    public function headings(): array
    {
        return [
            'Marking',
            'Name',
            'Email',
            'Latest Order'
        ];
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function query()
    {
        return CompanyModule::where('type', '=', 1);
    }

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

        $employees = $company->employees()->first();

        $order = $company->orders()
            ->join('packing_lists', 'packing_lists.owner_id', '=', 'orders.id')
            ->join('transport_arrangements', 'transport_arrangements.owner_id', '=', 'packing_lists.id')
            ->orderBy('drop_date', 'desc')
            ->first();

        return [
            $marking,
            $employees ? $employees->name : '',
            $employees ? $employees->email : '',
            $order ? $order->drop_date : ''
        ];
    }
}