<?php

namespace App\Classes\Modules\Exports\Services;

use App\Models\Container;
use App\Models\Package;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Carbon\Carbon;

class ExportsCompanyModuleSummary implements FromCollection, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{

    use Exportable;

    protected $companyModuleId, $containerIds;

    public function headings(): array
    {
        return [
            'Date',
            'Full Marking',
            'Container',
            'Description',
            'Ctns',
            'L (cm)',
            'H (cm)',
            'W (cm)',
            'CBM'
        ];
    }
    
    public function setParameters($companyModuleId, $containerIds)
    {
        $this->companyModuleId = $companyModuleId;
        $this->containerIds = $containerIds;
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function collection()
    {
        $packagesArray = collect();
        $containers = Container::whereIn('reference', explode(',', $this->containerIds))->get();
        foreach ($containers as $container){
            $company_module_id = $this->companyModuleId;
            $packingLists = $container->packingLists()->get()->filter(function ($packingList) use ($company_module_id) {
                return $packingList->owner->company_module_id == $company_module_id;
            });
            foreach ($packingLists as $packingList){
                if($packingList->packingLists->first()){
                    $packingList = $packingList->packingLists->first();
                }
                $packages = $packingList->packages;
                foreach ($packages as $package){
                    $packagesArray->push($package);
                }
            }
        }

        return $packagesArray;
    }

    /**
     * @param Package $package
     *
     * @return array
     */
    public function map($package): array
    {
        $connection = $package->packingList->owner->companyModule->inviters()->withPivot('invitee_reference')->first();
        $marking = $connection ? $connection->pivot->invitee_reference:'';

        return [
            Carbon::parse($package->created_at)->format('d-m-Y'),
            $marking,
            $package->packingList->containers()->first()->reference,
            $package->description,
            $package->quantity,
            $package->length,
            $package->height,
            $package->width,
            ((($package->length / 100) * ($package->height / 100) * ($package->width / 100)) *  $package->quantity)
        ];
    }
}