<?php

namespace App\Classes\Modules\Transactions\Services;

use Carbon\Carbon;
use App\Models\Company;
use App\Http\Resources\CompanyResource;
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 GeneratesCompanyBalanceAccount
{

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

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


    /**
     * @param Company $company
     */
    public function execute(Company $company) {
        $transferFeeTransactions = $company->issuerTransactions()->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 [
            'company' => new CompanyResource($company),
            'transferFeeTransactions' => $transferFeeTransactions,
            'creditNoteTransactions' => $creditNoteTransactions,
            'account_balance' => $transferFeeTransactions->sum('amount') - $creditNoteTransactions->sum('amount'),
        ];

    }

}