<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Bill;
use App\Models\DataPlan;
use App\Models\TransactionHistory;
use App\Models\Wallet;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
use KingFlamez\Rave\Facades\Rave as Flutterwave;
use Flutterwave\Payload;
use Flutterwave\Service\VirtualCard;
use Flutterwave\Util\Currency;
class BillController extends Controller
{
    //
    public function index(){
        $bill = Flutterwave::bill()->get_categories();
        dd($bill);
    }

    public function buyAirtime(){
        $wallets = Wallet::where('user_id',auth()->id())->first();

        return view('user.bill.bill_form',compact('wallets'));
    }

    public function buyAirtimeConfirm(Request $request)
    {

        $request->validate([
            'amount'    => 'required|numeric|gt:0',
            'phone_number' => 'required',
            'password'=>'required',
            'wallet'=>'required'

        ]);
        $phone_number = toPhoneNumber($request->phone_number);
        if(empty($phone_number)){
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid Phone Number Format'
            ], 400);
        }

        if (!(Hash::check( $request->password, Auth()->user()->getAuthPassword()))) {
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid Password Please Retry'
            ], 400);
        }
        //$checkBeneficiary = validatePhoneNumber(Auth()->user()->id, $request['beneficiary']);

      /*  if(!$checkBeneficiary){
            return response()->json([
                'status' => 'error',
                'message' => 'Beneficiary Not Found'
            ], 400);
            // return back()->with('error','Beneficiary Not Found');
        }*/

        $wallet = Auth()->user()->getMyWallet();
        if(!$wallet){
            return response()->json([
                'status' => 'error',
                'message' => 'Wallet Not Found'
            ], 400);
            // return back()->with('error','Wallet not found');
        }


        //if($request->amount < $method->min_amount || $request->amount > $method->max_amount){
        /* if($request->amount < $wallet->amount > $method->max_amount){
             return back()->with('error','Please follow the limit');
         }
 */
        // $charge = chargeCalc($method,$request->amount);
        $billAmount =  numFormat($request->amount);
        $walletType = $request->wallet;
        if($walletType=='balance') {
            if ($wallet->balance < $billAmount) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Insufficient balance'
                ], 400);
            }
            $wallet->balance -=  $billAmount;
        }else if($walletType=='bonus'){
            if ($wallet->refer_bonus_balance < $billAmount) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Insufficient balance'
                ], 400);
            }
            $wallet->refer_bonus_balance -=  $billAmount;
        }
        $reference = Flutterwave::generateReference();

        // $wallet->save();
        $bill              = new Bill();
        $bill->trx         = str_rand().time();
        $bill->user_id     = auth()->id();
        $bill->descriptions = toMoney($billAmount). ' Airtime to '. $request->phone_number;
        $bill->amount      = $billAmount;
        $bill->bill_to = $phone_number;
        $bill->bill_type = 'Airtime';
        $bill->status ='Initiated';
        $bill->refer_by = Auth()->user()->refer_by;
        $bill->refer_rate = '0.01';
        $bill->refer_bonus = $billAmount * 0.01;
        $bill->reference_no= 'R2T-BILL'.$reference;

        $bill->save();
        $data = [
            "country" => "NG",
            "customer" =>$phone_number,
            "amount" => $billAmount,
            "type" => "AIRTIME",
            "reference" => Flutterwave::generateReference(),

        ];

        $billPayment = Flutterwave::bill()->airtime($data);
        if($billPayment['status']=='success') {
            $bill->status='success';
            if(!empty($bill->refer_by)){
                Auth()->user()->saveToClientWalletBonus($bill->refer_bonus,$bill->refer_by,'refer', 'Airtime',$bill->user_id);
            }
            $wallet->save();
        }



        //return redirect('dashboard');
        return response()->json([
            'status' => 'success',
            'message' => 'Operation is initiated'
        ], 200);
        // return back()->with('success','Withdraw request has been submitted successfully.');
    }

    public function history()
    {
        $bills = Bill::where('user_id',auth()->id())->latest()->paginate(15);
        return view('user.bill.history',compact('bills'));
    }

    public function updateData(){

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.oneappgo.com/v1/databundle',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array('datacode' => 'mtn500gift','network_id' => '2','phoneno' => '08067166444','reference' => 'DJIEJ2MEUE2EN34'.time(),'dtype' => 'sme'),
            CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer 1applive_sk_486ee2af3ec5b208fc2ad42b79ce2de9'
            ),
        ));

        $response = curl_exec($curl);


        curl_close($curl);
        dd($response);
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.oneappgo.com/v1/getdataplans?provider=ETISALAT',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer 1applive_pb_85d59633f745ec8126f5732f27d01020'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        $result=  json_decode($response, true);
        $desiredDataCode='etisalat500cg';
        $filteredData = array_filter($result['data'], function ($item) use ($desiredDataCode) {
            return $item['datacode'] === $desiredDataCode;
        });
       var_dump($filteredData);

        //var_dump($result['data']);
    }

    public function getDataBundle(Request $request){

            $result = getDataPlan($request->network);


                return response()->json([
                    'data' => $result,
                    'status' => 'success'
                ], 200);


    }

    public function buyData(){
        $wallets = Wallet::where('user_id',auth()->id())->first();

        return view('user.bill.buy_data',compact('wallets'));
    }



    public function buyDataConfirm(Request $request)
    {



        $request->validate([
            'data_plan'    => 'required',
            'network'=>'required',
            'phone_number' => 'required|numeric',
            'password'=>'required',
            'wallet'=>'required'

        ]);
        $phone_number = convertDataPhone($request->phone_number);
        if(empty($phone_number)){
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid Phone Number Format'
            ], 400);
        }
        $network =$request->network;
        $data_plan =$request->data_plan;
        $phone_number = convertDataPhone($request->phone_number);
        $dataBundle = Dataplan::where('network',$network)->where('datacode',$data_plan)->firstOrFail();
        $selectedPlan = $request->data_plan;

        if(empty($dataBundle)){
            return response()->json([
                'status' => 'error',
                'message' => 'Unknown Data Plan Please retry again'
            ], 400);
        }
                $billAmount=$dataBundle->price;
                $dataType=$dataBundle->dtype;
                $planName = $dataBundle->pname;





        if (!(Hash::check( $request->password, Auth()->user()->getAuthPassword()))) {
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid Password Please Retry'
            ], 400);
        }


        $wallet = Auth()->user()->getMyWallet();
        if(!$wallet){
            return response()->json([
                'status' => 'error',
                'message' => 'Wallet Not Found'
            ], 400);
            // return back()->with('error','Wallet not found');
        }

        $walletType = $request->wallet;
        if($walletType=='balance') {
            if ($wallet->balance < $billAmount) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Insufficient balance'
                ], 400);
            }
            $wallet->balance -=  $billAmount;
        }else if($walletType=='bonus'){
            if ($wallet->refer_bonus_balance < $billAmount) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Insufficient balance'
                ], 400);
            }
            $wallet->refer_bonus_balance -=  $billAmount;
        }

       $networkId= getNetwork($network);

        $reference='R2TDATA'.str_rand().time().Auth()->user()->id;
        // $wallet->save();
        $bill              = new Bill();
       // $bill->trx         = str_rand().time();
        $bill->user_id     = auth()->id();
        $bill->descriptions = 'Purchase of '.$planName. ' to '. $request->phone_number;
        $bill->amount      = $billAmount;
        $bill->bill_to = $phone_number;
        $bill->bill_type = 'Data';
        $bill->bill_plan = $selectedPlan;
        $bill->bill_network = $network;
        $bill->status ='Initiated';
        $bill->refer_by = Auth()->user()->refer_by;
        $bill->refer_rate = '0.015';
        $bill->refer_bonus = $billAmount * 0.015;
        $bill->reference_no= 'R2T-BILL'.$reference;

        $bill->save();
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.oneappgo.com/v1/databundle',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array('datacode' => $selectedPlan,'network_id' => $networkId,'phoneno' => $phone_number,'reference' => $reference,'dtype' => $dataType),
            CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer '.env('BILL_SECRET')
            ),
        ));

        $response = curl_exec($curl);


        curl_close($curl);
        $result = json_decode($response, true);
