/**
  * @param Budget $budget
  * @param Carbon $date
  * @param        $amount
  *
  * @return BudgetLimit
  */
 public function updateLimitAmount(Budget $budget, Carbon $date, $amount)
 {
     // there should be a budget limit for this startdate:
     /** @var BudgetLimit $limit */
     $limit = $budget->budgetlimits()->where('budget_limits.startdate', $date)->first(['budget_limits.*']);
     if (!$limit) {
         // if not, create one!
         $limit = new BudgetLimit();
         $limit->budget()->associate($budget);
         $limit->startdate = $date;
         $limit->amount = $amount;
         $limit->repeat_freq = 'monthly';
         $limit->repeats = 0;
         $limit->save();
         // likewise, there should be a limit repetition to match the end date
         // (which is always the end of the month) but that is caught by an event.
     } else {
         if ($amount > 0) {
             $limit->amount = $amount;
             $limit->save();
         } else {
             $limit->delete();
         }
     }
     return $limit;
 }
 /**
  * @param Budget $budget
  * @param Carbon $start
  * @param Carbon $end
  * @param string $range
  * @param int    $amount
  *
  * @return BudgetLimit
  */
 public function updateLimitAmount(Budget $budget, Carbon $start, Carbon $end, string $range, int $amount) : BudgetLimit
 {
     // there might be a budget limit for this startdate:
     $repeatFreq = config('firefly.range_to_repeat_freq.' . $range);
     /** @var BudgetLimit $limit */
     $limit = $budget->budgetlimits()->where('budget_limits.startdate', $start)->where('budget_limits.repeat_freq', $repeatFreq)->first(['budget_limits.*']);
     // delete if amount is zero.
     if (!is_null($limit) && $amount <= 0.0) {
         $limit->delete();
         return new BudgetLimit();
     }
     // update if exists:
     if (!is_null($limit)) {
         $limit->amount = $amount;
         $limit->save();
         // fire event to create or update LimitRepetition.
         event(new BudgetLimitUpdated($limit, $end));
         return $limit;
     }
     // create one and return it.
     $limit = new BudgetLimit();
     $limit->budget()->associate($budget);
     $limit->startdate = $start;
     $limit->amount = $amount;
     $limit->repeat_freq = $repeatFreq;
     $limit->repeats = 0;
     $limit->save();
     event(new BudgetLimitStored($limit, $end));
     // likewise, there should be a limit repetition to match the end date
     // (which is always the end of the month) but that is caught by an event.
     // so handled automatically.
     return $limit;
 }