<?php

namespace App\Http\Middleware;

use Closure;
use App\Classes\Modules\Transactions\Processors\CheckStorageInvoiceTransactionProcessor;
use App\Classes\Modules\Transactions\Services\ListsGroups;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CheckForStorageInvoiceByGroup
{

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

    /** @var ListsGroups */
    private $listsGroups;


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


    /**
     * 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)
    {
        // :options="{'per_page': 10, order_by: {column: 'id', DESC: true}, 'status_in': [0, 1], 'receiver': company_module_id, order_by: {column: 'updated_at', DESC: true}}"
        $filters = json_decode($request->input('filters'), true);
        if(json_encode($filters['order_by']) == '{"column":"updated_at","DESC":true}'){
            $filters['order_by_updated_at_desc'] = true;
        }
        unset($filters['order_by']);
        $groups = $this->listsGroups->execute($filters);


        if(isset($filters['check_for_storage_invoice'])){
            foreach ($groups as $group){
                foreach ($group->groupTransactions as $groupTransaction) {
                    $invoice = $groupTransaction->transaction;
                    $packingList = $invoice->owner()->first();
                    if($packingList){
                        $order = $packingList->owner()->first();
                        if($order instanceof Order){
                            $storages = $this->storageInvoiceTransactionProcessor->executeOrder($order);
                        }
                    }
                }
            }
        }

        return $next($request);
    }
}