//dd($result);
        if($result['status']=='success' || $result['status']) {
            $bill->status='successful';
            $bill->trx=$result['txref'];
            if(!empty($bill->refer_by)){
                Auth()->user()->saveToClientWalletBonus($bill->refer_bonus,$bill->refer_by,'refer', 'Data',$bill->user_id);
            }
            $wallet->save();

            $bill->save();
            TransactionHistory::create([
                'descriptions' =>$bill->descriptions,
                'trade_id' => null,
                'request_id' => $bill->id,
                'tradedcard_details_id' => null,
                'transaction_ref' => $result['txref'],
                'user_id' => $bill->user_id,
                'amount' =>$billAmount,
                'exchange_rate'=>1,
                'transaction_amount_in_usd'=>0,
                'transaction_type' => 'Debit',
                'created_by' => $bill->user_id,
                'source' => 'Data',
                'status' => 'success',
                'status_at' => now(),
                'status_by' => $bill->user_id,
                'status_reason' => "Successful",
                'refer_bonus' => $bill->refer_bonus,
                'referer_user_id' => auth()->user()->refer_by,
                'rate' => null,
                'currency' => "NGN",
            ]);
            return response()->json([
                'status' => 'success',
                'message' => 'Operation is '.$bill->status,
            ], 200);
        }else{
            return response()->json([
                'status' => 'error',
                'message' => 'Error Performing this operation please try again later',
            ], 400);
        }






    }


    public function buyCable(){
       // getCableList('dd');
        $wallets = Wallet::where('user_id',auth()->id())->first();

        return view('user.bill.buy_cable',compact('wallets'));
    }

    public function getTVSub(Request $request){

        $result = getCableList($request->network);


        return response()->json([
            'data' => $result,
            'status' => 'success'
        ], 200);


    }
    public function verifyICU(Request $request){
        $request->validate([
            'cable_type'    => 'required',
            'icu_no' => 'required'


        ]);


        $result = verifyICU($request->cable_type, $request->icu_no);
       // dd($result);
        return response()->json([
            'data' => $result,
            'status' => 'success'
        ], 200);


    }



    public function buyCableConfirm(Request $request)
    {



        $request->validate([
            'data_plan'    => 'required',
            'cable_type'=>'required',
            'icu_no' => 'required|numeric',
            'password'=>'required',
            'wallet'=>'required'

        ]);
        $icuVerify = verifyICU( $request->cable_type, $request->icu_no);
       // dd($icuVerify);

        if(empty($icuVerify)){
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid IUC Number'
            ], 400);
        }
        $network =$request->cable_type;
        $icu_no = $request->icu_no;
        $dataBundle = getCableList($network);
        $selectedPlan = $request->data_plan;
       // dd($selectedPlan);
        $customerName = $icuVerify['custname'];
        $customerNo = $icuVerify['custno'];

