<?php
namespace App\Services\PaymentGateways\Coin\Bitcoin\Api;

use App\Helpers\PaymentGateways\Bnb\BnbNodeHelper;
use App\Interfaces\PaymentsGateways\Coin\CoinGatewayInterface;
use App\Services\PaymentGateways\Coin\Ethereum\Api\EthereumGateway;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Setting;

class BitcoinGateway implements CoinGatewayInterface
{
    /**
     * Used to generate address wallet per currency
     * @return array
     */
    public function createBitcoinAddress() {
        return bitcoind()->getnewaddress()->get();
    }

    /**
     * Used to generate data to withdraw
     * @param $address
     * @param $amount
     * @return array
     */
    public function withdraw($type, $withdrawal, $address, $amount)
    {
        $response = bitcoind()->sendToAddress($address, $amount);

        $message = '';
        $source = '';

        if ($response->hasError()) {
            $status = STATUS_VALIDATION_ERROR;
        } else {
            $status = STATUS_OK;
            $message = generate_string();
            $source = $message;
        }

        //return the tx id
        $txn = $response->get();

        if($txn) {
            $withdrawal->txn = $txn;
            $withdrawal->update();
        }

        return [
            'status' => $status,
            'source' => $source,
            'message' => $message,
        ];
    }

    public function withdrawBrc($withdrawal, $txn)
    {
        $status = STATUS_OK;

        if($txn) {
            $withdrawal->txn = $txn;
            $withdrawal->update();
        } else {
            $status = STATUS_VALIDATION_ERROR;
        }

        return [
            'status' => $status,
            'source' => '',
            'message' => generate_string(),
        ];
    }

    public static function send($address, $amount)
    {
        try {
            $response = bitcoind()->sendToAddress($address, $amount);
        } catch (BitcoindException $bitcoindException) {
            throw new WithdrawException('Unable to send via bitcoind->sendtoaddress', $bitcoindException->getMessage());
        }

        if ($response->hasError()) {
            throw new WithdrawException('Unable to send via bitcoind->sendtoaddress', $response->error());
        }

        //return the tx id
        return $response->get();
    }
}
