<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Gateway\nowpayments\NowPaymentsAPI;
use App\Models\Coins;
use App\Models\CryptoTransaction;
use BitWasp\Bitcoin\Address\PayToPubKeyHashAddress;
use BitWasp\Bitcoin\Key\Deterministic\HierarchicalKeyFactory;
use BitWasp\Bitcoin\Network\NetworkFactory;
use btc\HD;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use PrevailExcel\Nowpayments\Facades\Nowpayments;
use Illuminate\Http\Request;
use BitcoinPHP\BitcoinECDSA\BitcoinECDSA;
use Nimiq\XPub;
use \BitWasp\Bitcoin\Bitcoin;

use \BitWasp\Bitcoin\PrivateKeyFactory;
use stdClass;
use Samrap\Gemini\Gemini;
use GuzzleHttp\Client;
use App\Http\Controllers\Gateway\KrakenAPI;
use KingFlamez\Rave\Facades\Rave as Flutterwave;


class CryptoControllernk extends Controller
{

    private $network = NULL;
    private $baseUrl='https://api.sandbox.gemini.com/v1';
    private $secretKey='master-oOI44bqYu7HeICPhV8ii';

    public function privateRequest(string $api, array $data = []) : array
    {





        $uri = $this->baseUrl.trim($api, '/');
        $endpoint = sprintf('/%s/%s', self::API_VERSION, trim($api, '/'));
        $payload = new Payload($endpoint, $data);
        $request = $this->messageFactory->createRequest('POST', $uri, [
            'Content-Type' => 'text/plain',
            'Content-Length' => 0,
            'X-GEMINI-APIKEY' => $this->key,
            'X-GEMINI-PAYLOAD' => $payload->encode(),
            'X-GEMINI-SIGNATURE' => Signature::generate($payload, $this->secret),
            'Cache-Control' => 'no-cache',
        ]);

        return $this->getResponseJson($this->send($request));
    }
    public function __construct($network = 'bitcoin')
    {
        $this->network = NetworkFactory::bitcoin();

    }
    public function tradeCrypto()
    {

        $coins = Coins::where('status', '1')->get();

        return view('user.crypto.trade_crypto', compact('coins'));
    }
    //
    public function tradeCryptoTest(){
        $client = new \GuzzleHttp\Client();

// Validate and sanitize user input before using it
        $coin = trim(strtoupper('btc')); // Assuming coin comes from a GET parameter

        $url = sprintf('https://api.binance.us/api/v3/ticker/price?symbol=%sUSDT', $coin);

        try {
            $response = $client->get($url);
        } catch (Exception $e) {
            // Handle the error gracefully, e.g., log the error and provide a user-friendly message
            echo "An error occurred while fetching data: " . $e->getMessage();
            exit;
        }

// Assuming the response is successful, decode the JSON and check for errors
        $data = json_decode($response->getBody(), true);

        if (isset($data['error'])) {
            // Handle API error
            echo "API Error: " . $data['error']['message'];
            exit;
        } else {
            // Process the price data from $data
            echo "The current price of " . $coin . " is " . $data['price'];
        }
//test rate from binance
        $ch = curl_init('https://api.binance.us/api/v3/ticker/price?symbol=BTCUSDT');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'r2t');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, false ? $timeout : 7);
        curl_setopt($ch, CURLOPT_HEADER, false);
        //$crypto_rate_usd = json_decode(bxc_curl('https://api.binance.us/api/v3/ticker/price?symbol=' . 'btc' . 'USD'), true)['price'];
       // $rate = 1 / (floatval($crypto_rate_usd) * '1');

        $response = curl_exec($ch);
        if (curl_errno($ch) > 0) {
            $error = curl_error($ch);
            curl_close($ch);
            return $error;
        }
        curl_close($ch);
        dd(  $response);
        $key = 'account-D5mUBiT8OTcBqAxCjIGn';
        $secret = 'qTmYHwY6FKoJ4HSFjLagS52iAUr';
        $gemini = new Gemini($key, $secret);
       // $gemini = new Gemini();
        $symbols = $gemini->newDepositAddress('btc');

        dd($symbols['address']);
        /// Replace these with your actual API credentials
$apiKey = 'YOUR_API_KEY';
$apiSecret = 'YOUR_API_SECRET';

// URL for retrieving order book data
$url = 'https://api.gemini.com/v1/addresses/bitcoin';

// Generate the signature for the request
$timestamp = gmdate('Y-m-d\TH:i:s\Z');
$payload = $timestamp . $url;
$signature = hash_hmac('sha384', $payload, $apiSecret, true);
$encodedSignature = base64_encode($signature);

// Set headers
$headers = array(
    'X-GEMINI-APIKEY: ' . $apiKey,
    'X-GEMINI-PAYLOAD: ' . $payload,
    'X-GEMINI-SIGNATURE: ' . $encodedSignature,
    'Content-Type: application/json'
);

// Send GET request and retrieve response
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

