<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Beneficiaries;
use KingFlamez\Rave\Facades\Rave as Flutterwave;
use Illuminate\Http\Request;

class BeneficiaryController extends Controller
{
    //
    public function index(){
        $beneficiaries= Beneficiaries::where('user_id',auth()->id())->latest()->paginate(15);
        return view('user.beneficiary.beneficiary_list', compact('beneficiaries'));
    }

    public function resolveAccount(Request $request){

        $data = [

            'account_number'=>$request->account_number, //'0690000032',//$request['bank_account'],
            'account_bank' =>$request->bank// '044',//$request['bank'];
        ];
     //   dd($request);

        $resolveDetails= Flutterwave::VerifyAccount()->verify($data);
      //  dd($resolveDetails);
       if($resolveDetails['status']=='success'){
           return $resolveDetails['data']['account_name'];
       }else{
           return null;
       }
    }

    public function saveBeneficiary(Request $request){
        $request->validate([
            'account_name'=>'required',
            'account_number'=>'required',
            'bank'=>'required'
        ]);

        $checkifExit = Beneficiaries::where('account_number',$request['account_number'])->where( 'user_id',Auth()->user()->id)->first();
        if($checkifExit)
            return back()->with('error','Account Number Already Exist');

       $benefit = new Beneficiaries();
            $benefit->beneficiary_name= $request['account_name'];
            $benefit->account_number= $request['account_number'];
            $benefit->bank_code= $request['bank'];
            $benefit->bank_name= getBankName($request['bank']);
            $benefit->user_id= Auth()->user()->id;
            $benefit->is_verified= '1';
            $benefit->save();
            if($request->source=='withdraw'){
                return redirect('user/withdraw-money')->with('success','Account Added Successfully, Proceed with your withdraw');

            }
        return redirect('user/beneficiary')->with('success','Account Added Successfuly');


    }
}