//dd($customerNo);
        //dd($dataBundle);
        /*  $filteredData = array_filter($dataBundle, function ($item) use ($selectedPlan) {
            return   $item['datacode'] === $selectedPlan;
          });*/
        $billAmount =  0;//$filteredData['price'];
        $dataType = null;//$filteredData['dtype'];
        $planName= null;
       // dd($dataBundle);
        for($d=0; $d<=count($dataBundle)-1; $d++){
            $dataDetails = $dataBundle[$d];
            if($dataDetails['code']==$selectedPlan){
                $billAmount=$dataDetails['price'];
                $dataType=$dataDetails['type'];
                $planName = $dataDetails['name'];
                break;
            }
        }

       // dd($billAmount);


        if($billAmount<=0){
            return response()->json([
                'status' => 'error',
                'message' => 'Unknown Subscription Plan Please retry again'
            ], 400);
        }
        //  var_dump($filteredData);
        //$filteredData=$filteredData[0];


        if (!(Hash::check( $request->password, Auth()->user()->getAuthPassword()))) {
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid Password Please Retry'
            ], 400);
        }
        //$checkBeneficiary = validatePhoneNumber(Auth()->user()->id, $request['beneficiary']);

        /*  if(!$checkBeneficiary){
              return response()->json([
                  'status' => 'error',
                  'message' => 'Beneficiary Not Found'
              ], 400);
              // return back()->with('error','Beneficiary Not Found');
          }*/

        $wallet = Auth()->user()->getMyWallet();
        if(!$wallet){
            return response()->json([
                'status' => 'error',
                'message' => 'Wallet Not Found'
            ], 400);
            // return back()->with('error','Wallet not found');
        }


        //if($request->amount < $method->min_amount || $request->amount > $method->max_amount){
        /* if($request->amount < $wallet->amount > $method->max_amount){
             return back()->with('error','Please follow the limit');
         }
 */
        // $charge = chargeCalc($method,$request->amount);

        $walletType = $request->wallet;
        $billAmount=$billAmount+50;
        if($walletType=='balance') {
            if ($wallet->balance < $billAmount) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Insufficient balance'
                ], 400);
            }
            $wallet->balance -=  $billAmount;
        }else if($walletType=='bonus'){
            if ($wallet->refer_bonus_balance < $billAmount) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Insufficient balance'
                ], 400);
            }
            $wallet->refer_bonus_balance -=  $billAmount;
        }
        // dd($billAmount);

