$data['name'], 'interval_type' => $data['interval_type'], 'start_date' => $data['start_date'], 'end_date' => $data['end_date'], 'notes' => $data['notes'] ?? null, ]); foreach ($data['budgetItems'] as $itemData) { /** @var BudgetItem $budgetItem */ $budgetItem = $budget->budgetItems()->create([ 'account_id' => $itemData['account_id'], ]); $allocationStart = Carbon::parse($data['start_date']); foreach ($itemData['amounts'] as $periodLabel => $amount) { $allocationEnd = self::calculateEndDate($allocationStart, BudgetIntervalType::parse($data['interval_type'])); $budgetItem->allocations()->create([ 'period' => $periodLabel, 'interval_type' => $data['interval_type'], 'start_date' => $allocationStart->toDateString(), 'end_date' => $allocationEnd->toDateString(), 'amount' => $amount, ]); $allocationStart = $allocationEnd->addDay(); } } return $budget; } private static function calculateEndDate(Carbon $startDate, BudgetIntervalType $intervalType): Carbon { return match ($intervalType) { BudgetIntervalType::Week => $startDate->copy()->endOfWeek(), BudgetIntervalType::Month => $startDate->copy()->endOfMonth(), BudgetIntervalType::Quarter => $startDate->copy()->endOfQuarter(), BudgetIntervalType::Year => $startDate->copy()->endOfYear(), }; } }