<?php

namespace App\Classes\Modules\Transactions\Services;

use Carbon\Carbon;
use App\Models\Bank;
use App\Http\Resources\BankResource;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\Modules\Transactions\Services\ChecksIfTransactionBillNumberExists;
use Illuminate\Database\Eloquent\Collection;

class GeneratesBankBalanceAccount
{

    /** @var ChecksIfTransactionBillNumberExists */
    private $checksIfTransactionBillNumberExists;

    /**
     * GeneratesTransactionBillNo constructor.
     * @param ChecksIfTransactionBillNumberExists $checksIfTransactionBillNumberExists
     */
    public function __construct(ChecksIfTransactionBillNumberExists $checksIfTransactionBillNumberExists)
    {
        $this->checksIfTransactionBillNumberExists = $checksIfTransactionBillNumberExists;
    }


    /**
     * @param Bank $bank
     */
    public function execute(Bank $bank) {
        $floatTransactions = $bank->recipientTransactions()->where('transactions.type', TransactionType::BILL)->whereIn('transactions.status', [ApprovalStatus::APPROVED])->orderBy('id', 'DESC')->get();
        $transferFeeTransactions = $bank->recipientTransactions()->where('transactions.type', TransactionType::TRANSFER_FEE)->whereIn('transactions.status', [ApprovalStatus::APPROVED])->orderBy('id', 'DESC')->get();

        $creditNoteTransactions = [];
        foreach($transferFeeTransactions as $transferFeeTransaction){
            $creditNoteTransactions[] = $transferFeeTransaction->creditNoteTransaction;
        }
        $creditNoteTransactions = new Collection($creditNoteTransactions);

        return [
            'bank' => new BankResource($bank),
            'floatTransactions' => $floatTransactions,
            'transferFeeTransactions' => $transferFeeTransactions,
            'creditNoteTransactions' => $creditNoteTransactions,
            'account_balance' => $floatTransactions->sum('amount') + $transferFeeTransactions->sum('amount') - $creditNoteTransactions->sum('amount'),
        ];

    }

}