<?php

namespace App\Http\Controllers\Account;

use App\Http\Controllers\Controller;
use App\Models\Investment;

class InvestmentController extends Controller {
    public static function handle() {

        $investments = Investment::active()->get();

        foreach ($investments as $investment) {
            $plan = $investment->plan;

            $interval = convert_singular($plan->increment_interval);
            $intervalMethod = 'add' . $interval;
            $nextReturn = $investment->next_return->copy()->$intervalMethod();

            if ($investment->expires_at->isFuture()) {

                if (now()->greaterThanOrEqualTo($investment->next_return)) {
                    $user = $investment->user;

                    $coinBalance = $user->balances()->where('coin_id', $investment->coin->id)->first();

                    $return = $plan->increment * $investment->amount;

                    $coinBalance->increment('value', $return);

                    $investment->update([
                        'next_return' => $nextReturn,
                    ]);

                    $investment->earnings()->create([
                        'amount' => $return,
                    ]);
                }

            } else {
                $investment->update([
                    'is_active' => false,
                ]);
            }
        }
    }
}
