<?php

namespace App\Classes\Modules\ControllersLogic\Dashboard;

use App\Models\Package;
use App\Models\Order;
use App\Models\PackingList;
use Carbon\Carbon;

class CbmReportLogic
{
    /* @var Package */
    private $repository;

    /**
     * CbmReportLogic constructor.
     * @param Package $repository
     */
    public function __construct(Package $repository)
    {
        $this->repository = $repository;
    }

    public function execute() {
        $excludedOrders = Order::where('company_id', 349)->withTrashed()->pluck('id')->toArray();
        $excludedPackingLists = PackingList::whereIn('order_id', $excludedOrders)->pluck('id')->toArray();
        $cbm = $this->repository->selectRaw('created_at, ((((width/100) * (length/100) * (height/100))) * quantity) as cbm')->whereYear('created_at', '=', Carbon::now()->year)->whereMonth('created_at', '=', Carbon::now()->month)->whereNotIn('list_id', $excludedPackingLists)->orderBy('created_at')->get();

        $cbmGroup = $cbm->groupBy(function ($item) {
            return Carbon::parse($item->created_at)->format('j');
        });

        $cbmMap  = $cbmGroup->map(function ($item){
            return collect($item)->sum("cbm");
        })->toArray();

        $report = [];
        for($x = 1; $x <= Carbon::now()->daysInMonth; $x++){
            $report[] = isset($cbmMap[$x]) ? $cbmMap[$x] : 0;
        }

        return $report;
    }
}