<?php

namespace App\Classes\Modules\Exports\Services;

use App\Classes\ValueObjects\Constants\PackingListType;
use App\Models\CompanyModule;
use App\Models\Company;
use App\Models\PackingList;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Illuminate\Http\Request;

class ExportsCustomerTotalOrderByYear implements FromCollection, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{
    use Exportable;

    private $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function headings(): array
    {
        return [
            'CompanyId',
            'CompanyName',
            'CompanyReference',
            'TotalCbm'
        ];
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function collection()
    {
        $packingLists = PackingList::where('type', PackingListType::SHIPPING_PACKING_LIST)->whereHas('containers', function($container){
            return $container->where('loading_date', '>=', Carbon::parse('01-01-' . $this->request->route('year')))
                ->where('loading_date', '<=', Carbon::parse('31-12-' . $this->request->route('year')));
        })->get();

        $packingLists = $packingLists->groupBy(function ($packingList){
            return $packingList->owner->company_module_id;
        })->sortByDesc(function($companyModule){
            return $companyModule->sum(function($packingList){
                return $packingList->packages->sum(function ($package){
                    return (($package->width / 100) * ($package->height / 100) * ($package->length / 100)) * $package->quantity;
                });
            });
        })->take(10);
        return $packingLists;
    }

    /**
     * @param $row
     * @return array
     */
    public function map($row): array
    {

        $companyModule = $row[0]->owner->companyModule;
        $marking = $companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;

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

        return [
            $companyModule->company_id,
            $companyModule->name,
            $marking,
            $cbm
        ];
    }
}
