<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BlockchainWallet;
use App\Models\Coins;
use App\Models\UsdtAddress;
use App\Models\VirtualAccounts;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CoinsController extends Controller
{
    public function index(){
        $coins = Coins::paginate(15);
        return view('admin.coins.index',compact('coins'));
    }

    public function create(){
        return view('admin.coins.create');
    }
    public function store(Request $request){
        $request->validate([
            'name'=>'required',
            'code'=>'required|unique:coins,code',
            'logo'=>'required',
            'rate'=>'required|numeric',
            'status'=>'required',
            'min_payment'=>'required|numeric',
            'selling_rate'=>'required|numeric',
            'min_selling'=>'required|numeric',
            'selling_refer_bonus'=>'required|numeric',
            'transaction_charges'=>'required|numeric',
            'minimum_withdraw'=>'required|numeric',


        ]);
//dd(auth()->user());
        $newCoin = new Coins();
        $newCoin->name = $request->name;
        $newCoin->code= $request->code;
        $newCoin->logo = $request->logo;
        $newCoin->rate = $request->rate;
        $newCoin->min_payment = $request->min_payment;
        $newCoin->status = $request->status;
        $newCoin->refer_bonus = $request->refer_bonus;
        $newCoin->selling_rate = $request->selling_rate;
        $newCoin->min_selling = $request->min_selling;
        $newCoin->selling_refer_bonus = $request->selling_refer_bonus;
        $newCoin->transaction_charges = $request->transaction_charges;
        $newCoin->minimum_withdraw = $request->minimum_withdraw;
      //  $newCoin->created_by = auth()->user()->id;
        $newCoin->save();
        return back()->with('success','Coin Added Successfully');

    }

    public function edit($id)
    {
        $coin = Coins::findOrFail($id);
        return view('admin.coins.edit',compact('coin'));
    }

    public function updateCoin(Request $request, $id){
    $request->validate([
        'name'=>'required',
        'code'=>'required',
        'logo'=>'required',
        'rate'=>'required|numeric',
        'status'=>'required',
        'min_payment'=>'required|numeric',
         'selling_rate'=>'required|numeric',
            'min_selling'=>'required|numeric',
            'selling_refer_bonus'=>'required|numeric',
            'transaction_charges'=>'required|numeric',
            'minimum_withdraw'=>'required|numeric',


    ]);
//dd($request);
    $newCoin =  Coins::where('id',$id)->firstOrFail();
    $newCoin->name = $request->name;
    $newCoin->code= $request->code;
    $newCoin->logo = $request->logo;
    $newCoin->rate = $request->rate;
    $newCoin->min_payment = $request->min_payment;
    $newCoin->status = $request->status;
    $newCoin->refer_bonus = $request->refer_bonus;
        $newCoin->selling_rate = $request->selling_rate;
        $newCoin->min_selling = $request->min_selling;
        $newCoin->selling_refer_bonus = $request->selling_refer_bonus;
        $newCoin->transaction_charges = $request->transaction_charges;
        $newCoin->minimum_withdraw = $request->minimum_withdraw;
    //  $newCoin->created_by = auth()->user()->id;
    $newCoin->save();
    return back()->with('success','Coin Updated Successfully');
}

public function manageUsdtAddress(){
        $wallets = UsdtAddress::paginate(20);
return view('admin.coins.manage_wallet_address',compact('wallets'));
}

    public function saveUsdtAddress(Request $request){
        $request->validate([
            'wallet_type'=>'required',
            'address'=>'required|unique:usdt_addresses,address',

            'status'=>'required',



        ]);
//dd(auth()->user());
        $newCoin = new UsdtAddress();
        $newCoin->wallet_type = $request->wallet_type;
        $newCoin->address= $request->address;

        $newCoin->status = $request->status;

        //  $newCoin->created_by = auth()->user()->id;
        $newCoin->save();
        return back()->with('success','Address Added Successfully');

    }
    public function updateUsdtAddress(Request $request){
        $request->validate([
            'wallet_type'=>'required',
            'address'=>'required|unique:usdt_addresses,address',

            'status'=>'required',
            'id'=>'required'



        ]);
//dd(auth()->user());
        $newCoin =UsdtAddress::where('id',$request->id)->firstorFail();
        $newCoin->wallet_type = $request->wallet_type;
        $newCoin->address= $request->address;

        $newCoin->status = $request->status;

        //  $newCoin->created_by = auth()->user()->id;
        $newCoin->save();
        return back()->with('success','Address Updated Successfully');

    }


    public function generateBtcWallet(){
        $tSdk =initiateTatum();// new \Tatum\Sdk('',env('TTAPIKEYTEST'));
       // $tSdk->testnet()->config()->setDebug(true);
        //create a wallet
        $dd= $tSdk->local()->wallet()->bitcoin()->generateWallet();
        $wallet = new BlockchainWallet();
        $wallet->blockchain_code='BTC';
        $wallet->blockchain_name='BITCOIN';
        $wallet->menonic = $dd->getMnemonic();
        $wallet->xpub = $dd->getXpub();
        $wallet->created_by = Auth()->user()->id;
        $wallet->status = 1;
        if($wallet->save())
            echo 'WAllet Created Successfuly';
       // var_dump($dd->get());die();


    }
    public function generateUSDTTronWallet(){
        $tSdk = initiateTatum();//new \Tatum\Sdk('',env('TTAPIKEYTEST'));
        //$tSdk->testnet()->config()->setDebug(true);
        //create a wallet
        $dd= $tSdk->local()->wallet()->tron()->generateWallet();
       // dd($dd);
        $wallet = new BlockchainWallet();
        $wallet->blockchain_name='USDT TRON 20';
        $wallet->blockchain_code='USDT_TRON';
        $wallet->menonic = $dd->getMnemonic();
        $wallet->xpub = $dd->getXpub();
        $wallet->created_by = Auth()->user()->id;
        $wallet->status = 1;
        if($wallet->save())
            echo 'WAllet Created Successfuly';
        //dd($dd['_data']);


    }
    public function generateTronWallet(){
        $tSdk = initiateTatum();//new \Tatum\Sdk('',env('TTAPIKEYTEST'));
        //$tSdk->testnet()->config()->setDebug(true);
        //create a wallet
        $dd= $tSdk->local()->wallet()->tron()->generateWallet();
       // dd($dd);
        $wallet = new BlockchainWallet();
        $wallet->blockchain_name='TRON';
        $wallet->blockchain_code='TRON';
        $wallet->menonic = $dd->getMnemonic();
        $wallet->xpub = $dd->getXpub();
        $wallet->created_by = Auth()->user()->id;
        $wallet->status = 1;
        if($wallet->save())
            echo 'WAllet Created Successfuly';
        //dd($dd['_data']);


    }
    public function generateEtheriumWallet(){
        $tSdk =initiateTatum();// new \Tatum\Sdk('',env('TTAPIKEYTEST'));
      //  $tSdk->config()->setDebug(true);
        //create a wallet
        $dd= $tSdk->local()->wallet()->ethereum()->generateWallet();
       // dd($dd);
        $wallet = new BlockchainWallet();
        $wallet->blockchain_code='ETH';
        $wallet->blockchain_name='ETHERIUM';
        $wallet->menonic = $dd->getMnemonic();
        $wallet->xpub = $dd->getXpub();
        $wallet->created_by = Auth()->user()->id;
        $wallet->status = 1;
        if($wallet->save())
            echo 'WAllet Created Successfuly';


    }


    public function createWalletTradingBTC(Request $request){
      /*  $request->validate([
            'asset'=>'required',
        ]);*/

        $asset = 'BTC';//$request->asset;
        $user_id = Auth()->user()->id;

        $cryptoWallet = BlockchainWallet::where('blockchain_code',$asset)->firstOrFail();
        //check if created
        $checkifExits = VirtualAccounts::where('user_id',$user_id)->where('wallet_id',$cryptoWallet->id)->exists();
         if($checkifExits){
            return  back()->with('error',"You already have this asset");
          }
        //dd($cryptoWallet);

        //if not crated before check if their is still pending address
        //create addresss using xpub
       // $apiKeyTest = env('TTAPIKEYTEST');
        $tSdk =initiateTatum(); //new \Tatum\Sdk('',$apiKeyTest);
//echo $apiKey; die();
        //  $tSdk->testnet()->config()->setDebug(true);
        $customer = new \Tatum\Model\CustomerRegistration(['external_id'=>Auth()->user()->crypto_customer_id,'accounting_currency'=>'USD']);


        $arg_create_account_xpub = (new \Tatum\Model\CreateAccountXpub())
            // <p>The currency for the virtual account</p> <ul> <li><b>Native blockchain assets:</b> ALGO, BCH, ...
            ->setCurrency($cryptoWallet->blockchain_code)

            // Extended public key to generate addresses from.
            ->setXpub($cryptoWallet->xpub)

            // (optional) \Tatum\Model\CustomerRegistration
            ->setCustomer($customer)

            // (optional) Enable compliant checks. If this is enabled, it is impossible to create account if compliant chec...
            ->setCompliant(false)

            // (optional) For bookkeeping to distinct account purpose.
            ->setAccountCode(Auth()->user()->crypto_account_code)

            // (optional) All transaction will be accounted in this currency for all accounts. Currency can be overridden p...
            ->setAccountingCurrency('USD')

            // (optional) Account number from external system.
            ->setAccountNumber(Auth()->user()->crypto_account_number);

        try {

            /**
             * POST /v3/ledger/account
             *
             * @var \Tatum\Model\Account $response
             */
            $response = $tSdk//->testnet()
                ->api()
                ->account()
                ->createAccount($arg_create_account_xpub);

            $responseData = json_decode($response);
            // dd($responseData);
            //save virtual account
            // $argb = (new \Tatum\Model\GenerateAccountAddress())
            $addressGenerated = generateAddressByAccountId($responseData->id);

            $acct = new VirtualAccounts();
            $acct->virtual_account_id=$responseData->id;
            $acct->customer_id =$responseData->customerId;
            $acct->currency = $responseData->currency;
            $acct->account_number = $responseData->accountNumber;
            $acct->account_code = $responseData->accountCode;
            $acct->accounting_currency = $responseData->accountingCurrency;
            $acct->xpub = $responseData->xpub;
            $acct->wallet_id = $cryptoWallet->id;
            $acct->virtual_account_type ='Trading';
            $acct->user_id = $user_id;
            $acct->blockchain_code=$cryptoWallet->blockchain_code;
            $acct->blockchain_name=$cryptoWallet->blockchain_name;
            $acct->attarched_address= $addressGenerated->getGeneratedAddress();
            $acct->derivation_key=$addressGenerated->getDerivationKey();
            if($acct->save()){
                return  back()->with('success',"Asset Created Successfully Make you first deposit");
            };
            //once is save generate address





        } catch (\Tatum\Sdk\ApiException $apiExc) {
            echo sprintf(
                "API Exception when calling api()->account()->createAccount(): %s\n",
                var_export($apiExc->getResponseObject(), true)
            );
        } catch (\Exception $exc) {
            echo sprintf(
                "Exception when calling api()->account()->createAccount(): %s\n",
                $exc->getMessage()
            );
        }
    }
    public function createWalletTradingETH(Request $request){
      /*  $request->validate([
            'asset'=>'required',
        ]);*/

        $asset = 'ETH';//$request->asset;
        $user_id = Auth()->user()->id;

        $cryptoWallet = BlockchainWallet::where('blockchain_code',$asset)->firstOrFail();
        //check if created
        $checkifExits = VirtualAccounts::where('user_id',$user_id)->where('wallet_id',$cryptoWallet->id)->exists();
         if($checkifExits){
            return  back()->with('error',"You already have this asset");
          }
        //dd($cryptoWallet);

        //if not crated before check if their is still pending address
        //create addresss using xpub
       // $apiKeyTest = env('TTAPIKEYTEST');
        $tSdk = initiateTatum();// \Tatum\Sdk('',$apiKeyTest);
//echo $apiKey; die();
        //  $tSdk->testnet()->config()->setDebug(true);
        $customer = new \Tatum\Model\CustomerRegistration(['external_id'=>Auth()->user()->crypto_customer_id,'accounting_currency'=>'USD']);


        $arg_create_account_xpub = (new \Tatum\Model\CreateAccountXpub())
            // <p>The currency for the virtual account</p> <ul> <li><b>Native blockchain assets:</b> ALGO, BCH, ...
            ->setCurrency($cryptoWallet->blockchain_code)

            // Extended public key to generate addresses from.
            ->setXpub($cryptoWallet->xpub)

            // (optional) \Tatum\Model\CustomerRegistration
            ->setCustomer($customer)

            // (optional) Enable compliant checks. If this is enabled, it is impossible to create account if compliant chec...
            ->setCompliant(false)

            // (optional) For bookkeeping to distinct account purpose.
            ->setAccountCode(Auth()->user()->crypto_account_code)

            // (optional) All transaction will be accounted in this currency for all accounts. Currency can be overridden p...
            ->setAccountingCurrency('USD')

            // (optional) Account number from external system.
            ->setAccountNumber(Auth()->user()->crypto_account_number);

        try {

            /**
             * POST /v3/ledger/account
             *
             * @var \Tatum\Model\Account $response
             */
            $response = $tSdk//->testnet()
                ->api()
                ->account()
                ->createAccount($arg_create_account_xpub);

            $responseData = json_decode($response);
            // dd($responseData);
            //save virtual account
            // $argb = (new \Tatum\Model\GenerateAccountAddress())
            $addressGenerated = generateAddressByAccountId($responseData->id);

            $acct = new VirtualAccounts();
            $acct->virtual_account_id=$responseData->id;
            $acct->customer_id =$responseData->customerId;
            $acct->currency = $responseData->currency;
            $acct->account_number = $responseData->accountNumber;
            $acct->account_code = $responseData->accountCode;
            $acct->accounting_currency = $responseData->accountingCurrency;
            $acct->xpub = $responseData->xpub;
            $acct->wallet_id = $cryptoWallet->id;
            $acct->virtual_account_type ='Trading';
            $acct->user_id = $user_id;
            $acct->blockchain_code=$cryptoWallet->blockchain_code;
            $acct->blockchain_name=$cryptoWallet->blockchain_name;
            $acct->attarched_address= $addressGenerated->getGeneratedAddress();
            $acct->derivation_key=$addressGenerated->getDerivationKey();
            if($acct->save()){
                return  back()->with('success',"Asset Created Successfully Make you first deposit");
            };
            //once is save generate address





        } catch (\Tatum\Sdk\ApiException $apiExc) {
            echo sprintf(
                "API Exception when calling api()->account()->createAccount(): %s\n",
                var_export($apiExc->getResponseObject(), true)
            );
        } catch (\Exception $exc) {
            echo sprintf(
                "Exception when calling api()->account()->createAccount(): %s\n",
                $exc->getMessage()
            );
        }
    }
    public function createWalletTradingUSDT_TRON(Request $request){
      /*  $request->validate([
            'asset'=>'required',
        ]);*/

        $asset = 'USDT_TRON';//$request->asset;
        $user_id = Auth()->user()->id;

        $cryptoWallet = BlockchainWallet::where('blockchain_code',$asset)->firstOrFail();
        //check if created
        $checkifExits = VirtualAccounts::where('user_id',$user_id)->where('wallet_id',$cryptoWallet->id)->exists();
         if($checkifExits){
            return  back()->with('error',"You already have this asset");
          }
        //dd($cryptoWallet);

        //if not crated before check if their is still pending address
        //create addresss using xpub
       // $apiKeyTest = env('TTAPIKEYTEST');
        $tSdk = initiateTatum();//new \Tatum\Sdk('',$apiKeyTest);
//echo $apiKey; die();
        //  $tSdk->testnet()->config()->setDebug(true);
        $customer = new \Tatum\Model\CustomerRegistration(['external_id'=>Auth()->user()->crypto_customer_id,'accounting_currency'=>'USD']);


        $arg_create_account_xpub = (new \Tatum\Model\CreateAccountXpub())
            // <p>The currency for the virtual account</p> <ul> <li><b>Native blockchain assets:</b> ALGO, BCH, ...
            ->setCurrency($cryptoWallet->blockchain_code)

            // Extended public key to generate addresses from.
            ->setXpub($cryptoWallet->xpub)

            // (optional) \Tatum\Model\CustomerRegistration
            ->setCustomer($customer)

            // (optional) Enable compliant checks. If this is enabled, it is impossible to create account if compliant chec...
            ->setCompliant(false)

            // (optional) For bookkeeping to distinct account purpose.
            ->setAccountCode(Auth()->user()->crypto_account_code)

            // (optional) All transaction will be accounted in this currency for all accounts. Currency can be overridden p...
            ->setAccountingCurrency('USD')

            // (optional) Account number from external system.
            ->setAccountNumber(Auth()->user()->crypto_account_number);

        try {

            /**
             * POST /v3/ledger/account
             *
             * @var \Tatum\Model\Account $response
             */
            $response = $tSdk//->testnet()
                ->api()
                ->account()
                ->createAccount($arg_create_account_xpub);

            $responseData = json_decode($response);
            // dd($responseData);
            //save virtual account
            // $argb = (new \Tatum\Model\GenerateAccountAddress())
            $addressGenerated = generateAddressByAccountId($responseData->id);

            $acct = new VirtualAccounts();
            $acct->virtual_account_id=$responseData->id;
            $acct->customer_id =$responseData->customerId;
            $acct->currency = $responseData->currency;
            $acct->account_number = $responseData->accountNumber;
            $acct->account_code = $responseData->accountCode;
            $acct->accounting_currency = $responseData->accountingCurrency;
            $acct->xpub = $responseData->xpub;
            $acct->wallet_id = $cryptoWallet->id;
            $acct->virtual_account_type ='Trading';
            $acct->user_id = $user_id;
            $acct->blockchain_code=$cryptoWallet->blockchain_code;
            $acct->blockchain_name=$cryptoWallet->blockchain_name;
            $acct->attarched_address= $addressGenerated->getGeneratedAddress();
            $acct->derivation_key=$addressGenerated->getDerivationKey();
            if($acct->save()){
                return  back()->with('success',"Asset Created Successfully Make you first deposit");
            };
            //once is save generate address





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

    public function createWalletTradingTRONO(Request $request){
      /*  $request->validate([
            'asset'=>'required',
        ]);*/

        $asset = 'TRON';//$request->asset;
        $user_id = Auth()->user()->id;

        $cryptoWallet = BlockchainWallet::where('blockchain_code',$asset)->firstOrFail();
        //check if created
        $checkifExits = VirtualAccounts::where('user_id',$user_id)->where('wallet_id',$cryptoWallet->id)->exists();
         if($checkifExits){
            return  back()->with('error',"You already have this asset");
          }
        //dd($cryptoWallet);

        //if not crated before check if their is still pending address
        //create addresss using xpub
       // $apiKeyTest = env('TTAPIKEYTEST');
        $tSdk = initiateTatum();//new \Tatum\Sdk('',$apiKeyTest);
//echo $apiKey; die();
        //  $tSdk->testnet()->config()->setDebug(true);
        $customer = new \Tatum\Model\CustomerRegistration(['external_id'=>Auth()->user()->crypto_customer_id,'accounting_currency'=>'USD']);


        $arg_create_account_xpub = (new \Tatum\Model\CreateAccountXpub())
            // <p>The currency for the virtual account</p> <ul> <li><b>Native blockchain assets:</b> ALGO, BCH, ...
            ->setCurrency($cryptoWallet->blockchain_code)

            // Extended public key to generate addresses from.
            ->setXpub($cryptoWallet->xpub)

            // (optional) \Tatum\Model\CustomerRegistration
            ->setCustomer($customer)

            // (optional) Enable compliant checks. If this is enabled, it is impossible to create account if compliant chec...
            ->setCompliant(false)

            // (optional) For bookkeeping to distinct account purpose.
            ->setAccountCode(Auth()->user()->crypto_account_code)

            // (optional) All transaction will be accounted in this currency for all accounts. Currency can be overridden p...
            ->setAccountingCurrency('USD')

            // (optional) Account number from external system.
            ->setAccountNumber(Auth()->user()->crypto_account_number);

        try {

            /**
             * POST /v3/ledger/account
             *
             * @var \Tatum\Model\Account $response
             */
            $response = $tSdk//->testnet()
                ->api()
                ->account()
                ->createAccount($arg_create_account_xpub);

            $responseData = json_decode($response);
            // dd($responseData);
            //save virtual account
            // $argb = (new \Tatum\Model\GenerateAccountAddress())
            $addressGenerated = generateAddressByAccountId($responseData->id);

            $acct = new VirtualAccounts();
            $acct->virtual_account_id=$responseData->id;
            $acct->customer_id =$responseData->customerId;
            $acct->currency = $responseData->currency;
            $acct->account_number = $responseData->accountNumber;
            $acct->account_code = $responseData->accountCode;
            $acct->accounting_currency = $responseData->accountingCurrency;
            $acct->xpub = $responseData->xpub;
            $acct->wallet_id = $cryptoWallet->id;
            $acct->virtual_account_type ='Trading';
            $acct->user_id = $user_id;
            $acct->blockchain_code=$cryptoWallet->blockchain_code;
            $acct->blockchain_name=$cryptoWallet->blockchain_name;
            $acct->attarched_address= $addressGenerated->getGeneratedAddress();
            $acct->derivation_key=$addressGenerated->getDerivationKey();
            if($acct->save()){
                return  back()->with('success',"Asset Created Successfully Make you first deposit");
            };
            //once is save generate address





        } catch (\Tatum\Sdk\ApiException $apiExc) {
            echo sprintf(
                "API Exception when calling api()->account()->createAccount(): %s\n",
                var_export($apiExc->getResponseObject(), true)
            );
        } catch (\Exception $exc) {
            echo sprintf(
                "Exception when calling api()->account()->createAccount(): %s\n",
                $exc->getMessage()
            );
        }
    }
    //creation of gas account for btc
    public function createWalletGasBTC(Request $request){
      /*  $request->validate([
            'asset'=>'required',
        ]);*/

        $asset = 'BTC';//$request->asset;
        $user_id = Auth()->user()->id;

        $cryptoWallet = BlockchainWallet::where('blockchain_code',$asset)->firstOrFail();
        //check if created
        $checkifExits = VirtualAccounts::where('user_id',$user_id)->where('wallet_id',$cryptoWallet->id)->exists();
         if($checkifExits){
            return  back()->with('error',"You already have this asset");
          }
        //dd($cryptoWallet);

        //if not crated before check if their is still pending address
        //create addresss using xpub
       // $apiKeyTest = env('TTAPIKEYTEST');
        $tSdk =initiateTatum();// new \Tatum\Sdk('',$apiKeyTest);
//echo $apiKey; die();
        //  $tSdk->testnet()->config()->setDebug(true);
        $customer = new \Tatum\Model\CustomerRegistration(['external_id'=>Auth()->user()->crypto_customer_id_gas,'accounting_currency'=>'USD']);


        $arg_create_account_xpub = (new \Tatum\Model\CreateAccountXpub())
            // <p>The currency for the virtual account</p> <ul> <li><b>Native blockchain assets:</b> ALGO, BCH, ...
            ->setCurrency($cryptoWallet->blockchain_code)

            // Extended public key to generate addresses from.
            ->setXpub($cryptoWallet->xpub)

            // (optional) \Tatum\Model\CustomerRegistration
            ->setCustomer($customer)

            // (optional) Enable compliant checks. If this is enabled, it is impossible to create account if compliant chec...
            ->setCompliant(false)

            // (optional) For bookkeeping to distinct account purpose.
            ->setAccountCode(Auth()->user()->crypto_account_code_gas)

            // (optional) All transaction will be accounted in this currency for all accounts. Currency can be overridden p...
            ->setAccountingCurrency('USD')

            // (optional) Account number from external system.
            ->setAccountNumber(Auth()->user()->crypto_account_number_gas);

        try {

            /**
             * POST /v3/ledger/account
             *
             * @var \Tatum\Model\Account $response
             */
            $response = $tSdk//->testnet()
                ->api()
                ->account()
                ->createAccount($arg_create_account_xpub);

            $responseData = json_decode($response);
            // dd($responseData);
            //save virtual account
            // $argb = (new \Tatum\Model\GenerateAccountAddress())
            $addressGenerated = generateAddressByAccountId($responseData->id);

            $acct = new VirtualAccounts();
            $acct->virtual_account_id=$responseData->id;
            $acct->customer_id =$responseData->customerId;
            $acct->currency = $responseData->currency;
            $acct->account_number = $responseData->accountNumber;
            $acct->account_code = $responseData->accountCode;
            $acct->accounting_currency = $responseData->accountingCurrency;
            $acct->xpub = $responseData->xpub;
            $acct->wallet_id = $cryptoWallet->id;
            $acct->virtual_account_type ='Gas';
            $acct->user_id = $user_id;
            $acct->blockchain_code=$cryptoWallet->blockchain_code;
            $acct->blockchain_name=$cryptoWallet->blockchain_name;
            $acct->attarched_address= $addressGenerated->getGeneratedAddress();
            $acct->derivation_key=$addressGenerated->getDerivationKey();
            if($acct->save()){
                return  back()->with('success',"Asset Created Successfully Make you first deposit");
            };
            //once is save generate address





        } catch (\Tatum\Sdk\ApiException $apiExc) {
            echo sprintf(
                "API Exception when calling api()->account()->createAccount(): %s\n",
                var_export($apiExc->getResponseObject(), true)
            );
        } catch (\Exception $exc) {
            echo sprintf(
                "Exception when calling api()->account()->createAccount(): %s\n",
                $exc->getMessage()
            );
        }
    }
    public function createWalletGasETH(Request $request){
      /*  $request->validate([
            'asset'=>'required',
        ]);*/

        $asset = 'ETH';//$request->asset;
        $user_id = Auth()->user()->id;

        $cryptoWallet = BlockchainWallet::where('blockchain_code',$asset)->firstOrFail();
        //check if created
        $checkifExits = VirtualAccounts::where('user_id',$user_id)->where('wallet_id',$cryptoWallet->id)->exists();
         if($checkifExits){
            return  back()->with('error',"You already have this asset");
          }
        //dd($cryptoWallet);

        //if not crated before check if their is still pending address
        //create addresss using xpub
       // $apiKeyTest = env('TTAPIKEYTEST');
        $tSdk = initiateTatum();//new \Tatum\Sdk('',$apiKeyTest);
//echo $apiKey; die();
        //  $tSdk->testnet()->config()->setDebug(true);
        $customer = new \Tatum\Model\CustomerRegistration(['external_id'=>Auth()->user()->crypto_customer_id_gas,'accounting_currency'=>'USD']);


        $arg_create_account_xpub = (new \Tatum\Model\CreateAccountXpub())
            // <p>The currency for the virtual account</p> <ul> <li><b>Native blockchain assets:</b> ALGO, BCH, ...
            ->setCurrency($cryptoWallet->blockchain_code)

            // Extended public key to generate addresses from.
            ->setXpub($cryptoWallet->xpub)

            // (optional) \Tatum\Model\CustomerRegistration
            ->setCustomer($customer)

            // (optional) Enable compliant checks. If this is enabled, it is impossible to create account if compliant chec...
            ->setCompliant(false)

            // (optional) For bookkeeping to distinct account purpose.
            ->setAccountCode(Auth()->user()->crypto_account_code_gas)

            // (optional) All transaction will be accounted in this currency for all accounts. Currency can be overridden p...
            ->setAccountingCurrency('USD')

            // (optional) Account number from external system.
            ->setAccountNumber(Auth()->user()->crypto_account_number_gas);

        try {

            /**
             * POST /v3/ledger/account
             *
             * @var \Tatum\Model\Account $response
             */
            $response = $tSdk
                ->api()
                ->account()
                ->createAccount($arg_create_account_xpub);

            $responseData = json_decode($response);
            // dd($responseData);
            //save virtual account
            // $argb = (new \Tatum\Model\GenerateAccountAddress())
            $addressGenerated = generateAddressByAccountId($responseData->id);

            $acct = new VirtualAccounts();
            $acct->virtual_account_id=$responseData->id;
            $acct->customer_id =$responseData->customerId;
            $acct->currency = $responseData->currency;
            $acct->account_number = $responseData->accountNumber;
            $acct->account_code = $responseData->accountCode;
            $acct->accounting_currency = $responseData->accountingCurrency;
            $acct->xpub = $responseData->xpub;
            $acct->wallet_id = $cryptoWallet->id;
            $acct->virtual_account_type ='Gas';
            $acct->user_id = $user_id;
            $acct->blockchain_code=$cryptoWallet->blockchain_code;
            $acct->blockchain_name=$cryptoWallet->blockchain_name;
            $acct->attarched_address= $addressGenerated->getGeneratedAddress();
            $acct->derivation_key=$addressGenerated->getDerivationKey();
            if($acct->save()){
                return  back()->with('success',"Asset Created Successfully Make you first deposit");
            };
            //once is save generate address





        } catch (\Tatum\Sdk\ApiException $apiExc) {
            echo sprintf(
                "API Exception when calling api()->account()->createAccount(): %s\n",
                var_export($apiExc->getResponseObject(), true)
            );
        } catch (\Exception $exc) {
            echo sprintf(
                "Exception when calling api()->account()->createAccount(): %s\n",
                $exc->getMessage()
            );
        }
    }
    public function createWalletGasTRON(Request $request){
      /*  $request->validate([
            'asset'=>'required',
        ]);*/

        $asset = 'USDT_TRON';//$request->asset;
        $user_id = Auth()->user()->id;

        $cryptoWallet = BlockchainWallet::where('blockchain_code',$asset)->firstOrFail();
        //check if created
        $checkifExits = VirtualAccounts::where('user_id',$user_id)->where('wallet_id',$cryptoWallet->id)->exists();
         if($checkifExits){
            return  back()->with('error',"You already have this asset");
          }
        //dd($cryptoWallet);

        //if not crated before check if their is still pending address
        //create addresss using xpub
      //  $apiKeyTest = env('TTAPIKEYTEST');
        $tSdk =initiateTatum();// new \Tatum\Sdk('',$apiKeyTest);
//echo $apiKey; die();
        //  $tSdk->testnet()->config()->setDebug(true);
        $customer = new \Tatum\Model\CustomerRegistration(['external_id'=>Auth()->user()->crypto_customer_id,'accounting_currency'=>'USD']);


        $arg_create_account_xpub = (new \Tatum\Model\CreateAccountXpub())
            // <p>The currency for the virtual account</p> <ul> <li><b>Native blockchain assets:</b> ALGO, BCH, ...
            ->setCurrency($cryptoWallet->blockchain_code)

            // Extended public key to generate addresses from.
            ->setXpub($cryptoWallet->xpub)

            // (optional) \Tatum\Model\CustomerRegistration
            ->setCustomer($customer)

            // (optional) Enable compliant checks. If this is enabled, it is impossible to create account if compliant chec...
            ->setCompliant(false)

            // (optional) For bookkeeping to distinct account purpose.
            ->setAccountCode(Auth()->user()->crypto_account_code_gas)

            // (optional) All transaction will be accounted in this currency for all accounts. Currency can be overridden p...
            ->setAccountingCurrency('USD')

            // (optional) Account number from external system.
            ->setAccountNumber(Auth()->user()->crypto_account_number_gas);

        try {

            /**
             * POST /v3/ledger/account
             *
             * @var \Tatum\Model\Account $response
             */
            $response = $tSdk
                ->api()
                ->account()
                ->createAccount($arg_create_account_xpub);

            $responseData = json_decode($response);
            // dd($responseData);
            //save virtual account
            // $argb = (new \Tatum\Model\GenerateAccountAddress())
            $addressGenerated = generateAddressByAccountId($responseData->id);

            $acct = new VirtualAccounts();
            $acct->virtual_account_id=$responseData->id;
            $acct->customer_id =$responseData->customerId;
            $acct->currency = $responseData->currency;
            $acct->account_number = $responseData->accountNumber;
            $acct->account_code = $responseData->accountCode;
            $acct->accounting_currency = $responseData->accountingCurrency;
            $acct->xpub = $responseData->xpub;
            $acct->wallet_id = $cryptoWallet->id;
            $acct->virtual_account_type ='Gas';
            $acct->user_id = $user_id;
            $acct->blockchain_code=$cryptoWallet->blockchain_code;
            $acct->blockchain_name=$cryptoWallet->blockchain_name;
            $acct->attarched_address= $addressGenerated->getGeneratedAddress();
            $acct->derivation_key=$addressGenerated->getDerivationKey();
            if($acct->save()){
                return  back()->with('success',"Asset Created Successfully Make you first deposit");
            };
            //once is save generate address





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


public function precalculateGasAddress(){
$masterAddress = masterGasAddress('USDT_TRON');
//dd($masterAddress);
    $curl = curl_init();

    curl_setopt_array($curl, [
        CURLOPT_URL => "https://api.tatum.io/v3/gas-pump",
        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([
            'chain' => 'TRON',
            'owner' => $masterAddress->attarched_address,
            'from' => 1,
            'to' => 1
        ]),
        CURLOPT_HTTPHEADER => [
            "accept: application/json",
            "content-type: application/json",
            "x-api-key: ".env('TTAPIKEYLIVE')
        ],
    ]);

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

    curl_close($curl);

    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        try {
            $responseArray = json_decode($response, true);
dd($responseArray);
            // Check if decoding was successful
            if (json_last_error() === JSON_ERROR_NONE && is_array($responseArray)) {
                // Loop through each address and save to the database
                foreach ($responseArray as $index => $address) {
                    // Check if the address already exists
                    $exists = DB::table('usdt_addresses')
                        ->where('address', $address)
                        ->exists();

                    // If it does not exist, insert the new address
                    if (!$exists) {
                        DB::table('usdt_addresses')->insert([
                            'address' => $address,
                            'derivative_index' => $index, // This will be 0 for the first element, 1 for the second, etc.
                            'master_address' => $masterAddress->attarched_address,
                            'token_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
                            'master_derivative'=>$masterAddress->derivation_key
                        ]);
                    }
                }
                echo "Addresses processed successfully.";
            }

        } catch (\Exception $e) {
            echo "Database error: " . $e->getMessage();
        }
    }
}

    public function activateGasAddress(){

        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => "https://api.tatum.io/v3/gas-pump/activate",
            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([
                'chain' => 'TRON',
                //'feesCovered' => true,
                'owner' => 'TENTK4TdKExNx8uqLSF5L13saa8r4ozEbV',
                'from' => 0,
                'to' => 0,
                'feeLimit' => 24,
                'fromPrivateKey' => '7eec35fe77b1ed7bd9aa8c792b5203b53c853ecb5788081f1db9ec9d8fab5899'
            ]),
            CURLOPT_HTTPHEADER => [
                "accept: application/json",
                "content-type: application/json",
                "x-api-key: ".env('TTAPIKEYLIVE')
            ],
        ]);

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

        curl_close($curl);

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

    public function withdrawFromGas(){

        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => "https://api.tatum.io/v3/blockchain/sc/custodial/transfer",
            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([
                'chain' => 'TRON',
                'custodialAddress' => 'TQ2hgd5gbzurB4rwUsh1K1yLGGLj8P1k7a',
                'recipient' => 'TQPR6VXYYkYChahkqp3fQS1kSEf2EzmEJt',
                'contractType' => 0,
                //'tokenAddress' => '0x782919AFc85eEA2cB736874225456bB5d3e242bA',
                'amount' => '3',
                'tokenId' => '',
                'fromPrivateKey' => '0219fa135f6cf89cc77519723ed8b6f99afcb8b0c43d97526db4462002635b39',
                'nonce' => 1,
                'feeLimit' => 40,
                'fee' => [
                    'gasPrice' => '40',
                    'gasLimit' => '40',

                ]
            ]),
            CURLOPT_HTTPHEADER => [
                "accept: application/json",
                "content-type: application/json",
                "x-api-key: ".env("TTAPIKEYLIVE")
            ],
        ]);

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

        curl_close($curl);

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

    public function validateGasActivation(){


$client = new \GuzzleHttp\Client();

$response = $client->request('GET', 'https://api.tatum.io/v3/gas-pump/address/TRON/88782eff7af403dde546dddf5297d0edd4005b4a3ea0d617c918d6180e99ad1b', [
    'headers' => [
        'accept' => 'application/json',
        'x-api-key' => 't-65e6f6ed202429001bcf0a0d-3ef243888a3e4bfb8eb3dcac',
    ],
]);

echo $response->getBody();


    }



    public function createWalletProfit(){

        //$asset = "USDT_TRON";
        $asset = "ETH";
        $user_id = Auth()->user()->id;

        $cryptoWallet = BlockchainWallet::where('blockchain_code',$asset)->firstOrFail();
        //check if created
        $checkifExits = VirtualAccounts::where('user_id',$user_id)->where('wallet_id',$cryptoWallet->id)->where('virtual_account_type','Profit')->exists();

        if($checkifExits){
           echo "You already have this asset";
        }

        //dd($cryptoWallet);
//check if virtual account exist

        //dd(Auth()->user()->crypto_account_number);
        //if not crated before check if their is still pending address
        //create addresss using xpub

//echo $apiKey; die();
        // $tSdk->testnet()->config()->setDebug(true);
        $response = initiateTatum();
        $customer = new \Tatum\Model\CustomerRegistration(['external_id'=>"R2TTRAD000001000PROFIT",'accounting_currency'=>'USD']);
        try {
            if($asset=='USDT_TRON'){
//just create account
                $arg_create_account = (new \Tatum\Model\CreateAccount())

                    // <p>The currency for the virtual account</p> <ul> <li><b>Native blockchain assets:</b> ALGO, BCH, ...
                    ->setCurrency('USDT_TRON')

                    // Extended public key to generate addresses from.
                    //  ->setXpub($cryptoWallet->xpub)

                    // (optional) \Tatum\Model\CustomerRegistration
                    ->setCustomer($customer)

                    // (optional) Enable compliant checks. If this is enabled, it is impossible to create account if compliant chec...
                    ->setCompliant(false)

                    // (optional) For bookkeeping to distinct account purpose.
                    ->setAccountCode("TRAD000001000PROFIT")

                    // (optional) All transaction will be accounted in this currency for all accounts. Currency can be overridden p...
                    ->setAccountingCurrency('USD')

                    // (optional) Account number from external system.
                    ->setAccountNumber("000001002");
//dd($arg_create_account);
                $addressGenerated = getUSDTAddress();
                try {
                    $responseData = $response->api()->account()
                        ->createAccount($arg_create_account);
                    // dd($responseData->getId());
                } catch (\Tatum\Sdk\ApiException $apiExc) {
                    echo sprintf(
                        "API Exception when calling api()->account()->getAccounts(): %s\n",
                        var_export($apiExc->getResponseObject(), true)
                    );
                } catch (\Exception $exc) {
                    echo sprintf(
                        "Exception when calling api()->account()->getAccounts(): %s\n",
                        $exc->getMessage()
                    );
                }
                // $addressGenerated = generateAddressByAccountId($responseData->id);
                //check if created already
                // $accountCheck = checkAccount('USDT_TRON',Auth()->user()->crypto_account_number);

                $assignedStatus = assignAddressToVA($responseData->getId(),$addressGenerated->address);
                if($assignedStatus) {
                    $acct = new VirtualAccounts();
                    $acct->virtual_account_id = $responseData->getId();
                    $acct->customer_id = $responseData->getCustomerId();
                    $acct->currency = $responseData->getCurrency();
                    $acct->account_number = $responseData->getAccountNumber();
                    $acct->account_code = $responseData->getAccountCode();
                    $acct->accounting_currency = $responseData->getAccountingCurrency();
                    // $acct->xpub = $responseData->xpub;
                    $acct->wallet_id = $cryptoWallet->id;
                    $acct->virtual_account_type = 'ProfitGas';
                    $acct->user_id = $user_id;
                    $acct->blockchain_code = $cryptoWallet->blockchain_code;
                    $acct->blockchain_name = $cryptoWallet->blockchain_name;
                    $acct->attarched_address = $addressGenerated->address;
                    $acct->is_attarched = 1;
                    $acct->derivation_key = $addressGenerated->derivative_index;
                    $acct->master_address = $addressGenerated->master_address;
                    $acct->master_derivative = $addressGenerated->master_derivative;
                    $acct->token_address = $addressGenerated->token_address;
                    if ($acct->save()) {
                        //attarched address to an account
                        $addressGenerated->assigned_to=$user_id;
                        $addressGenerated->assigned_wallet_id=$acct->id;
                        $addressGenerated->save();
                       echo "Asset Created Successfully! Make you first deposit";
                    };
                }

            }else {
//just generate it using xpub
                $arg_create_account = (new \Tatum\Model\CreateAccountXpub())
                    // <p>The currency for the virtual account</p> <ul> <li><b>Native blockchain assets:</b> ALGO, BCH, ...
                    ->setCurrency($cryptoWallet->blockchain_code)

                    // Extended public key to generate addresses from.
                    ->setXpub($cryptoWallet->xpub)

                    // (optional) \Tatum\Model\CustomerRegistration
                    ->setCustomer($customer)

                    // (optional) Enable compliant checks. If this is enabled, it is impossible to create account if compliant chec...
                    ->setCompliant(false)

                    // (optional) For bookkeeping to distinct account purpose.
                    ->setAccountCode("TRAD000001000PROFIT")

                    // (optional) All transaction will be accounted in this currency for all accounts. Currency can be overridden p...
                    ->setAccountingCurrency('USD')

                    // (optional) Account number from external system.
                    ->setAccountNumber("000001002");
                $responseData= $response->api()->account()
                    ->createAccount($arg_create_account);
                $addressGenerated = generateAddressByAccountId($responseData->getId());


                $acct = new VirtualAccounts();
                $acct->virtual_account_id=$responseData->getId();
                $acct->customer_id =$responseData->getCustomerId();
                $acct->currency = $responseData->getCurrency();
                $acct->account_number = $responseData->getAccountNumber();
                $acct->account_code = $responseData->getAccountCode();
                $acct->accounting_currency = $responseData->getAccountingCurrency();
                $acct->xpub = $responseData->getXpub();
                $acct->wallet_id = $cryptoWallet->id;
                $acct->virtual_account_type ='Profit';
                $acct->user_id = $user_id;
                $acct->blockchain_code=$cryptoWallet->blockchain_code;
                $acct->blockchain_name=$cryptoWallet->blockchain_name;
                $acct->attarched_address= $addressGenerated->getGeneratedAddress();
                $acct->derivation_key=$addressGenerated->getDerivationKey();
                if($acct->save()){
                    return  back()->with('success',"Asset Created Successfully! Make you first deposit");
                };

            }





            //  $responseData = json_decode($response);
            // dd($responseData);
            //save virtual account
            // $argb = (new \Tatum\Model\GenerateAccountAddress())


            //once is save generate address





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

    }

}