// Decode the JSON response
$data = json_decode($response, true);
dd($data);
// Check for errors
if (isset($data['error'])) {
    echo 'Error: ' . $data['error'];
} else {
    // Process the market data (e.g., display ask and bid prices)
    echo 'Ask price: ' . $data['ask'] . '<br>';
    echo 'Bid price: ' . $data['bid'];
}


        $apiKey = 'master-oOI44bqYu7HeICPhV8ii';
        $apiSecret = '3pXwYZwxfjiaXymaLP5jo4QcejQ';

        // URL for retrieving order book data
        $url = 'https://api.sandbox.gemini.com/v1/order/book/' . 'btcusd';

        // Generate the signature for the request
        $timestamp = gmdate('Y-m-d\TH:i:s\Z');
        $payload = $timestamp . $url;
        $signature = hash_hmac('sha384', $payload, $apiSecret, true);
        $encodedSignature = base64_encode($signature);

        // Set headers
        $headers = [
            'X-GEMINI-APIKEY' => $apiKey,
            'X-GEMINI-PAYLOAD' => $payload,
            'X-GEMINI-SIGNATURE' => $encodedSignature,
            'Content-Type' => 'application/json'
        ];

        // Send GET request using Laravel's Http facade
        $response = Http::withHeaders($headers)->get($url);

        // Check for errors
       /* if ($response->failed()) {
            return response()->json(['error' => $response->json('error')], $response->getStatusCode());
        }*/

        // Decode the JSON response
        $data = $response->json();

        dd($response);
       // phpinfo();
//die();

        $xpub = 'xpub6CU38b3dFGkZMFqNk9Zcvf3DWHCzQmk3n3hA8pTPMNwi6f6KzxjxvFfvatpXUJoYEqcWQhswChYS1nfxCeUVe52HjnL1jPtynHEMASDzr8c';
            $hdFactory = new HierarchicalKeyFactory();
            $key = $hdFactory->fromExtended($xpub, $this->network);
            $hardened = $key->derivePath("0/0");
            $privateKey =  $hardened->getPrivateKey()->toWif($this->network);
            $address = new PayToPubKeyHashAddress($hardened->getPublicKey()->getPubKeyHash($this->network));
            $address = $address->getAddress($this->network);



            $cred = new stdClass();
            $cred->balance = 0;
            $cred->address = $address;
            $cred->privateKey = $privateKey;

            return $json = json_encode($cred);



        $private = PrivateKeyFactory::create();
        echo $private->getAddress()->getAddress();
        $bitcoin = new BitcoinLib();
        $privateKey = 'cQ4E323v7n4s5zG3z8sM432v89n4s5zG3z8sM432v89n4s5zG3z8sM432';
        $bitcoin->importPrivateKey($privateKey);
        $address = $bitcoin->generateAddress();

        return response()->json(['address' => $address]);
      //  Create an XPub class instance from an xpub/tpub/ypub/upub/zpub/vpub string.
        $xpub = XPub::fromString( 'xpub6CU38b3dFGkZMFqNk9Zcvf3DWHCzQmk3n3hA8pTPMNwi6f6KzxjxvFfvatpXUJoYEqcWQhswChYS1nfxCeUVe52HjnL1jPtynHEMASDzr8c' ); // => BIP44 Original


# Derive a child extended public key from it.
$xpub_i = $xpub->derive( 0 );
# You can also pass an array to derive a path.
//$xpub_i_k = $xpub->derive( [$i, $k]);

# An XPub can be serialized back into a string.
# Pass $asHex = true to serialize into a HEX string, base58 is the default.
//$xpub_string = $xpub_i->toString( $asHex = false );

# An XPub can be converted into an address.
# Pass $coin = 'eth' to convert into an ETH address.
#
# By default, xpubs are converted into standard addresses,
# ypubs are converted into nested segwit addresses,
# and zpubs are converted into native segwit addresses.
$address = $xpub_i->toAddress( $coin = 'eth' );
dd($address);

        $xpub = 'xpub6CU38b3dFGkZMFqNk9Zcvf3DWHCzQmk3n3hA8pTPMNwi6f6KzxjxvFfvatpXUJoYEqcWQhswChYS1nfxCeUVe52HjnL1jPtynHEMASDzr8c';
        $path = '0/0'; // 1st receiving address
// $path = '0/2'; // 3rd receiving address
// $path = '1/0'; // 1st change address
// $path = '1/1'; // 2nd change address
        $hd = new HD();
        $hd->set_xpub($xpub);
        $address = $hd->address_from_xpub($path);
        dd ($address);


        $bitcoinECDSA = new BitcoinECDSA();
        $bitcoinECDSA->setPrivateKey("L1cNafxv6YeP5MpWxBxcynYd7CMGDT7UwM5ZKX4Z7MpeJQCFG15A");
        dd($bitcoinECDSA->getAddress());

// Set your API key
$api_key = "23fe60e0e783488985d6db1808cd1e57";

