<?php

namespace App\Http\Controllers;

use App\Models\InvestMoney;
use App\Models\ReferenceBalanceModel;
use App\Models\UserLogin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ReferredBalanceController extends Controller
{
    //
    function user_referred_balnce(){
        $sd =  UserLogin::where('Refer_by',Auth::guard('user_login')->user()->Refer_id)->get();

        foreach($sd as $w){
              $ree =  InvestMoney::where('user_id',$w->id)->where('time_period','!=',null)->where('status',1)->get();
            
              
            foreach($ree as $r){
              
                $existingRecord = ReferenceBalanceModel::where('user_id',Auth::guard('user_login')->user()->id)->where('invest_id',$r->id)->first();
                $referred_blnc =  $r->Tk * 0.05;
            
                if(!$existingRecord){
                    ReferenceBalanceModel::create([
                        'user_id'=>Auth::guard('user_login')->user()->id,
                        'refer_to_id'=>$w->id,
                        'refer_to_tk'=>$r->Tk,
                        'invest_id'=>$r->id,
                        'percentage'=>5,
                        'after_percentage'=>$referred_blnc
                    ]);
                }
                
                   
              
               
            }
        }
        $reference_balance = ReferenceBalanceModel::where('user_id',Auth::guard('user_login')->user()->id)->get();
        return view('user.referred_balance',[
            'reference_balance'=>$reference_balance
        ]);
    }
}
