<?php

namespace App\Http\Middleware;

use Closure;
use App\Classes\Modules\Transactions\Processors\CheckStorageInvoiceTransactionProcessor;
use App\Classes\Modules\PackingLists\Services\ListsPackingLists;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\CompanyConnection;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CheckForStorageInvoiceByPackingLists
{

    /** @var CheckStorageInvoiceTransactionProcessor */
    private $storageInvoiceTransactionProcessor;

    /** @var ListsPackingLists */
    private $listsPackingLists;


    public function __construct(CheckStorageInvoiceTransactionProcessor $storageInvoiceTransactionProcessor, ListsPackingLists $listsPackingLists)
    {
        $this->storageInvoiceTransactionProcessor = $storageInvoiceTransactionProcessor;
        $this->listsPackingLists = $listsPackingLists;
    }


    /**
     * Handle an incoming request.
     *
     * @param  Request $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $results = [];
        $packinglists = null;

        $filters = json_decode($request->input('filters'), true);
        // $filters['type_in'] = [TransactionType::SHIPPING_INVOICE];
        // if(json_encode($filters['order_by']) == '{"column":"id","DESC":true}'){
        //     $filters['order_by_id_desc'] = true;
        // }

        if(isset($filters['check_for_storage_invoice'])){
            unset($filters['order_by']);
            $packinglists = $this->listsPackingLists->execute($filters);
            foreach($packinglists as $packingList){
                if($packingList){
                    $order = $packingList->owner()->first();
                    if($order instanceof Order){
                        $storages = $this->storageInvoiceTransactionProcessor->executeOrder($order);
                        if($storages){
                            $results = array_merge($results, $storages);
                        }
                    }
                }
            }
        }

        $request->merge(['storages' => $results]);

        return $next($request);
    }
}