// Set the base URL for the BlockCypher API
$base_url = "https://api.blockcypher.com/v1/btc/main";

// Set the endpoint for generating a BTC deposit address
$endpoint = "/addresses";

// Set the request headers
$headers = array(
    "Content-Type: application/json",
    "Authorization: Bearer " . $api_key
);

// Make a POST request to the BlockCypher API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $base_url . $endpoint);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

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

// Print the BTC deposit address
dd ($json["address"]);


        $coins = Coins::where('status','1')->get();

        return view('user.crypto.trade_crypto',compact('coins'));
     //   try{
            $data = [
                'price_amount' => request()->price_amount ?? 100,
                'price_currency' => request()->price_currency ?? 'usd',
                'order_id' => request()->order_id ?? uniqid(), // you can generate your order id as you wish
                'pay_currency' => request()->pay_currency ?? 'btc',
                'payout_currency' => request()->payout_currency ?? 'btc',//'USDTTRC20',
            ];

           $paymentDetails = Nowpayments::createPayment($data);
//$paymentDetails= NowPayments::getCurrencies();
            dd($paymentDetails);
            // Now you have the payment details,
            // you can then redirect or do whatever you want

           // return Redirect::back()->with(['msg'=>"Payment created successfully", 'type'=>'success'], 'data'=>$paymentDetails);
      /*  }catch(\Exception $e) {
            return Redirect::back()->withMessage(['error'=>"There's an error in the data", 'type'=>'error']);
        }*/
        //  $nowPay = new NowPaymentsAPI(env('nowPay'));

    }

    public function getEstimated($id){
        $data =
            "amount=" . 1 . "&" .
            "currency_from=usd" . "&" .
            "currency_to=" . $id;
        $rate = Nowpayments::getEstimatePrice($data);
//$paymentDetails= NowPayments::getCurrencies();
        return  response()->json(['rate'=>$rate['estimated_amount']],200);
       //dd($rate);
    }

    public function initTrade(Request $request){
        $request->validate([
            'coin'=>'required',
            'amount'=>'required'
        ]);
        $coin = Coins::where('code',$request->coin)->first();
        $transChanges=0;
        if($request->coin=='usdt'){
            $rate=1;
            $pay_amount = $request->amount;

            $address = newUSDTDepositAddress();
            $payaddress = $address;

        }else{
            $rate= getEstimated($request->amount, $request->coin);
            if($rate['type']=='error'){
                return response()->json(['message' => $rate['message']], 406);
            }
            // return response()->json(['message' => $rate], 406);

            $pay_amount= $rate['price'];
            $transChanges = $pay_amount * 0.005;
            //$key = 'master-E12zWEcmRhXOiQw0n7Uk';
            // $secret = '4DehYVbN9wQWrLYU2w6pz6PQ216K';
            $gemini = new Gemini(env('GEMINI_API'), env('GEMINI_SK'));
            // $gemini = new Gemini();
            $address = $gemini->newDepositAddress($request->coin);
            if(isset($address['address'])) {
                $payaddress = $address['address'];
            } else{
            return response()->json(['message' => 'Error Initiating Payment, Please try again'], 406);

        }
        }



            $newTrans = new CryptoTransaction();
            $orderId = 'R2T-' . uniqid().time() . Auth()->user()->id;
            $newTrans->price_amount = $request->amount;
            $newTrans->price_in_usd = $request->amount;
            $newTrans->price_currency = 'usd';
            $newTrans->order_id = $orderId;
            $newTrans->coin = $request->coin;
            $newTrans->pay_currency = $request->coin;
            $newTrans->user_id = Auth()->user()->id;
            $newTrans->payout_currency = 'usdttrc20'; //env('PAYOUT','btc');
            $newTrans->pay_address = $payaddress;
            $newTrans->rate = $coin->rate;
            $newTrans->pay_amount = $pay_amount + $transChanges;
            $newTrans->converted_amount =0;
            $newTrans->order_description = '$' . $request->amount . ' ' . $request->coin . ' Crypto Trading';
            $newTrans->payment_creation_status = 'Initialized';
            $newTrans->referred_by = Auth()->user()->refer_by;
            $newTrans->refer_bonus_rate = $coin->refer_bonus;
            if ($newTrans->save()) {
                // $payStatus = NowPayments::getPaymentStatus('4703776273');
                //\  dd($payStatus);

                    return response()->json(['data' => $newTrans->order_id, 'message' => 'Payment Initiated Successfuly'], 200);

            }

    }

    public function trackPayment($id){
        $getPayment = CryptoTransaction::where('order_id',$id)->first();
        $getPayment->payment_status = 'Expecting Payment';

        $getPayment->save();

        return view('user.crypto.track_payment', compact('getPayment'));

    }


    public function ipnCallback(Request $request){
        $checkValid = Nowpayments::verifyIPN();
        Log::info('receive form now payment');
        Log::info($request);
        if($checkValid){ //receive from good source
            $paymentId = $request['payment_id'];
            $getTransaction = CryptoTransaction::where('payment_id',$paymentId)->first();
            $getTransaction->payment_status=$request['payment_status'];
            $getTransaction->outcome_amount=$request['payment_status'];
            Log::info("now payment request start here");
            Log::alert($request);
        }

    }

    function getBalance($address) {
        return file_get_contents('https://blockchain.info/q/addressbalance/'. $address);
    }
    function get_address_transactions($address) {
        $url = "https://mempool.space/api/address/{$address}/txs";
        $response = file_get_contents($url);
        if ($response !== false) {
            return json_decode($response, true);
        } else {
            return null;
        }
    }

    function filter_transactions_by_amount($transactions, $amount) {
        $filtered_transactions = [];
        foreach ($transactions as $tx) {
            //if(isset($tx['value'])) {
                if ($tx['value'] >=0) {
                    $filtered_transactions[] = $tx;
                }
            //}
        }
        return $filtered_transactions;
    }

    public function testCoinBase(){
        $apiKey = 'bb62d873-757f-4457-b71e-44c14c293e36';
        $endpoint = 'https://api.commerce.coinbase.com/charges';

        $data = array(
            'name' => 'Order #123',
            'description' => 'Sample Charge',
            'local_price' => array(
                'amount' => '10.00',
                'currency' => 'USD'
            ),
            'pricing_type' => 'fixed_price',
            'metadata' => array(
                'customer_id' => '123456'
            )
        );

        $headers = array(
            'Content-Type: application/json',
            'X-CC-Api-Key: ' . $apiKey
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        curl_close($ch);

// Process the response
        $responseData = json_decode($response, true);
        dd($responseData);
// Handle the response data as needed
    }

public function testConfirm(){
//btctousd


// your api credentials
    $key = 'cmBq5tyrK68Dj+2VbZMM2qY1k0dgFw8nuiEzIayWCMC/pj+U3x+mWmlg';
    $secret = 'ZOexz6LpYp6q5WNf3KVk8wJ1ffb7n+EAGkNI89/5/iFuvGfyO6tsen7HgncGK8A9yUjvjKYypLI3fUqPlvw/Yw==';

    // API endpoint
    $endpoint = 'https://api.kraken.com/0/private/DepositAddresses';

// set which platform to use (beta or standard)
    $beta = false;
    $url = $beta ? 'https://api.beta.kraken.com' : 'https://api.kraken.com';
    $sslverify = $beta ? false : true;
    $version = 0;

    $kraken = new KrakenAPI($key, $secret, $url, $version, $sslverify);

// Query a public list of active assets and their properties:
  //  $res = $kraken->QueryPublic('Assets');
   $res= $kraken->getDepositAddresses('XBT', 'Bitcoin');
    dd($res);
die();
    $apiKey = '65f76a0208d04c0001d720de';
    $apiSecret = 'cd5640c3-bdc0-4f13-97be-d1b088aade63';
    $apiPassphrase = 'qKh5gedVKxnfAX9i2d94EBh7grsfcMq1';
    $timestamp =  round(microtime(true) * 1000);

    $endpoint = '/api/v1/deposit-addresses';
    $httpMethod = 'POST';
    $nonce = uniqid();
    $requestBody = json_encode([
        'currency' => 'btc',
    ]);

    $signString = $timestamp . $httpMethod . $endpoint . $requestBody . $nonce;
    $signature = base64_encode(hash_hmac('sha256', $apiPassphrase, $apiSecret, true));

    $headers = [
        'Content-Type' => 'application/json',
        'KC-API-KEY' => $apiKey,
        'KC-API-SIGN' => $signature,
        'KC-API-TIMESTAMP' => $timestamp,
        'KC-API-PASSPHRASE' => $apiPassphrase,
        'KC-API-NONCE' => $nonce,
    ];

    $client = new \GuzzleHttp\Client([
        'base_uri' => 'https://api.kucoin.com',
    ]);

    try {
        $response = $client->post($endpoint, [
            'headers' => $headers,
            'json' => [
                'currency' => 'YOUR_CURRENCY',
            ],
        ]);

        $body = $response->getBody();
        $data = json_decode($body);

        // Access the generated deposit address
        $depositAddress = $data->data->address;

        // Use the deposit address as needed
        echo 'New deposit address: ' . $depositAddress;
    } catch (\GuzzleHttp\Exception\RequestException $e) {
        // Handle request error
        echo 'Error: ' . $e->getMessage();
    }
    die();



    $apiEndpoint = 'https://pro-api.coinmarketcap.com/v1/tools/price-conversion';
    $apiKey = 'f2e9c0b7-7edd-4889-b97c-83c2e19b7b9e'; // Replace with your actual API key

    $parameters = [
        'amount' => '1',
        'symbol' => 'BTC',
        'convert' => 'USD'
    ];

    $url = $apiEndpoint . '?' . http_build_query($parameters);

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        'X-CMC_PRO_API_KEY: ' . $apiKey
    ]);

    $response = curl_exec($curl);

    if ($response === false) {
        echo 'Error accessing CoinMarketCap API: ' . curl_error($curl);
        exit();
    }

    $data = json_decode($response, true);
