public function closeReport(CloseReportRequest $request, $id, AppMailer $mailer) { $report = ExpenseReport::findorFail($id)->load('owner', 'users'); if ($report->expenses()->count() == 0) { return redirect()->back()->withErrors('Reports with no expenses cannot be closed. Consider deleting it.'); } if ($report->status == 0) { $report->updateStatus(1); $mailer->sendReportClosedNotification($report); } $oweesAndOwed = $report->oweesAndOwed(); if (!$report->areSettlementsNecessary()) { $messageHeader = 'Settlements for: ' . $report->title; $messageBody = 'No settlements are necessary! All users have paid the right amount towards expenses.'; $report->updateStatus(4); return view('utilities.displayMessage', compact(['messageHeader', 'messageBody', 'report'])); } $owees = $oweesAndOwed['owees']; $oweds = $oweesAndOwed['owed']; $settlements = []; //If there is only 1 owee or 1 owed, then the settlements are pre-determined if (count($owees) == 1 || count($oweds) == 1) { foreach ($owees as $owee) { foreach ($oweds as $owed) { $settlements['settlementowee' . $owee[1]->id . 'owed' . $owed[1]->id] = count($oweds) == 1 ? $owee[0] * -1 : $owed[0]; } } return redirect('/settlements/' . $id . '/add')->with('settlements', $settlements); } return view('expenseReports.close', compact(['report', 'oweesAndOwed'])); }