//send to load data

        //dd($result);
        // $reference = Flutterwave::generateReference();
        // dd($network);
       // $networkId= getNetwork($network);

        $reference='R2TCABLE'.str_rand().time().Auth()->user()->id;
        // $wallet->save();
        $bill              = new Bill();
        // $bill->trx         = str_rand().time();
        $bill->user_id     = auth()->id();
        $bill->descriptions = 'Cable TV Subscription of '.$planName. ' for Customer: '.$customerName.', Customer No: '.$customerNo;
        $bill->amount      = $billAmount;
        $bill->bill_to = $icu_no;
        $bill->bill_type = 'Cable';
        $bill->bill_plan = $selectedPlan;
        $bill->bill_network = $network;
        $bill->status ='Initiated';
        $bill->refer_by = Auth()->user()->refer_by;
        $bill->refer_rate = '';
        $bill->refer_bonus = 25;
        $bill->reference_no= 'R2T-BILL'.$reference;

        $bill->save();
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.oneappgo.com/v1/cabletv',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array('tvno' => $icu_no,'amount' => $billAmount-50,'tv' => $network,'custname' => $customerName,'custno' => $customerNo),
            CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer '.env('BILL_SECRET')
            ),
        ));

        $response = curl_exec($curl);


        curl_close($curl);
        $result = json_decode($response, true);

      if(!empty($response)) {
          if ($result['status']) {
              $bill->status = 'successful';
              $bill->trx = $result['txref'];
              if (!empty($bill->refer_by)) {
                  Auth()->user()->saveToClientWalletBonus($bill->refer_bonus, $bill->refer_by, 'refer', 'Cable', $bill->user_id);
              }
              $wallet->save();
              $bill->save();
              TransactionHistory::create([
                  'descriptions' =>$bill->descriptions,
                  'trade_id' => null,
                  'request_id' => $bill->id,
                  'tradedcard_details_id' => null,
                  'transaction_ref' => $result['txref'],
                  'user_id' => $bill->user_id,
                  'amount' =>$billAmount,
                  'exchange_rate'=>1,
                  'transaction_amount_in_usd'=>0,
                  'transaction_type' => 'Debit',
                  'created_by' => $bill->user_id,
                  'source' => 'CableTv',
                  'status' => 'success',
                  'status_at' => now(),
                  'status_by' => $bill->user_id,
                  'status_reason' => "Successful",
                  'refer_bonus' => $bill->refer_bonus,
                  'referer_user_id' => auth()->user()->refer_by,
                  'rate' => null,
                  'currency' => "NGN",
              ]);
              return response()->json([
                  'status' => 'success',
                  'message' => 'Operation is ' . $bill->status,
              ], 200);
          }
      }

          else {
              {
                  $bill->status = 'Unsuccessful';
                  $bill->trx = $result['txref'];
                  $bill->save();
                  return response()->json([
                      'status' => 'error',
                      'message' => $result['message'],
                  ], 400);
              }


          }
        //return redirect('dashboard');

        // return back()->with('success','Withdraw request has been submitted successfully.');
    }

    public function buyElectricity(){
        // getCableList('dd');
        $wallets = Wallet::where('user_id',auth()->id())->first();
       $providers= getElectricityProvider();

        return view('user.bill.buy_electricity',compact('wallets','providers'));
    }

    public function verifyMeterNo(Request $request){
        $request->validate([
            'provider'    => 'required',
            'meter_no' => 'required'


        ]);


        $result = verifyMeterNo($request->provider, $request->meter_no);
        if(empty($result)){
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid Account Number(Meter No) Please Check Your Input',
            ], 400);
        }else{
            return response()->json([
                'data' => $result,
                'status' => 'success'
            ], 200);
        }



    }


    public function buyElectricityConfirm(Request $request)
    {



        $request->validate([
            'amount'    => 'required|numeric',
            'provider'=>'required',
            'meter_no' => 'required',
            'password'=>'required',
            'wallet'=>'required'

        ]);
        $meterVerify = verifyMeterNo( $request->provider, $request->meter_no);
        // dd($icuVerify);

        if(empty($meterVerify)){
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid Account Number'
            ], 400);
        }
        $network =$request->provider;
        $meter_no = $request->meter_no;
      //  $dataBundle = getCableList($network);

        $customerName = $meterVerify['namne'];
        //$customerNo = $meterVerify['custno'];
        $customerAddress = $meterVerify['address'];
        $vendType = $meterVerify['vendtype'];


        //dd($dataBundle);
        /*  $filteredData = array_filter($dataBundle, function ($item) use ($selectedPlan) {
            return   $item['datacode'] === $selectedPlan;
          });*/
        $billAmount =  $request->amount+50;//$filteredData['price'];
        $dataType = null;//$filteredData['dtype'];
        $planName= null;
        // dd($dataBundle);
      /*  for($d=0; $d<=count($dataBundle)-1; $d++){
            $dataDetails = $dataBundle[$d];
            if($dataDetails['code']==$selectedPlan){
                $billAmount=$dataDetails['price'];
                $dataType=$dataDetails['type'];
                $planName = $dataDetails['name'];
                break;
            }
        }


        if(empty($dataBundle)){
            return response()->json([
                'status' => 'error',
                'message' => 'Unknown Subscription Plan Please retry again'
            ], 400);
        }
      */
        //  var_dump($filteredData);
        //$filteredData=$filteredData[0];


        if (!(Hash::check( $request->password, Auth()->user()->getAuthPassword()))) {
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid Password Please Retry'
            ], 400);
        }
        //$checkBeneficiary = validatePhoneNumber(Auth()->user()->id, $request['beneficiary']);

        /*  if(!$checkBeneficiary){
              return response()->json([
                  'status' => 'error',
                  'message' => 'Beneficiary Not Found'
              ], 400);
              // return back()->with('error','Beneficiary Not Found');
          }*/

        $wallet = Auth()->user()->getMyWallet();
        if(!$wallet){
            return response()->json([
                'status' => 'error',
                'message' => 'Wallet Not Found'
            ], 400);
            // return back()->with('error','Wallet not found');
        }


        //if($request->amount < $method->min_amount || $request->amount > $method->max_amount){
        /* if($request->amount < $wallet->amount > $method->max_amount){
             return back()->with('error','Please follow the limit');
         }
 */
        // $charge = chargeCalc($method,$request->amount);

        $walletType = $request->wallet;
        if($walletType=='balance') {
            if ($wallet->balance < $billAmount) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Insufficient balance'
                ], 400);
            }
            $wallet->balance -=  $billAmount;
        }else if($walletType=='bonus'){
            if ($wallet->refer_bonus_balance < $billAmount) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Insufficient balance'
                ], 400);
            }
            $wallet->refer_bonus_balance -=  $billAmount;
        }
        // dd($billAmount);