//dd($data);
    if (isset($data['data']['quote']['USD']['price'])) {
        $usdPrice = $data['data']['quote']['USD']['price'];
       // $convertedAmount = $parameters['amount'] * $usdPrice;

        echo "0.00038 BTC is approximately $usdPrice USD\n";
    } else {
        echo 'Failed to convert BTC to USD using CoinMarketCap API.';
    }

    curl_close($curl);

    $apiEndpoint = 'https://api.gemini.com/v2/ticker/btcusdt';

    $curl = curl_init($apiEndpoint);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($curl);

    if ($response === false) {
        echo 'Error accessing Gemini API: ' . curl_error($curl);
        exit();
    }

    $data = json_decode($response, true);
dd($data);
    if (isset($data['last'])) {
        $btcPrice = $data['last'];

        echo "BTC Price: $btcPrice USD\n";
    } else {
        echo 'Failed to retrieve BTC price from Gemini API.';
    }

    curl_close($curl);


    //mempool
// Address to query
    $address = "1DyDvLSenrGC2ZfiLWknBMQA5xMare1ST1";


// Build the API endpoint URL
    $url = 'https://mempool.space/api/address/' . $address . '/txs/chain';

// Make the API request
    $response = file_get_contents($url);

    if ($response === false) {
        echo 'Error accessing mempool.space API';
        exit();
    }

    $data = json_decode($response, true);

