<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\UserBalanceRechargeHistory;

class UserBalanceController extends Controller
{
    public function recharge($id, Request $request)
    {
        $user = User::find($id);

        $rechargeList = UserBalanceRechargeHistory::with('recharge_by_user')->where('user_id', $id)
            ->orderBy('id', 'desc');
        return view('user.recharge', [
            'page_title'   => 'User Recharge',
            'user'     => $user,
            'rechargeList' =>  $rechargeList->get()
        ]);
    }



    public function rechargeUpdate($id, Request $request)
    {

        // dd($request->all());

        $this->validate($request, [
            'amount' => 'required|numeric'
        ]);

        DB::beginTransaction();

        try {
            $user = User::find($request->id);
            $curbalance = $user->user_balance ?? 0;
            UserBalanceRechargeHistory::create(
                [
                    'amount' => $request->amount,
                    'after_recharge_balance' => $curbalance + $request->amount,
                    'remarks' => $request->remarks,
                    'user_id' => $id,
                    'recharge_by' => auth()->user()->id
                ]
            );

            User::where('id',$id)->update([
                'user_balance' => $curbalance + $request->amount
            ]);



            DB::commit();
        } catch (\Throwable $th) {
          DB::rollback();
        }


        return redirect()->route('user-recharge', $id)->with('success_message', 'Recharge Success');
    }
}
