<?php

namespace App\Http\Controllers\API;

#Model
use App\User;
use App\Models\Payment;
use App\Models\PaymentHistory;
use App\Models\DebitPayment;
use App\Models\UserWinnersAmount;
use App\Models\PaymentNewHistory;
use App\Models\AppDetail;
use App\Models\FundRequests;
use App\Models\ImbHistory;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use GuzzleHttp\Client;
#Other Class
use DB;
use Carbon\Carbon;
use App\Traits\FirebaseTraits;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Kreait\Firebase\Factory;
use App\Http\Controllers\API\BaseController as BaseController;

class PaymentController extends BaseController
{

    use FirebaseTraits;
    #Bind Payment model
    protected $appDetail;
    #Bind Payment model
    protected $payment;

    #Bind PaymentHistory model
    protected $paymentHistory;

    #Bind UserWinnersAmount model
    protected $userWinnersAmount;

    #Bind DebitPayment model
    protected $debitPayment;

    #Bind FundRequests model
    protected $fundRequest;

    #Bind ImbHistory model
    protected $imbHistory;



    /**
     * Defining the default constructor for controller
     *
     */
    public function __construct(
        FundRequests                   $fundRequest,
        AppDetail                   $appDetail,
        User                           $user,
        Payment                        $payment,
        UserWinnersAmount              $userWinnersAmount,
        PaymentNewHistory              $paymentNewHistory,
        PaymentHistory                 $paymentHistory,
        ImbHistory                 $imbHistory,
        DebitPayment                   $debitPayment
    ) {
        $this->fundRequest              = $fundRequest;
        $this->debitPayment             = $debitPayment;
        $this->payment                  = $payment;
        $this->paymentHistory           = $paymentHistory;
        $this->userWinnersAmount        = $userWinnersAmount;
        $this->paymentNewHistory        = $paymentNewHistory;
        $this->appDetail        = $appDetail;
        $this->imbHistory        = $imbHistory;
        $this->user                     = $user;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
     
     
     public function webhook(Request $request){
        file_put_contents(
            public_path('webhook_log.txt'),
            print_r($request->all(), true),
            FILE_APPEND
        );

        // Fetch main parameters
        $status   = $request->input('status', '');
        $orderId  = $request->input('order_id', '');
        $result   = $request->input('result', []);

        // If "result" is JSON string, decode it
        if (is_string($result)) {
            $result = json_decode($result, true);
        }

        // Extract nested data
        $txnStatus = $result['txnStatus'] ?? '';
        $amount    = $result['amount'] ?? '';
        $utr       = $result['utr'] ?? '';
        $mobile    = $result['customer_mobile'] ?? '';
        $email     = $result['remark1'] ?? '';

        // Payment validation
        if ($status === 'SUCCESS' && $txnStatus === 'COMPLETED') {
            // Update wallet or database here
            
            $fund = $this->fundRequest->where('order_id',$orderId)->first();
            
            
             if($fund->status && $fund->payment_created != 3){
                        
                        $paymentchecck = Payment::where('user_id',$fund->user_id)->first();
                        if(!empty($paymentchecck)){
                                $paymentchecck->amount = $paymentchecck->amount+$fund->amount;
                                $paymentchecck->save();
                                $paymentid = $paymentchecck->id;
                        }else{
                            #get the requested data in Data variable
                              $data = [
                                'payment_id' =>1,
                                'amount'       => $fund->amount,
                                'user_id'    => $fund->user_id,
                                ];
                            #store the newly creted resoures
                           $paymentchecck = Payment::create($data);
                             $paymentid = $paymentchecck->id;
                        }
            
            
                        $data = [
                                'debit_amount'       => 0,
                                'credit_amount'       => $fund->amount,
                                'user_id'    => $fund->user_id,
                                'created_by'        =>$fund->user_id,
                                ];
                            #store the newly creted resoures
                            DebitPayment::create($data);
            
                        $paymentHistorychecck = PaymentHistory::where('user_id',$fund->user_id)->first();
                   
                        if(!empty($paymentHistorychecck)){
                            $remainamount =$paymentHistorychecck->remain_amount+$fund->amount;
                                $paymentHistorychecck->total_amount = $paymentHistorychecck->total_amount+$fund->amount;
                                $paymentHistorychecck->remain_amount =  $remainamount;
                                $paymentHistorychecck->save();
                               
                        }else{
                            #get the requested data in Data variable
                              $data = [
                                'total_amount'       => $fund->amount,
                                'remain_amount'      => $fund->amount,
                                'debit_total_amount' => 0,
                                'user_id'    => $fund->user_id,
                                ];
                            #store the newly creted resoures
                            PaymentHistory::create($data);
                             $remainamount = $fund->amount;
                        }
                        
                           $data = [
                                'reamount' =>$remainamount ,
                                    'remark' => $fund->amount.' Points added by you',
                                'amount'       => $fund->amount,
                                'payment_id'      => $paymentid,
                                'type'            => 'add',
                                'user_id'    => $fund->user_id,
                                'order_id'  => $fund->order_id,
                                ];
                            #store the newly creted resoures
                            PaymentNewHistory::create($data);
                            
                            
                              $postcust = User::whereId($fund->user_id)->first();
                                $user_id = $fund->user_id;
                                $name = $postcust->name;
                                $body = 'Dear '.$name .' '.$fund->amount.' Points added by you	';
                                $title = "Point Added";
                                $this->notificationUser($title,$body,$user_id);
                        
                      
                      $fundcheck = $this->fundRequest->whereId($fund->id)->first();
            
                        $fundcheck->payment_created = 3;
                        $fundcheck->status = 0;
                        $fundcheck->save();
                        
                        
                        $this->imbHistory->create([
                            'order_id' => $fund->order_id,
                            'status' => 3,
                            ]);
            
            
               
                
            
            
            return response("✅ Payment Success for Order ID: $orderId", 200);
            
             }
        }

        return response("❌ Payment Failed or Incomplete.", 400);
     }
     
     public function paymentCheck(){
         
         $appSetup = $this->appDetail->first();
        
        $fundRequest = $this->fundRequest->whereNotIn('payment_created',[2,3])->where('status',1)->orderBy('id','DESC')->get();
        
      
            $client = new Client();
        
        foreach($fundRequest as $key => $value){
            
            try{
                 $checkStatus = $this->fundRequest->where('id',$value->id)->first();
                
                    
                if($checkStatus->payment_created == 1){
                
           
            
            // Make the GET request with the 'date' parameter
            $response = $client->request('POST', 'https://pay.imb.org.in/api/check-order-status', [
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded'
                ],
                'form_params' => [
                    "user_token" => $appSetup->api_token,
                    "order_id" => $value->order_id,
                ]
            ]);

            $data = json_decode($response->getBody(), true);
            
          
            // Check if the 'data' key exists in the response array
            if (isset($data['result'])) {
                
                    if($data['status'] == "COMPLETED"){
                        
                        
                        $fund = $this->fundRequest->whereId($value->id)->first();
            
                        $fund->payment_created = 2;
                        $fund->save();
                        
                        $this->imbHistory->create([
                            'order_id' => $value->order_id,
                            'status' => 2,
                            ]);
                        
                    }
                    
            }
            
           
            
            }
            
        }catch(\Exception $ex)
                {
                    
                   
                }
        }
        
        return 'success';
     }
     