// Check if there are any transactions for the address
    if (empty($data)) {
        echo 'No transactions found for the address.';
        exit();
    }

// Get the last received transaction
    $lastTransaction = $data[0]; // Assuming the transactions are sorted in descending order (most recent first)

    $totalReceivedAmount = 0;
    $totalConfirmations = 0;
    $receiveDate =  null;
    $transId = null;


    foreach ($data as $transaction) {
        if (isset($transaction['status']['confirmed'])) {
            $totalConfirmations += $transaction['status']['confirmed'];
            $receiveDate = $transaction['status']['block_time'];
        }
        foreach ($transaction['vout'] as $output) {
            if ($output['scriptpubkey_address'] === $address) {
                $transId =$transaction['txid'];
                $totalReceivedAmount += $output['value'];
                echo $output['scriptpubkey_address'];
            }
        }
    }

    $totalReceivedAmount = $totalReceivedAmount / 100000000; // Convert satoshis to BTC

    echo "Total Received Amount: " . $totalReceivedAmount . " BTC\n";
    echo "Total Confirmations: " . $totalConfirmations . " confirmations\n";
    echo "Recived Id: " .$transId;

dd($data);

    $address = '1DyDvLSenrGC2ZfiLWknBMQA5xMare1ST1'; // Replace with the address you want to query

// Build the API endpoint URL
    $url = 'https://mempool.space/api/address/' . $address . '/txs';

// Make the API request
    $response = file_get_contents($url);

    if ($response === false) {
        echo 'Error accessing mempool.space API';
        exit();
    }

    $data = json_decode($response, true);
// Check if there are any transactions for the address
    if (empty($data)) {
        echo 'No transactions found for the address.';
        exit();
    }