//send to load data

        //dd($result);
        // $reference = Flutterwave::generateReference();
        // dd($network);
        // $networkId= getNetwork($network);

        $reference='R2TDATA'.str_rand().time().Auth()->user()->id;
        // $wallet->save();
        $bill              = new Bill();
        // $bill->trx         = str_rand().time();
        $bill->user_id     = auth()->id();
        $bill->descriptions = 'Electricity Bill Payment for '.$request->meter_no. ' for Customer: '.$customerName.', Address: '.$customerAddress;
        $bill->amount      = $billAmount;
        $bill->bill_to = $meter_no;
        $bill->bill_type = 'Electricity';
        $bill->bill_plan = $billAmount;
        $bill->bill_network = $network;
        $bill->status ='Initiated';
        $bill->refer_by = Auth()->user()->refer_by;
        $bill->refer_rate = '';
        $bill->refer_bonus = 25;
        $bill->reference_no= 'R2T-BILL'.$reference;

        $bill->save();
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.oneappgo.com/v1/cabletv',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array('meterno' => $meter_no,'provider'=>$network, 'amount' => $billAmount-50,'vendtype' => $vendType,'metername' => $customerName),
            CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer '.env('BILL_SECRET')
            ),
        ));

        $response = curl_exec($curl);


        curl_close($curl);
        $result = json_decode($response, true);

        //  dd($result);
        if($result['status']) {
            $bill->status='successful';
            $bill->trx=$result['txref'];
            if(!empty($bill->refer_by)){
                Auth()->user()->saveToClientWalletBonus($bill->refer_bonus,$bill->refer_by,'refer', 'Cable',$bill->user_id);
            }
            $wallet->save();
            $bill->save();
            return response()->json([
                'status' => 'success',
                'message' => 'Operation is '.$bill->status,
            ], 200);
        }else{
            $bill->status='Unsuccessful';
            $bill->trx=$result['txref'];
            $bill->save();
            return response()->json([
                'status' => 'error',
                'message' => $result['message'],
            ], 400);
        }



        //return redirect('dashboard');

        // return back()->with('success','Withdraw request has been submitted successfully.');
    }

    public function dataPlan(){
        $dd = getDataPlan('9MOBILE');
        dd($dd);
    }

    public function testCard()
    {
        $requestData = [
            'currency' => "USD",
            'amount' => '5',
            'first_name' => "Alex",
            'last_name' => "Akinwande",
            'date_of_birth' => "1999/01/01", // Use actual date of birth in YYYY-MM-DD format
            'email' => "alex@example.com", // Use a valid email
            'phone' => "2348123456789", // Use a valid phone number
            'title' => "Mr",
            'gender' => "M", // M or F
            'billing_name' => "Alex Akinwande",
            'billing_address' => "123 Test Street",
            'billing_city' => "Ado Ekiti",
            'billing_state' => "Ekiti",
            'billing_postal_code' => "360001",
            'billing_country' => "NG", // Use ISO 2-letter country code
            'callback_url' => "https://webhook.site/5e9f9b9b-5e9f-4b9b-9b9b-5e9f9b9b5e9f" // Use a valid callback URL // Consider providing a valid callback URL
        ];

        $response = Http::withHeaders([
            'Authorization' => 'Bearer FLWSECK-77cbd25bc38084dc8dd9ded62d209088-18db480b48evt-X',
            'Content-Type' => 'application/json',
        ])->post('https://api.flutterwave.com/v3/virtual-cards', $requestData);

        // Log the full response
        \Log::info('Flutterwave API Response', [
            'status' => $response->status(),
            'body' => $response->json(),
        ]);

        // Check if the request was successful
        if ($response->successful()) {
            $cardData = $response->json()['data'];
            return response()->json([
                'message' => 'Virtual card created successfully',
                'card' => $cardData
            ], 201);
        } else {
            // If not successful, return the error details
            return response()->json([
                'message' => 'Failed to create virtual card',
                'errors' => $response->json(),
                'status' => $response->status()
            ], $response->status());
        }
    }
      /*  } catch (\Exception $e) {
            Log::error('Error creating virtual card: ' . $e->getMessage());

            return response()->json([
                'message' => 'An error occurred while creating the virtual card'
            ], 500);
        }*/



}