     public function paymentSettle(){
         
         
        $appSetup = $this->appDetail->first();
        
        $fundRequest = $this->fundRequest->whereNotIn('payment_created',[1,3])->where('status',1)->orderBy('id','DESC')->get();
        
        
        foreach($fundRequest as $key => $fund){
            
            
            try{
                
                $checkStatus = $this->fundRequest->where('id',$fund->id)->first();
                
                if($checkStatus->payment_created == 2){
            
            
                        
                        $paymentchecck = Payment::where('user_id',$fund->user_id)->first();
                        if(!empty($paymentchecck)){
                                $paymentchecck->amount = $paymentchecck->amount+$fund->amount;
                                $paymentchecck->save();
                                $paymentid = $paymentchecck->id;
                        }else{
                            #get the requested data in Data variable
                              $data = [
                                'payment_id' =>1,
                                'amount'       => $fund->amount,
                                'user_id'    => $fund->user_id,
                                ];
                            #store the newly creted resoures
                           $paymentchecck = Payment::create($data);
                             $paymentid = $paymentchecck->id;
                        }
            
            
                        $data = [
                                'debit_amount'       => 0,
                                'credit_amount'       => $fund->amount,
                                'user_id'    => $fund->user_id,
                                'created_by'        =>$fund->user_id,
                                ];
                            #store the newly creted resoures
                            DebitPayment::create($data);
            
                        $paymentHistorychecck = PaymentHistory::where('user_id',$fund->user_id)->first();
                   
                        if(!empty($paymentHistorychecck)){
                            $remainamount =$paymentHistorychecck->remain_amount+$fund->amount;
                                $paymentHistorychecck->total_amount = $paymentHistorychecck->total_amount+$fund->amount;
                                $paymentHistorychecck->remain_amount =  $remainamount;
                                $paymentHistorychecck->save();
                               
                        }else{
                            #get the requested data in Data variable
                              $data = [
                                'total_amount'       => $fund->amount,
                                'remain_amount'      => $fund->amount,
                                'debit_total_amount' => 0,
                                'user_id'    => $fund->user_id,
                                ];
                            #store the newly creted resoures
                            PaymentHistory::create($data);
                             $remainamount = $fund->amount;
                        }
                        
                           $data = [
                                'reamount' =>$remainamount ,
                                    'remark' => $fund->amount.' Points added by you',
                                'amount'       => $fund->amount,
                                'payment_id'      => $paymentid,
                                'type'            => 'add',
                                'user_id'    => $fund->user_id,
                                'order_id'  => $fund->order_id,
                                ];
                            #store the newly creted resoures
                            PaymentNewHistory::create($data);
                            
                            
                              $postcust = User::whereId($fund->user_id)->first();
                                $user_id = $fund->user_id;
                                $name = $postcust->name;
                                $body = 'Dear '.$name .' '.$fund->amount.' Points added by you	';
                                $title = "Point Added";
                                $this->notificationUser($title,$body,$user_id);
                        
                      
                      $fundcheck = $this->fundRequest->whereId($fund->id)->first();
            
                        $fundcheck->payment_created = 3;
                        $fundcheck->status = 0;
                        $fundcheck->save();
                        
                        
                        $this->imbHistory->create([
                            'order_id' => $fund->order_id,
                            'status' => 3,
                            ]);
            
            
               
                
            }
            }catch(\Exception $ex)
                {
                   
                }
        }
        
        return 'success';
     }
     
     
    public function index()
    {
        try {
            #Stat get 
            $success['waletanount'] = $this->paymentHistory->select('remain_amount as walletamount')->where('user_id', auth('api')->user()->id)->first();

            #return response with active state
            return $this->sendResponse($success, 'walet.');
        } catch (\Exception $ex) {
            return $this->sendError('Validation Error.', $ex->getMessage());
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */

    public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            $validator = Validator::make($request->all(), [
                'payment_id' => 'required',
                'amount' => 'required',
                'payment_status' => 'required',
            ]);

            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }
            #get the requested data in Data variable
            $data = [
                'payment_id'              => $request->payment_id,
                'amount'                  => $request->amount,
                'payment_status'          => $request->payment_status,
                'user_id'                 => auth('api')->user()->id,

            ];
            #store the newly creted resoures
            $this->payment->create($data);
            $amount = $request->amount;
            $paymentHistorycheck = PaymentHistory::where('user_id', auth('api')->user()->id)->first();
            if (!empty($paymentHistorycheck)) {
                $paymentHistorycheck->total_amount   = $paymentHistorycheck->total_amount + $amount;
                $paymentHistorycheck->remain_amount = $paymentHistorycheck->remain_amount + $amount;
                $paymentHistorycheck->save();
                $remain_amount = $paymentHistorycheck->remain_amount;
            } else {
                $data = [
                    'total_amount'        => $amount,
                    'remain_amount'       => $amount,
                    'debit_total_amount'  => 0,
                    'user_id'             => auth('api')->user()->id,

                ];
                #store the newly creted resoures
                $this->paymentHistory->create($data);
                $remain_amount =  $amount;
            }


            $success['payment']  =  $remain_amount;
            DB::commit();
            return $this->sendResponse($success, 'Payment Created successfully.');
        } catch (\Exception $ex) {
            DB::rollback();
            return $this->sendError('error.', $ex->getMessage());
        }
    }

    public function addMoney(Request $request)
    {
        DB::beginTransaction();
        try {

            $validator = Validator::make($request->all(), [
                'amount' => 'required',
            ]);

            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors());
            }

            $userid = auth('api')->user()->id;
            $paymentchecck = $this->payment->where('user_id', $userid)->first();
            if (!empty($paymentchecck)) {
                $paymentchecck->amount = $paymentchecck->amount + $request->amount;
                $paymentchecck->save();
                $paymentid = $paymentchecck->id;
            } else {
                #get the requested data in Data variable
                $data = [
                    'payment_id'   => 1,
                    'amount'       => $request->amount,
                    'user_id'      => $userid,
                ];
                #store the newly creted resoures
                $paymentchecck = $this->payment->create($data);
                $paymentid = $paymentchecck->id;
            }

            $data = [
                'debit_amount'        => 0,
                'credit_amount'       => $request->amount,
                'user_id'             => $userid,
                'created_by'          => $userid,
            ];

            #store the newly created resoures
            $this->debitPayment->create($data);

            $paymentHistorychecck = $this->paymentHistory->where('user_id', $userid)->first();

            if (!empty($paymentHistorychecck)) {
                $remainamount = $paymentHistorychecck->remain_amount + $request->amount;
                $paymentHistorychecck->total_amount = $paymentHistorychecck->total_amount + $request->amount;
                $paymentHistorychecck->remain_amount =  $remainamount;
                $paymentHistorychecck->save();
            } else {
                #get the requested data in Data variable
                $data = [
                    'total_amount'       => $request->amount,
                    'remain_amount'      => $request->amount,
                    'debit_total_amount' => 0,
                    'user_id'    => $userid,
                ];
                #store the newly creted resoures
                $this->paymentHistory->create($data);
                $remainamount = $request->amount;
            }

            $data = [
                'reamount'       => $remainamount,
                'remark'         => $request->amount . ' Points added by User',
                'amount'         => $request->amount,
                'payment_id'     => $paymentid,
                'type'           => 'add',
                'user_id'        => $userid,
            ];
            #store the newly creted resoures
            $this->paymentNewHistory->create($data);


            $postcust = $this->user->whereId($userid)->first();
            $user_id = $userid;
            $name = $postcust->name;
            $body = 'Dear ' . $name . ' ' . $request->amount . ' Points added by admin	';
            $title = "Point Added";
            $this->notificationUser($title, $body, $user_id);
            DB::commit();
            $success['payment'] =  "sss";
            return $this->sendResponse($success, 'Payment Created successfully.');
        } catch (\Exception $ex) {
            DB::rollback();
            return $this->sendError('error.', $ex->getMessage());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    public function debit()
    {
        try {
            #Stat get 
            $relation = ['username'];
            $success['debitamount'] = DebitPayment::with($relation)->where('user_id', auth('api')->user()->id)->orderBy('id', 'desc')->get();

            #return response with active state
            return $this->sendResponse($success, 'debitamount.');
        } catch (\Exception $ex) {
            return $this->sendError('Validation Error.', $ex->getMessage());
        }
    }

    public function history()
    {
        try {
            #Stat get 
            $success['debitamount'] = PaymentHistory::where('user_id', auth('api')->user()->id)->get();

            #return response with active state
            return $this->sendResponse($success, 'debitamount.');
        } catch (\Exception $ex) {
            return $this->sendError('Validation Error.', $ex->getMessage());
        }
    }

    public function UserGameWinner(Request $request)
    {
        try {
            #Stat get 

            $relation = ['Stores', 'GameName'];

            #get all paymentUser resources

            $details = $this->userWinnersAmount->with($relation)->where('user_id', 16)->get();
            $data = array();
            $i = 0;
            foreach ($details as $value) {
                $data[$i]['bazar']  = $value->Stores->name;
                $data[$i]['game']  = $value->GameName->name;
                $data[$i]['type']   = $value->type;
                $data[$i]['amount'] = $value->amount;
                $data[$i]['bit']   = $value->open_time;
                $data[$i]['date']   = dateShow($value->created_at);
                $data[$i]['time']   = timeShow($value->created_at);
                $data[$i]['sno']   = $i + 1;
                $i++;
            }
            $success['lists'] = $data;

            #return response with active state
            return $this->sendResponse($success, 'game leader.');
        } catch (\Exception $ex) {
            return $this->sendError('Validation Error.', $ex->getMessage());
        }
    }
    
    
    public function paymentFire(Request $request)
        {
            $orderId = $request->order_id;
            $newStatus = true;
        
            // Load Firebase service account
            $firebase = (new Factory)
                ->withServiceAccount(storage_path('app/firebase_credentials.json'))
                ->withDatabaseUri('https://jr777-e9a6c-default-rtdb.firebaseio.com/'); // << Change to yours
        
            // Create Realtime Database instance
            $database = $firebase->createDatabase();
        
            // Path: Orders/{orderId}/status
            $database->getReference('Orders/'.$orderId.'/status')->set($newStatus);
        
            return response()->json(['message' => 'Order status updated successfully']);
        }
    
    public function generateOrderId()
        {
            do {
                // Generate 12 digit random number
                $orderId = mt_rand(100000000000, 999999999999);
            } while ($this->fundRequest->where('order_id', $orderId)->exists());
        
            return $orderId;
        }

    public function fundRequest(Request $request)
    {
        
        
        // try {
            $validator = Validator::make($request->all(), [
                'amount' => 'required',
            ]);

            if ($validator->fails()) {
                return $this->sendError($validator->errors(), 'Validation Error.');
            }



        $appSetup = $this->appDetail->first();
        
        if($request->amount < $appSetup->min_despoite){
                return $this->sendError("Minimum Fund Amount is ₹" . $appSetup->min_despoite, "Minimum Fund Amount is ₹" . $appSetup->min_despoite);
            }
        
        $order_id = (string)$this->generateOrderId();
        
        $user = $this->user->where('id',Auth::user()->id)->first();
        

            $image = $request->file('image');
            $unique = substr(str_shuffle("0123456789"), 0, 4);


            $data = [
                'user_id'   => Auth::user()->id,
                'amount'    => $request->amount,
                'image'    => isset($image) ? fileUploadProfile('admin/home/fundScreenshot', $image, $unique) : null,
                'status'    => 1,
                'payment_created'   => 1,
                'order_id' => $order_id,
            ];

            $success = $this->fundRequest->create($data);
            
            
            ImbHistory::create([
                'order_id' => $order_id,
                'status' => 1,
                ]);
            
          
            
            $client = new Client();

            
            $remark = $user->name.' '.'Amount request sent '.$request->amount;
            
            // $response = $client->request('POST', 'http://upigatewaydashboard.profcymadev.com:5000/api/create-order', [
            //     'headers' => [
            //         'Content-Type' => 'application/json',
            //         'Accept'       => 'application/json',
            //         'merchant_key'  => $appSetup->api_token,
            //     ],
            //     'json' => [
            //         "p_info"          => $user->name,
            //         "customer_name" => $user->name,
            //         "customer_phone" => $user->mobile_number,
            //         "customer_email"  => "test@gmail.com",
            //         "key"             => $appSetup->api_token,
            //         "amount"          => $request->amount,
            //         "order_id"   => $order_id,
            //         "redirect_url"    => "https://gama5678.com/payment-success.html",
            //         "webhook_url"     => "https://a2zgame.profcymadev.in/public/api/webhook",
            //         "udf1"            => $remark,
            //         "udf2"            => $remark,
            //         "udf3"            => $remark
            //     ]
            // ]);
            
            
            // $response = $client->request('POST', 'https://api.ekqr.in/api/v2/create_order', [
            //     'headers' => [
            //         'Content-Type' => 'application/json',
            //         'Accept'       => 'application/json'
            //     ],
            //     'json' => [
            //         "p_info"          => $user->name,
            //         "customer_name" => $user->name,
            //         "customer_mobile" => $user->mobile_number,
            //         "customer_email"  => "test@gmail.com",
            //         "key"             => $appSetup->api_token,
            //         "amount"          => $request->amount,
            //         "client_txn_id"   => $order_id,
            //         "redirect_url"    => "https://gama5678.com/payment-success.html",
            //         "udf1"            => $remark,
            //         "udf2"            => $remark,
            //         "udf3"            => $remark
            //     ]
            // ]);
            
           

            // Log::info($response->getBody());
            // $data = json_decode($response->getBody(), true);
            
            // // Check if the JSON decoding was successful
            // if ($data === null) {
            //     // Log an error if JSON decoding fails
            //     Log::error('Failed to decode JSON response', ['response' => $rawResponse]);
            //     return $this->sendError('Validation Errors.', 'Validation Errors.');
            // }
    
            // // Check if the 'data' key exists in the response array
            // if (isset($data['data'])) {

            //     return $this->sendResponse($data['data'], 'Amount Request Gone Successfully.');
            // } else {
            //     return $this->sendError('Validation Error.','Validation Error.');
            // }
            
            
            //  $client = new Client();

            
            // $remark = $user->name.' '.'Amount request sent '.$request->amount;
            
            $response = $client->request('POST', 'https://pay.imb.org.in/api/create-order', [
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded'
                ],
                'form_params' => [
                    "customer_mobile" => $user->mobile_number,
                    "user_token" => $appSetup->api_token,
                    "amount" => $request->amount,
                    "order_id" => $order_id,
                    "redirect_url" => "https://onebetplays.com/payment-success.html",
                    "remark1" => $remark,
                    "remark2" => $remark,
                ]
            ]);

            
            $data = json_decode($response->getBody(), true);
            
    
            // Check if the JSON decoding was successful
            if ($data === null) {
                // Log an error if JSON decoding fails
                Log::error('Failed to decode JSON response', ['response' => $rawResponse]);
                return $this->sendError('Validation Errors.', 'Validation Errors.');
            }
    
            // Check if the 'data' key exists in the response array
            if (isset($data['result'])) {
                $data['result']['payment_url'] = $data['result']['payment_url'];

                return $this->sendResponse($data['result'], 'Amount Request Gone Successfully.');
            } else {
                return $this->sendError('Validation Error.','Validation Error.');
            }
            



            #return response with active state
           
        // } catch (\Exception $ex) {
        //     return $this->sendError('Validation Error.','Validation Error.');
        // }
    }
    
    public function fundRequestCheck(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'order_id' => 'required',
            ]);

            if ($validator->fails()) {
                return $this->sendError($validator->errors(), 'Validation Error.');
            }



        $appSetup = $this->appDetail->first();
        
        
            
            $client = new Client();
            
            
            // Make the GET request with the 'date' parameter
            $response = $client->request('POST', 'https://pay.imb.org.in/api/check-order-status', [
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded'
                ],
                'form_params' => [
                    "user_token" => $appSetup->api_token,
                    "order_id" => $request->order_id,
                ]
            ]);

    
            
            $data = json_decode($response->getBody(), true);
            
            
            return $data;
    
           // Check if the JSON decoding was successful
            if ($data === null) {
                // Log an error if JSON decoding fails
                Log::error('Failed to decode JSON response', ['response' => $rawResponse]);
                 return $this->sendResponse(false, 'Amount Request Gone Successfully.');
            }
    
            // Check if the 'data' key exists in the response array
            if (isset($data['result'])) {
                
                    if($data['status'] == "COMPLETED"){
                        return $this->sendResponse(true, 'Amount Request Gone Successfully.');
                    }else{
                       return $this->sendResponse(false, 'Amount Request Gone Successfully.');
                    }
                    
                
            } else {
                 return $this->sendResponse(false, 'Amount Request Gone Successfully.');
            }
            



            #return response with active state
           
        } catch (\Exception $ex) {
            return $this->sendError('Validation Error.', $ex->getMessage());
        }
    }
    public function fundRequestGet(Request $request)
    {
        try {
            $user_id = Auth::user()->id;


            $success = $this->fundRequest->where('user_id', $user_id)->paginate(10);



            #return response with active state
            return $this->sendResponse($success, 'Amount Request Get Successfully.');
        } catch (\Exception $ex) {
            return $this->sendError('Validation Error.', $ex->getMessage());
        }
    }
}