// Get the last received transaction
    $lastTransaction = $data[0]; // Assuming the transactions are sorted in descending order (most recent first)

    $transactionId = $lastTransaction['txid'];
    $confirmations = $lastTransaction['status']['block_height'];
    $receivedAmount = $lastTransaction['vout'][0]['value'];
    $senderAddress = $lastTransaction['vin'][0]['prevout']['scriptpubkey_address'];
    $networkFees = $lastTransaction['fee'];
   // $timestamp = $lastTransaction['time'];
   // $date = date('Y-m-d H:i:s', $timestamp);

    echo "Last Transaction ID: " . $transactionId . "\n";
    echo "Confirmation Status: " . $confirmations . " confirmations\n";
    echo "Received Amount: " . $receivedAmount . " BTC\n";
    echo "Sender Address: " . $senderAddress . "\n";
    echo "Network Fees: " . $networkFees . " satoshis\n";
  //  echo "Date: " . $date . "\n";
   dd($data);


    $url = "https://blockchain.info/rawaddr/" . '1DyDvLSenrGC2ZfiLWknBMQA5xMare1ST1';
    $addr = '1DyDvLSenrGC2ZfiLWknBMQA5xMare1ST1';
    $response = file_get_contents($url);

    if ($response === false) {
        echo 'Error accessing API';
        exit();
    }

    $data = json_decode($response, true);

    $totalReceived = $data['total_received'];
    $balance = $totalReceived / 100000000; // Convert from satoshis to BTC

    echo "Total Received: " . $totalReceived . " satoshis\n";
    echo "Total Balance: " . $balance . " BTC\n";

    $lastTx = $data['txs'][0]; // Retrieve the first transaction (most recent)
    $lastReceivedDate = $lastTx['time'];
    $lastReceivedAddress = $lastTx['out'][0]['addr'];
    $transactionId = $lastTx['hash'];

    $inputValue = 0;
    $outputValue = 0;
    $senderAddress = '';

    foreach ($lastTx['inputs'] as $input) {
        if (isset($input['prev_out']['addr']) && $input['prev_out']['addr'] == $addr) {
            $inputValue += $input['prev_out']['value'];
            $senderAddress = $input['prev_out']['addr'];
        }
    }

    foreach ($lastTx['out'] as $output) {
        if ($output['addr'] == $addr) {
            $outputValue += $output['value'];
        }
    }

    $networkCharges = $inputValue - $outputValue;
    $sentAmount = $outputValue - $networkCharges;

    echo "Last Received Date: " . date('Y-m-d H:i:s', $lastReceivedDate) . "\n";
    echo "Last Received Address: " . $lastReceivedAddress . "\n";
    echo "Transaction ID: " . $transactionId . "\n";
    echo "Network Charges: " . $networkCharges . " satoshis\n";
    echo "Sent Amount: " . $sentAmount . " satoshis\n";
    echo "Sender Address: " . $senderAddress . "\n";

    if (isset($lastTx['confirmations'])) {
        $confirmations = $lastTx['confirmations'];
        if ($confirmations > 0) {
            echo "Transaction is confirmed. Confirmations: " . $confirmations . "\n";
        } else {
            echo "Transaction is unconfirmed. Confirmations: " . $confirmations . "\n";
        }
    } else {
        echo "Confirmations field not present in the transaction data.\n";
    }

    dd($data);



    $r = file_get_contents('https://blockchain.info/q/addressbalance/1DyDvLSenrGC2ZfiLWknBMQA5xMare1ST1');
$addr='1DyDvLSenrGC2ZfiLWknBMQA5xMare1ST1';
    if ($r === false) {
        echo 'Error accessing API';
        exit();
    }
dd($r);
    $b = (int)$r;

    echo $addr . '\t' . $r . ' sat\t' . ($b / 100000) . ' mBTC\t' . ($b / 100000000) . ' BTC';
        confirmBalance('1DyDvLSenrGC2ZfiLWknBMQA5xMare1ST1');
   // $address = "1dice8EMZmqKvrGE4Qc9bUFf9PX3xaYDp";
   // $transactions = $this->get_address_transactions($address);
//dd($transactions);
//die();
   /* if ($transactions !== null) {
        // Assuming amount is in Satoshis (1 BTC = 100,000,000 Satoshis)
        $amount_to_check = 100000000; // For example, 1 BTC
        $filtered_transactions = $this->filter_transactions_by_amount($transactions, $amount_to_check);
       // dd($filtered_transactions);
        if (!empty($filtered_transactions)) {
            echo "Transactions found with the specified amount:<br>";
            foreach ($filtered_transactions as $tx) {
                print_r($tx);
                echo "<br>";
            }
        } else {
            echo "No transactions found with the specified amount.";
        }
    } else {
        echo "Error retrieving transaction information.";
    }
    die();
   */
//blokocnomy

    //$balance = $this->getBalance('1dice8EMZmqKvrGE4Qc9bUFf9PX3xaYDp');
//dd(satToBtc($balance));
  //  echo 'Address Balance: ' . getBalance('1EzwoHtiXB4iFwedPr49iywjZn2nnekhoj');

 //   echo json_encode($response);
  /*  $address = "1dice8EMZmqKvrGE4Qc9bUFf9PX3xaYDp"; // Replace with your actual Bitcoin address
    $apiKey = "hihv7pldoxmdsrTN84JESyrnCPe7k8SALKRqEc4o2Ho"; // Replace with your Blockonomics API key

    $addresses ="1LjFSQYBCMipDXGh7doSTFWW3Zsr6fx31k"; // Replace with your actual Bitcoin addresses (whitespace separated)
   // $apiKey = "YOUR_API_KEY_HERE"; // Replace with your Blockonomics API key

// Initialize a cURL handle
    $ch = curl_init("https://www.blockonomics.co/api/balance");

// Set cURL options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Capture response instead of printing it
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL certificate verification (not recommended for production)
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // Skip SSL hostname verification (not recommended for production)

// Set request method to POST
    curl_setopt($ch, CURLOPT_POST, true);

// Prepare the request body
    $requestBody = json_encode(['addr' =>  $addresses]); // Implode to create the whitespace-separated list

// Set the request body with proper content type
    curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

// Set the Authorization header
    $headers = array('Authorization: Bearer ' . $apiKey);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Execute the cURL request
    $response = curl_exec($ch);
//dd($response);
// Check for errors
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
        exit;
    }

// Close the cURL handle
    curl_close($ch);

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

// Process the response data (refer to Blockonomics API documentation)
    if (isset($data['balances'])) {
        foreach ($data['balances'] as $address => $balance) {
            echo "Address: " . $address . ", Balance: " . $balance . " Satoshi<br>";
        }
    } else {
        echo "Failed to retrieve balances.";
    }
*/
$url = 'https://mempool.space/api/address/1DyDvLSenrGC2ZfiLWknBMQA5xMare1ST1/txs/chain';

