<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ChatMessenger;
use App\Http\Controllers\Controller;
use App\Models\CryptoTransaction;
use App\Models\GiftCardAmount;
use App\Models\GiftCards;
use App\Models\VirtualAccounts;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class CryptoTradeController extends Controller
{

    protected $perPage = 30;
    public function allTrade()
    {
        $search = request('search');
        $status = request('status');
        $trades = CryptoTransaction::where('transaction_type','0')->join('users','crypto_transactions.user_id', '=', 'users.id')

            ->when($search,function($q) use($search){
                return $q->where('reference_no','like',"%$search%");
            })->select('crypto_transactions.*','users.name', 'users.phone',
               )
            ->latest()->paginate(15);
        // dd($trades);
        return view('admin.crypto.index', compact('trades','search'));
    }
    public function approvalTransactionList()
    {
        $search = request('search');
        $status = request('status');
        $trades =  CryptoTransaction::where('payment_status','Payment Received')->where('fund_wallet_status','Pending')->join('users','crypto_transactions.user_id', '=', 'users.id')

            ->when($search,function($q) use($search){
                return $q->where('reference_no','like',"%$search%");
            })->select('crypto_transactions.*','users.name', 'users.phone',
            )
            ->latest()->paginate(20);
        // dd($trades);
        return view('admin.crypto.approve_transaction', compact('trades','search'));
    }


    //view trades conversations



    public function approve(Request $request)
    {
        $trans = CryptoTransaction::where('fund_wallet_status','Pending')->find($request->id);
        if(empty($trans)){
            return response()->json(['status' => 'error', 'message'=>'Payout Approved Unsuccessful'], 401);
        }
        $trans->fund_wallet_status = 'Balance';
        $trans->fund_wallet_status_at= now()->toDateTimeString();
        $trans->approved_wallet_funding_method = 'Manual';
        $trans->approved_wallet_funding_at = now()->toDateTimeString();
        $trans->approved_wallet_funding_by = Auth()->user()->id;
        if($trans->save()){
            Auth()->user()->saveToClientWallet($trans->converted_amount,$trans->user_id,'balance', 'Crypto','');
        };
        if(!empty($trans->referred_by)){
            Auth()->user()->saveToClientWallet($trans->refer_bonus,$trans->referred_by,'refer', 'Crypto', $trans->user_id);
        }

        return response()->json(['status' => 'success', 'message'=>'Payout Approved Successfuly'], 200);



    }


    public function reject(Request $request)
    {

        $trans = CryptoTransaction::findOrFail($request->id);
        $trans->fund_wallet_status = 'Rejected';
        $trans->fund_wallet_status_at= now()->toDateTimeString();
        $trans->approved_wallet_funding_method = 'Manual';
        $trans->approved_wallet_funding_at = now()->toDateTimeString();
        $trans->approved_wallet_funding_by = Auth()->user()->id;
        if($trans->save())
            return back()->with('success','Payout has been decline');

    }

    public function tradeTransactions()
    {
        $search = request('search');
        $status = request('status');
        $trades = TransactionHistory::join('merchants','transaction_histories.created_by', '=', 'merchants.id')
            ->join('users','transaction_histories.user_id', '=', 'users.id')

            ->when($search,function($q) use($search){
                return $q->where('users.name','like',"%$search%");
            })->select('transaction_histories.*','merchants.name AS merchant_name','users.name')
            ->latest()->paginate(15);
        // dd($trades);
        return view('admin.manage_giftcard_trade.trade_transaction', compact('trades','search'));
    }


    public function confirmPayment(Request $request){


        $request->validate([
            'coin'=>'required',
            'address'=>'required',
            'order_id'=>'required'
        ]);
        $services = [
            'btc' => [['https://mempool.space/api/', 'address/{R}', 'address/{R}/txs', 'tx/{R}', 'blocks/tip/height', 'mempool'], ['https://blockstream.info/api/', 'address/{R}', 'address/{R}/txs', 'tx/{R}', 'blocks/tip/height', 'blockstream'], ['https://blockchain.info/', 'q/addressbalance/{R}', 'rawaddr/{R}?limit=30', 'rawtx/{R}', 'q/getblockcount', 'blockchain'], 'blockdaemon'],
            'eth' => [['https://api.etherscan.io/api?', 'module=account&action=balance&address={R}', 'module=account&action=txlist&address={R}&startblock=0&endblock=99999999&offset=99&sort=asc', 'module=account&action=txlist&address={R}&startblock=0&endblock=99999999&offset=99&sort=asc', false, 'etherscan'], ['https://api.ethplorer.io/', 'getAddressInfo/{R}', 'getAddressTransactions/{R}?limit=99&showZeroValues=false', 'getTxInfo/{R}', 'getLastBlock', 'ethplorer'], ['https://blockscout.com/eth/mainnet/api?', 'module=account&action=balance&address={R}', 'module=account&action=txlist&address={R}', 'module=transaction&action=gettxinfo&txhash={R}', false, 'blockscout'], 'blockdaemon'],
            'xrp' => [['https://data.ripple.com/v2/', 'accounts/{R}/balances', 'accounts/{R}/transactions', 'transactions/{R}', false, 'ripple'], 'blockdaemon'],
            'doge' => ['blockcypher', 'blockdaemon'],
            'algo' => [['https://algoindexer.algoexplorerapi.io/v2/', 'accounts/{R}', 'accounts/{R}/transactions?limit=99', 'transactions/{R}', 'accounts/{R}', 'algoexplorerapi'], 'blockdaemon'],
            'bnb' => [['https://api.bscscan.com/api?', 'module=account&action=balance&address={R}', 'module=account&action=txlist&address={R}&startblock=0&endblock=99999999&offset=99&sort=asc', 'module=account&action=txlist&address={R}&startblock=0&endblock=99999999&offset=99&sort=asc', false, 'bscscan']],
            'ltc' => ['tatum', 'blockdaemon', 'blockcypher'],
            'bch' => [['https://rest1.biggestfan.net/v2/address/', 'details/{R}', 'transactions/{R}', 'transactions/{R}', false, 'biggestfan'], 'blockdaemon'],
            'trx' => [['https://apilist.tronscan.org/api/', 'account?address={R}', 'transaction?sort=-timestamp&count=true&limit=99&start=0&address={R}', 'transaction-info?hash={R}', false, 'tronscan'], 'tatum']
        ];
        $coin = $request->coin;
        $address= $request->address;
        $order_id= $request->order_id;
        $trans = CryptoTransaction::where('order_id',$order_id)->firstOrFail();
        if(!($trans->coin_confirm_status)) {
            if ($coin == 'btc') {//check transaction mempool.space

                $data = confirmBtcPayment($request->address);
                if ($data['amount'] > 0) {
                    //update transaction
                    $trans->txid = $data['txid'];
                    // $trans->vin_crypto = $data['vin'];
                    //  $trans->vout_crypto = $data['vout'];
                    //  $trans->txt_fees = $data['fee'];
                    // $trans->vin_amount_usd = btcToUsd($data['vin']);
                    //$trans->vout_amount_usd = btcToUsd($data['vout']);

                    //   if($data['confirmed']){//that mnean the money is successufl
                    // dd(confirmBalance($address)['amount']);
                    $trans->amount_received = $data['amount'];//confirmBalance($address)['amount'];//$trans->vout_amount_usd * $trans->rate;

                    //save amount to wallet
                    $trans->payment_status = 'Payment Received';

                    $trans->recieved_converted_amount = $trans->price_in_usd * $trans->amount_received;

                    $trans->converted_amount = $trans->rate * $trans->recieved_converted_amount;
                    $trans->price_in_usd = btctoUsd();
                    if ($trans->fund_wallet_status != 'Pending' || $trans->fund_wallet_status != 'Balance') {
                        $trans->fund_wallet_status='Pending';
                        //load wallet
                        Auth()->user()->saveToClientWalletCrypto($trans->converted_amount, $trans->user_id, 'Pending');
                        if (!empty($trans->referred_by)) {
                            $bonus = $trans->recieved_converted_amount * $trans->refer_bonus;
                            Auth()->user()->saveToClientWalletCrypto($bonus, $trans->referred_by, 'ReferPending');
                        }
                    }


                    $trans->coin_confirm_status = $data['confirmed'];


                    // }
                    if ($trans->save()) {
                        return response()->json(['status' => $trans->coin_confirm_status, 'confirmed' => true, 'vout' => $trans->amount_received. ' ($'.$trans->recieved_converted_amount.')'], 200);
                    }

                } else {
                    // dd($data);
                    return response()->json(['confirmed' => false, 'message' => 'Payment not confirm, Bitcoin blocks only arrive at an average of 10 minutes'], 406);
                }

            } else if ($coin == 'eth') { //which etherrium etherscan.io

            } else if ($coin == 'bnb') {//explorer.bnbchain.org

            }
        }else{
            return response()->json(['status' => $trans->coin_confirm_status, 'confirmed' => true, 'vout' => $trans->amount_received. ' ($'.$trans->recieved_converted_amount.')'], 200);
        }


    }

    public function updateReceivedPayment(Request $request){
        $crypto = CryptoTransaction::where('id',$request->id)->firstOrFail();
//dd($request->payout_status);
        $crypto->amount_received= $request->amount_received;
        $crypto->payment_status= 'Payment Received';
        $crypto->recieved_converted_amount = $request->amount_received;

        $crypto->converted_amount = $crypto->rate * $crypto->recieved_converted_amount;
        $crypto->coin_confirm_status='Confirmed';
        if($request->payout_status=='Yes'){
            $crypto->fund_wallet_status = 'Balance';
            $crypto->fund_wallet_status_at= now()->toDateTimeString();
            $crypto->approved_wallet_funding_method = 'Manual';
            $crypto->approved_wallet_funding_at = now()->toDateTimeString();
            $crypto->approved_wallet_funding_by = Auth()->user()->id;
            if($crypto->save()){
                Auth()->user()->saveToClientWalletCrypto($crypto->converted_amount,$crypto->user_id,'Balance', 'Crypto','');
            };
            if(!empty($crypto->referred_by)){
                Auth()->user()->saveToClientWalletCrypto($crypto->refer_bonus,$crypto->referred_by,'Refer', 'Crypto', $crypto->user_id);
            }
return back()->with('success','Payment Update Successful');
        }else{
            $crypto->fund_wallet_status="Pending";

            if($crypto->save()) {
                Auth()->user()->saveToClientWalletCrypto($crypto->converted_amount, $crypto->user_id, 'Pending');
                if (!empty($crypto->referred_by)) {
                    $bonus = $crypto->recieved_converted_amount * $crypto->refer_bonus;
                    Auth()->user()->saveToClientWalletCrypto($bonus, $crypto->referred_by, 'ReferPending');
                }
            }
            return back()->with('success','Payment Update Successful');
        }
    }

    public function cryptoAllOrder()
    {
        $search = request('search');
        $status = request('status');
        $trades = CryptoTransaction::where('transaction_type','1')->join('users','crypto_transactions.user_id', '=', 'users.id')

            ->when($search,function($q) use($search){
                return $q->where('reference_no','like',"%$search%");
            })->select('crypto_transactions.*','users.name', 'users.phone',
            )
            ->latest()->paginate(15);
        // dd($trades);
        return view('admin.crypto.index_order_paid', compact('trades','search'));
    }

    //withdraw asset test
    public function withdrawBTC($account, $address, $amount, $gas){
        $sdk = initiateTatum();// \Tatum\Sdk();

// 🐛 Enable debugging on the MainNet
        // $sdk->mainnet()->config()->setDebug(true);

        $arg_transfer_btc_mnemonic = (new \Tatum\Model\TransferBtcMnemonic())

            // Sender account ID
            ->setSenderAccountId($account->virtual_account_id)

            // Blockchain address to send assets to. For BTC, LTC, DOGE and BCH, it is possible to enter list of...
            ->setAddress($address)

            // Amount to be withdrawn to blockchain.
            ->setAmount($amount)

            // (optional) Compliance check, if withdrawal is not compliant, it will not be processed.
            ->setCompliant(false)

            // (optional) Fee to be submitted as a transaction fee to blockchain. If none is set, default value of 0.0005 B...
            ->setFee($gas)

            // (optional) For BTC, LTC, DOGE and BCH, it is possible to enter list of multiple recipient blockchain amounts...
            ->setMultipleAmounts(null)

            // (optional) Used to parametrize withdrawal as a change address for left coins from transaction. XPub or attr ...
            ->setAttr('null')

            // Mnemonic seed - usually 12-24 words with access to whole wallet. Either mnemonic, keyPair or sign...
            ->setMnemonic($account->blockchain->menonic)

            // Extended public key (xpub) of the wallet associated with the accounts. Should be present, when mn...
            ->setXpub($account->xpub)

            // (optional) Identifier of the payment, shown for created Transaction within Tatum sender account.
            ->setPaymentId('R2T'.time())

            // (optional) Note visible to owner of withdrawing account
            ->setSenderNote('Withdrawing form master trading on '.date('Y-m-d h:i'));

        try {

            /**
             * POST /v3/offchain/bitcoin/transfer
             *
             * @var \Tatum\Model\TransferBtcMnemonic200Response $response
             */
            $response = $sdk//->mainnet()
            ->api()
                ->blockchainOperations()
                ->transferBtcMnemonic($arg_transfer_btc_mnemonic);

            var_dump($response);

        } catch (\Tatum\Sdk\ApiException $apiExc) {
            echo sprintf(
                "API Exception when calling api()->blockchainOperations()->transferBtcMnemonic(): %s\n",
                var_export($apiExc->getResponseObject(), true)
            );
        } catch (\Exception $exc) {
            echo sprintf(
                "Exception when calling api()->blockchainOperations()->transferBtcMnemonic(): %s\n",
                $exc->getMessage()
            );
        }
    }

    public function withdrawAsset(Request $request){

        $asset = $request->id;
        //recheck the balance
        $accountOld = VirtualAccounts::where('blockchain_code', $asset)->where('virtual_account_type','Trading')->firstOrFail();
        $account= getAssetAccountBalanceReal($accountOld);
        if($request->post()){
            $requestType = $request->type;
            $request->validate([
                'amount' => 'required',
                'address' => 'required',


            ]);

            $amount = $request->amount;
            $getConvertedAssetAmount = convertUsdToAsset($account->last_check_rate, $amount);
         /*   if($requestType=='g') { //this submittion is just for gast fees only


                $gasFees = getAssetGasEstimate($account, $request->address, $getConvertedAssetAmount);
                if (!empty($gasFees))
                    return response()->json(['fast' => $gasFees['fast'], 'medium' => $gasFees['medium'], 'slow' => $gasFees['medium'], 'amount' => $getConvertedAssetAmount . ' BTC (' . $amount . ')'], 200);
                else
                    return response()->json(['message' => 'Unknown Error Please Retry'], 403);
            }*/
            if($requestType=='b') { //finalize the withdraw
                $request->validate([
                    'amount' => 'required',
                    'address' => 'required',
                   // 'netFees'=>'required',


                ]);
                //first check if the balance is enough
$netFees = env($account->blockchain_code."_GAS");
                $networkFees = convertAssetToUSD($account->last_check_rate,$netFees);
                $finalWithdraw = $amount + $networkFees;

                //check if the available balance is same
                if ($finalWithdraw > $account->availableBalanceUSD) {
                    return response()->json(['message' => 'Insufficient Asset Balance Please try again', 'status'=>'error'], 403);

                }
                //check the password once it has sufficient balance
                if (!(Hash::check( $request->password, Auth()->user()->getAuthPassword()))) {
                    return response()->json([
                        'status' => 'error',
                        'message' => 'Invalid Password Please Retry'
                    ], 400);
                }
                //when the password is corrent initiate withdraw
                if($account->blockchain_code=='BTC'){
                  $response=  $this->withdrawBTC($account,$request->address, $amount, $netFees);
var_dump($response);
                }elseif($account->blockchain_code=='USDT_TRON'){
                    $response=  $this->withdrawUSDT($account, $request->address, $amount);
var_dump($response);
                }
            }
        }
        return view('admin.crypto.withdraw_asset', compact('asset', 'account'));
    }




    public function getWithdraw(){

// Set your API Keys 👇 here
        $sdk  = initiateTatum();

// 🐛 Enable debugging on the MainNet
       // $sdk->mainnet()->config()->setDebug(true);

// Max number of items per page is 50.
        $arg_page_size = 10;

// Currency of the withdrawal
        $arg_currency = "USDT_TRON";

// Status of the withdrawal
        $arg_status = "Done";

// Offset to obtain next page of the data.
        $arg_offset = 0;

        try {

            /**
             * GET /v3/offchain/withdrawal
             *
             * @var \Tatum\Model\WithdrawalObject[] $response
             */
            $response = $sdk//->mainnet()
                ->api()
                ->withdrawal()
                ->getWithdrawals($arg_page_size, $arg_currency, $arg_status, $arg_offset);

            var_dump($response);

        } catch (\Tatum\Sdk\ApiException $apiExc) {
            echo sprintf(
                "API Exception when calling api()->withdrawal()->getWithdrawals(): %s\n",
                var_export($apiExc->getResponseObject(), true)
            );
        } catch (\Exception $exc) {
            echo sprintf(
                "Exception when calling api()->withdrawal()->getWithdrawals(): %s\n",
                $exc->getMessage()
            );
        }
    }




    public function trans(){



// Set your API Keys 👇 here
        $sdk = initiateTatum();// \Tatum\Sdk();

// Set your API Keys 👇 here
       // $sdk = new \Tatum\Sdk();

// 🐛 Enable debugging on the MainNet
      //  $sdk->mainnet()->config()->setDebug(true);

// ID of created withdrawal
      //  $arg_id = '669814fc1b42ba657869113d';

// Defines whether fee should be reverted to account balance as well as amount. Defaults to true. Revert true would be typically used when withdrawal was not broadcast to blockchain. False is used usually for Ethereum based currencies when gas was consumed but transaction was reverted.
      //  $arg_revert = true;

        //try {

            /**
             * DELETE /v3/offchain/withdrawal/{id}
             */
         /*   $sdk
                ->api()
                ->withdrawal()
                ->cancelInProgressWithdrawal($arg_id, $arg_revert);

        } catch (\Tatum\Sdk\ApiException $apiExc) {
            echo sprintf(
                "API Exception when calling api()->withdrawal()->cancelInProgressWithdrawal(): %s\n",
                var_export($apiExc->getResponseObject(), true)
            );
        } catch (\Exception $exc) {
            echo sprintf(
                "Exception when calling api()->withdrawal()->cancelInProgressWithdrawal(): %s\n",
                $exc->getMessage()
            );
        }
        die();*/
// 🐛 Enable debugging on the MainNet
       // $sdk->mainnet()->config()->setDebug(true);

// Max number of items per page is 50.
     //   $arg_page_size = 10;

// Currency of the withdrawal
       // $arg_currency = "USDT_TRON";

// Status of the withdrawal
      //  $arg_status = "InProgress";

// Offset to obtain next page of the data.
     //  $arg_offset = 0;

     /*   try {

            /**
             * GET /v3/offchain/withdrawal
             *
             * @var \Tatum\Model\WithdrawalObject[] $response
             */
          /*  $response = $sdk
                ->api()
                ->withdrawal()
                ->getWithdrawals($arg_page_size, $arg_currency, $arg_status, $arg_offset);

            var_dump($response);

        } catch (\Tatum\Sdk\ApiException $apiExc) {
            echo sprintf(
                "API Exception when calling api()->withdrawal()->getWithdrawals(): %s\n",
                var_export($apiExc->getResponseObject(), true)
            );
        } catch (\Exception $exc) {
            echo sprintf(
                "Exception when calling api()->withdrawal()->getWithdrawals(): %s\n",
                $exc->getMessage()
            );
        }
        die();
          */
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => "https://api.tatum.io/v3/offchain/withdrawal",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode([
                'senderAccountId' => '668b0830df2a332607402d83',
                'address' => 'TRGL8Ya4oYnUNWjxwxv1peymNTt1XotVNc',
                'amount' => '1',
                'attr' => '12345',
                'compliant' => false,
                'fee' => '2.5',

                'paymentId' => '12345',
                'senderNote' => 'Sender note'
            ]),
            CURLOPT_HTTPHEADER => [
                "accept: application/json",
                "content-type: application/json",
                "x-api-key: t-65e6f6ed202429001bcf0a0d-3ef243888a3e4bfb8eb3dcac"
            ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            echo $response;
        }
        die();

        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => "https://api.tatum.io/v3/offchain/withdrawal",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => [
                "accept: application/json",
                "x-api-key: t-65e6f6ed202429001bcf0a0d-3ef243888a3e4bfb8eb3dcac"

            ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            echo $response;
        }
        die();
// Set your API Keys 👇 here
        $sdk =initiateTatum(); //new \Tatum\Sdk();

// Set your API Keys 👇 here
       // $sdk = new \Tatum\Sdk();

// 🐛 Enable debugging on the MainNet
        //$sdk->mainnet()->config()->setDebug(true);


// 🐛 Enable debugging on the MainNet
      //  $sdk->mainnet()->config()->setDebug(true);


        $arg_transfer_tron = (new \Tatum\Model\TransferTron())

            // Blockchain address to send assets
            ->setAddress('TRGL8Ya4oYnUNWjxwxv1peymNTt1XotVNc')

            // Amount to be sent in Tron.
            ->setAmount('2')

            // (optional) Compliance check, if withdrawal is not compliant, it will not be processed.
            ->setCompliant(false)

            // Private key of sender address. Either mnemonic and index, privateKey or signature Id must be pres...
            ->setFromPrivateKey('40581281e6b9afe57362c549e7eba257abf1bc78a6b8b61f2b6b501132f4e817')

            // (optional) Fee to be submitted as a transaction fee to blockchain. If none is set, default value of 2.5 TRX ...
            ->setFee("2.5")

            // (optional) Identifier of the payment, shown for created Transaction within Tatum sender account.
            ->setPaymentId('1234eer')

            // Sender account ID
            ->setSenderAccountId('668b0830df2a332607402d83')

            // (optional) Note visible to owner of withdrawing account
            ->setSenderNote('Sender note');

        try {

            /**
             * POST /v3/offchain/tron/transfer
             *
             * @var \Tatum\Model\TransferBtcMnemonic200Response $response
             */
            $response = $sdk//->mainnet()
                ->api()
                ->blockchainOperations()
                ->transferTron($arg_transfer_tron);

            var_dump($response);

        } catch (\Tatum\Sdk\ApiException $apiExc) {
            echo sprintf(
                "API Exception when calling api()->blockchainOperations()->transferTron(): %s\n",
                var_export($apiExc->getResponseObject(), true)
            );
        } catch (\Exception $exc) {
            echo sprintf(
                "Exception when calling api()->blockchainOperations()->transferTron(): %s\n",
                $exc->getMessage()
            );
        }
    }

    public function tranhistory(){
   //     t your API Keys 👇 here
        $sdk = initiateTatum();// \Tatum\Sdk();

// Set your API Keys 👇 here
       // $sdk = new \Tatum\Sdk();

// 🐛 Enable debugging on the MainNet
        // $sdk->mainnet()->config()->setDebug(true);

// Max number of items per page is 50.
         $arg_page_size = 50;

// Currency of the withdrawal
         $arg_currency = "BTC";

// Status of the withdrawal
          $arg_status = "Done";

// Offset to obtain next page of the data.
          $arg_offset = 0;

          try {

               /**
                * GET /v3/offchain/withdrawal
                *
                * @var \Tatum\Model\WithdrawalObject[] $response
                */
          $response = $sdk
              ->api()
              ->withdrawal()
              ->getWithdrawals($arg_page_size, $arg_currency, $arg_status, $arg_offset);

          var_dump($response);

      } catch (\Tatum\Sdk\ApiException $apiExc) {
          echo sprintf(
              "API Exception when calling api()->withdrawal()->getWithdrawals(): %s\n",
              var_export($apiExc->getResponseObject(), true)
          );
      } catch (\Exception $exc) {
          echo sprintf(
              "Exception when calling api()->withdrawal()->getWithdrawals(): %s\n",
              $exc->getMessage()
          );
      }
      die();

    }

    public function withdrawUSDT($account, $address, $amount){

// Set your API Keys 👇 here
        $sdk = initiateTatum();//new \Tatum\Sdk();

// 🐛 Enable debugging on the MainNet
       // $sdk->mainnet()->config()->setDebug(true);


        $arg_transfer_tron_mnemonic = (new \Tatum\Model\TransferTronMnemonic())

            // Blockchain address to send assets
            ->setAddress($address)

            // Amount to be sent in Tron.
            ->setAmount($amount)

            // (optional) Compliance check, if withdrawal is not compliant, it will not be processed.
            ->setCompliant(false)


            // (optional) Fee to be submitted as a transaction fee to blockchain. If none is set, default value of 2.5 TRX ...
            ->setFee('50')

            // Derivation index of sender address.
            ->setIndex($account->derivation_key)

            // Mnemonic to generate private key for sender address. Either mnemonic and index, privateKey or sig...
            ->setMnemonic($account->blockchain->menonic)

            // (optional) Identifier of the payment, shown for created Transaction within Tatum sender account.
            ->setPaymentId('R2T'.time())

            // Sender account ID
            ->setSenderAccountId($account->virtual_account_id)

            // (optional) Note visible to owner of withdrawing account
            ->setSenderNote('Withdrawing USDT '.$amount.' from trading wallet on '.date('Y-m-d h:i'));

        try {

            /**
             * POST /v3/offchain/tron/transfer
             *
             * @var \Tatum\Model\TransferBtcMnemonic200Response $response
             */
            $response = $sdk
                ->api()
                ->blockchainOperations()
                ->transferTronMnemonic($arg_transfer_tron_mnemonic);

            var_dump($response);

        } catch (\Tatum\Sdk\ApiException $apiExc) {
            echo sprintf(
                "API Exception when calling api()->blockchainOperations()->transferTronMnemonic(): %s\n",
                var_export($apiExc->getResponseObject(), true)
            );
        } catch (\Exception $exc) {
            echo sprintf(
                "Exception when calling api()->blockchainOperations()->transferTronMnemonic(): %s\n",
                $exc->getMessage()
            );
        }
    }


    public function getAddressBalance(){
        $tronAddress = "TSkXHYUGBDGEeykGHSGa9PBYVhT5gJR682"; // Replace with the Tron address

        $apiKey = env('TRONGRID'); // Your TronGrid API key

            // Define the TronGrid API endpoint
            $url = "https://api.trongrid.io/v1/accounts/" . $tronAddress;

            // Initialize cURL session
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Add the API key to headers for authentication
            $headers = [
                "TRON-PRO-API-KEY: $apiKey"
            ];
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            // Execute the cURL request
            $response = curl_exec($ch);
            curl_close($ch);

            // Check for errors in the response
            if ($response === false) {
                return "Error: " . curl_error($ch);
            }

            // Decode the JSON response
            $data = json_decode($response, true);

            // Check if the 'data' field exists and retrieve the TRX balance
            if (isset($data['data'][0]['balance'])) {
                $trxBalance = $data['data'][0]['balance']; // TRX balance in sun (smallest unit)
                return $trxBalance / pow(10, 6); // Convert to human-readable format (1 TRX = 1,000,000 sun)
            }

            return 0; // Return 0 if no balance found





    }



    public function withdrawUSDTest(){

// Set your API Keys 👇 here
        $sdk = initiateTatum();//new \Tatum\Sdk();

// 🐛 Enable debugging on the MainNet
        // $sdk->mainnet()->config()->setDebug(true);


        $arg_transfer_tron_mnemonic = (new \Tatum\Model\TransferTronMnemonic())

            // Blockchain address to send assets
            ->setAddress("TQPR6VXYYkYChahkqp3fQS1kSEf2EzmEJt")

            // Amount to be sent in Tron.
            ->setAmount(2)

            // (optional) Compliance check, if withdrawal is not compliant, it will not be processed.
            ->setCompliant(false)


            // (optional) Fee to be submitted as a transaction fee to blockchain. If none is set, default value of 2.5 TRX ...
            ->setFee('50')

            // Derivation index of sender address.
            ->setIndex(0)

            // Mnemonic to generate private key for sender address. Either mnemonic and index, privateKey or sig...
            ->setMnemonic("ranch pole book sell robust beach fame crumble pull merge diamond fold slab ladder scissors talent raise fabric mirror review duty source rocket whip")

            // (optional) Identifier of the payment, shown for created Transaction within Tatum sender account.
            ->setPaymentId('R2T'.time())

            // Sender account ID
            ->setSenderAccountId("6735eb1d9e717308058d8490")

            // (optional) Note visible to owner of withdrawing account
            ->setSenderNote('Withdrawing USDT  from trading wallet on '.date('Y-m-d h:i'));

        try {

            /**
             * POST /v3/offchain/tron/transfer
             *
             * @var \Tatum\Model\TransferBtcMnemonic200Response $response
             */
            $response = $sdk
                ->api()
                ->blockchainOperations()
                ->transferTronMnemonic($arg_transfer_tron_mnemonic);

            var_dump($response);

        } catch (\Tatum\Sdk\ApiException $apiExc) {
            echo sprintf(
                "API Exception when calling api()->blockchainOperations()->transferTronMnemonic(): %s\n",
                var_export($apiExc->getResponseObject(), true)
            );
        } catch (\Exception $exc) {
            echo sprintf(
                "Exception when calling api()->blockchainOperations()->transferTronMnemonic(): %s\n",
                $exc->getMessage()
            );
        }
    }


    public function generateCustomerWalletTron(){


        $client = new \GuzzleHttp\Client();

        $response = $client->request('POST', 'https://api.tatum.io/v3/blockchain/sc/custodial/transfer', [
            'body' => '{"chain":"TRON","contractType":0,"custodialAddress":"TQ2hgd5gbzurB4rwUsh1K1yLGGLj8P1k7a","recipient":"TQPR6VXYYkYChahkqp3fQS1kSEf2EzmEJt","tokenAddress":"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t","amount":"2","fromPrivateKey":"7eec35fe77b1ed7bd9aa8c792b5203b53c853ecb5788081f1db9ec9d8fab5899","feeLimit":40}',
            'headers' => [
                'accept' => 'application/json',
                'content-type' => 'application/json',
                'x-api-key' => 't-65e6f6ed202429001bcf0a0d-3ef243888a3e4bfb8eb3dcac',
            ],
        ]);

        echo $response->getBody();
    }













}
