<?php


namespace App\Classes\Modules\Transactions\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Transactions\Services\ListsTransactions;
use App\Http\Resources\TransactionWithStorageResource;
use App\Http\Resources\TransactionResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;


class ListTransactionsLogic extends AbstractControllerLogic
{
    /**
     * ListTransactionsLogic constructor.
     * @param ListsTransactions $listsTransactions
     */
    public function __construct(ListsTransactions $listsTransactions)
    {
        $this->listsTransactions = $listsTransactions;
    }

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Retrieved Transactions',
            'message' => 'You have successfully retrieved a list of transactions'
        ];
    }

    /** @var ListsTransactions */
    private $listsTransactions;



    public function logic(Request $request) : JsonResponse
    {
        $query = $this->listsTransactions->execute($this->listsTransactions->deserializeFilters($request->input('filters')));

        if($request->input('storages')){
            foreach ($query->items() as $item) {
                $transactionId = $item['id'];
                $filteredStorages = array_filter($request->input('storages'), function ($storage) use ($transactionId) {
                    return isset($storage['parentInvoiceId']) &&  $storage['parentInvoiceId'] == $transactionId;
                });
                $item['storages'] = $filteredStorages;
            }
            //return $this->collectionResponse(TransactionWithStorageResource::collection($query));
        }
        // else{
        //     return $this->collectionResponse(TransactionResource::collection($query));
        //
        return $this->collectionResponse(TransactionWithStorageResource::collection($query));
    }
}