// Initialize cURL
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Capture response instead of printing it
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL certificate verification (not recommended for production)
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // Skip SSL hostname verification (not recommended for production)

// Execute the cURL request
$response = curl_exec($ch);
//dd($response);
// Check for errors
if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
    exit;
}

// Close the cURL resource
curl_close($ch);

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


    $total_in = 0;
    $total_out = 0;
    dd($data[0]);
$transaction= $data[0];
// Calculate total amount received (in)
    foreach ($transaction['vout'] as $output) {
        $total_in += $output['value'];
    }

// Calculate total amount sent (out)
    foreach ($transaction['vin'] as $input) {
        $total_out += $input['prevout']['value'];
    }

    echo "Total amount received (in): " . $total_in . " Satoshi\n";
    echo "Total amount sent (out): " . $total_out . " Satoshi\n";
// Process the data
if (isset($data['txs'])) {
    foreach ($data['txs'] as $tx) {
        echo "Transaction ID: " . $tx['txid'] . "<br>";
        // Access other transaction details as needed (refer to API documentation)
    }
} else {
    echo "No transactions found for the address.";
}

}
    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;
       $orderId= $request->order_id;
        $trans = CryptoTransaction::where('order_id',$orderId)->where('user_id',Auth()->user()->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;
            $trans->price_in_usd = btctoUsd($trans->coint);
            $trans->coin_rate = $trans->price_in_usd;
            //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;

                if ($trans->fund_wallet_status != 'Pending' || $trans->fund_wallet_status != 'Balance') {
                    $trans->fund_wallet_status='Pending';
                    //load wallet
                    Auth()->user()->saveToClientWallet($trans->converted_amount, $trans->user_id, 'Pending');
                    if (!empty($trans->referred_by)) {
                        $bonus = $trans->recieved_converted_amount * $trans->refer_bonus_rate;
                        $trans->refer_bonus= $bonus;
                        Auth()->user()->saveToClientWallet($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.')', 'orderId'=>$trans->order_id], 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 == 'usdt') {//explorer.bnbchain.org
        $trans->payment_status = 'Reviewing Payment';
        $trans->price_in_usd=1;
        $trans->coin_rate = $trans->price_in_usd;

        $trans->coin_confirm_status = '0';
        $trans->save();
       // dd(address)
        updateUsdtAddressUsed($trans->pay_address, $trans->created_at, $trans->user_id);

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


    }

    public function viewTrade($id){
        $getPayment = CryptoTransaction::where('order_id',$id)->first();


        return view('user.crypto.view_crypto_trade', compact('getPayment'));

    }


    public function buyCrypto(){
        $coins = Coins::where('status', '1')->get();

        return view('user.crypto.buy',  compact('coins'));
    }

    public function confirmPreview(Request $request){
        $request->validate([
            'amount'    => 'required|numeric|gt:0',
            'address' => 'required',
            'payment_method'=>'required',
            'coin'=>'required'

        ]);

        $coin =  Coins::where('code', $request->coin)->first();
        if(empty($coin)){
            return response()->json([
                'status' => 'error',
                'message' => 'Coin not available'
            ], 400);
        }
$buyCrypto = Session::get('buyCrypto');
        if(!empty($buyCrypto)
            &&
            ($buyCrypto->price_amount==$request->amount) && ($buyCrypto->pay_address==$request->address) && ($buyCrypto->coin==$request->coin) && ($buyCrypto->payment_method==$request->payment_method)){
//this is good do nothing
           // dd($buyCrypto);
            }else{

            $buyCrypto = new CryptoTransaction();
            $buyCrypto->price_amount = $request->amount;
            $buyCrypto->pay_currency = 'NGN';
            $buyCrypto->price_currency = 'NGN';
            $buyCrypto->pay_address = $request->address;
            $buyCrypto->coin = $request->coin;
            $buyCrypto->rate = $coin->selling_rate;
            $buyCrypto->refer_bonus_rate = $coin->selling_refer_bonus;
            $buyCrypto->referred_by = Auth()->user()->refer_by;
            $buyCrypto->transaction_type = 1;
            $buyCrypto->payment_status = 'Pending';
            $buyCrypto->coin_rate = btctoUsd($coin->code);
            $buyCrypto->payment_method = $request->payment_method;
            $buyCrypto->price_in_usd = numFormat(($request->amount / $coin->selling_rate), 2);
            $buyCrypto->amount_received = numFormat($buyCrypto->price_in_usd / $buyCrypto->coin_rate, 6);

            $buyCrypto->order_id = 'R2T-BY' . uniqid() . Auth()->user()->id;;

            $buyCrypto->user_id = Auth()->user()->id;
            $buyCrypto->payout_currency = $request->coin; //env('PAYOUT','btc');

            $buyCrypto->pay_amount = $request->amount;
            $buyCrypto->converted_amount = $buyCrypto->price_in_usd;

            $buyCrypto->order_description = 'Buying of ' . toMoney($request->amount) . ' ' . $coin->name;
            //$buyCrypto->save();
            Session::put('buyCrypto', $buyCrypto);
        }

        return view('user.crypto._inner_confirm', [
            'model'=>$buyCrypto

        ])->render();


    }
    public function confirmOrder(Request $request){
        $request->validate([
            'orderId'    => 'required',


        ]);

        $coin =  Coins::where('code', $request->coin)->first();
        if(empty($coin)){
            return response()->json([
                'status' => 'error',
                'message' => 'Coin not available'
            ], 400);
        }

        $buyCrypto = Session::get('buyCrypto');
        if(!empty($buyCrypto)){
            $model = $buyCrypto->save();
            if($model->payment_method=='Wallet'){

            }
        }



        return 'uscess';


    }
    public function confirmOrderByWallet(Request $request){

        $buyCrypto = Session::get('buyCrypto');
        if(empty($buyCrypto)){
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid Trade please try again'
            ], 400);
        }
        $request->validate([
            'password'=>'required',


        ]);

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

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

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

       // $transferAmount =  numFormat($request->amount);

            if ($wallet->balance < $finalAmount ) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Insufficient balance please fund you wallet and try again'
                ], 400);
            }
            $wallet->balance -=  $finalAmount;

       // $coin =  Coins::where('code', $request->coin)->first();
        $buyCrypto->payment_status='Confirmed';
       $buyCrypto->save();
       $wallet->save();
 Session::remove('buyCrypto');


        return response()->json([
            'status' => 'success',
            'orderId' => $buyCrypto->order_id,
            'message' => 'Payment Successful',
        ], 200);

       // return 'uscess';


    }

    public function paymentConfirmed(Request $request){
        $model = CryptoTransaction::where('order_id',$request->id)->first();
        return view('user.crypto.payment_confirmed',compact('model'));
    }

    public function confirmOrderByCard(Request $request){

        $buyCrypto = Session::get('buyCrypto');
        if(empty($buyCrypto)){
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid Trade please try again'
            ], 400);
        }
      /*  $request->validate([
            'orderId'=>'required',


        ]);*/



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

        //This generates a payment reference
        $reference = Flutterwave::generateReference();

        // Enter the details of the payment
        $data = [
            'payment_options' => 'banktransfer',
            'amount' => $buyCrypto->pay_amount,
            'email' => Auth()->user()->email,
            'tx_ref' => $reference,
            'currency' => "NGN",
            'redirect_url' => route('user.crypto.card-callback'),
            'customer' => [
                'email' => Auth()->user()->email,
                "phone_number" => Auth()->user()->phone,
                "name" => Auth()->user()->name,
            ],

            "customizations" => [
                "title" => 'Payment for Purchasing of Coin',
                "description" => $buyCrypto->description
            ]
        ];

        $payment = Flutterwave::initializePayment($data);


        if ($payment['status'] !== 'success') {
            // notify something went wrong
            dd($payment);
            return response()->json([
                'status' => 'error',
                'message' => 'Payment Gate Error Please Try again'
            ], 400);
        }

       // return redirect($payment['data']['link']);
        // $coin =  Coins::where('code', $request->coin)->first();
        $buyCrypto->payment_status='Initiated';
        $buyCrypto->save();

        Session::remove('buyCrypto');


        return response()->json([
            'status' => 'success',
            'orderId' => $buyCrypto->order_id,
            'url' => $payment['data']['link'],
            'message' => 'Payment Successful',
        ], 200);

        // return 'uscess';


    }


    public function cardPaymentcallback()
    {

        $status = request()->status;

        //if payment is successful
        if ($status ==  'successful') {

            $transactionID = Flutterwave::getTransactionIDFromCallback();
            $data = Flutterwave::verifyTransaction($transactionID);

            dd($data);
        }
        elseif ($status ==  'cancelled'){
            //Put desired action/code after transaction has been cancelled here
            dd(request());
        }
        else{
            //Put desired action/code after transaction has failed here
            dd(request());
        }
        // Get the transaction from your DB using the transaction reference (txref)
        // Check if you have previously given value for the transaction. If you have, redirect to your successpage else, continue
        // Confirm that the currency on your db transaction is equal to the returned currency
        // Confirm that the db transaction amount is equal to the returned amount
        // Update the db transaction record (including parameters that didn't exist before the transaction is completed. for audit purpose)
        // Give value for the transaction
        // Update the transaction to note that you have given value for the transaction
        // You can also redirect to your success page from here

    }



}
