where('parent_id', $pid) ->where('school_year', $schoolYear) ->get() ->toArray(); if (empty($students)) { continue; } $invoice = Invoice::query() ->where('parent_id', $pid) ->where('school_year', $schoolYear) ->latest('created_at') ->first(); if (!$invoice) { $errors[] = "No invoice found for parent ID {$pid} (for refund calc)."; continue; } $refundAmount = $this->feeCalculationService->calculateRefund($students, $pid); $refundAmountByParent[$pid] = $refundAmount; $existingRefund = Refund::query() ->where('invoice_id', $invoice->id) ->first(); if ($existingRefund) { $existingRefund->update([ 'refund_amount' => $refundAmount, 'status' => 'Pending', 'updated_by' => $editorUserId, ]); } else { Refund::query()->create([ 'parent_id' => $pid, 'school_year' => $invoice->school_year, 'invoice_id' => $invoice->id, 'refund_amount' => $refundAmount, 'refund_paid_amount' => 0.0, 'status' => 'Pending', 'requested_at' => now(), 'updated_by' => $editorUserId, ]); } } return [ 'errors' => $errors, 'refundAmountByParent' => $refundAmountByParent, ]; } }