<?php

namespace App\Services\ThirdPartyApiServices\BSCApi;

use App\Models\ApiSettings;
use App\Services\ThirdPartyApiServices\BaseApiCall;

class BSCApi extends BaseApiCall
{
    protected array $data = [];
    protected $config;
    protected $chainId;

    public function __construct()
    {
        $this->config = ApiSettings::where('domain_holder', '=', 'bsc_scan_api')->first();
        $this->setApiUrl(getSiteSettings('api_mode') == 'live' ? $this->config['live_api_source'] : $this->config['test_api_source']);
        $this->chainId = getSiteSettings('api_mode') == 'live' ? $this->config['live_chain_id'] : $this->config['test_chain_id'];
        $this->setCredential($this->config['api_key']);
    }

    /**
     * Get block number by transaction hash
     *
     * @param $txHash
     * @param $contractAddress
     *
     * @return float|int|string
     */
    public function getBlockNumberByTransactionHash($txHash, $contractAddress)
    {
         $this->setContractAddress($contractAddress);
        $getTransactionByHash = $this->getTransactionByHash($txHash, $contractAddress);
        if (!isset($getTransactionByHash['result'])) {
            return [
                'error' => 1,
                'msg' => "No result found",
            ];
        }
        $blockNumberInHex = $getTransactionByHash['result']['blockNumber'];
        return hexdec($blockNumberInHex);
    }

    /**
     * Get transaction by hash
     *
     * @param                $txHash
     * @param array|string[] $query
     *
     * @return array|mixed|void
     */
    public function getTransactionByHash($txHash, $contractAddress = '', array $query = ['module' => 'proxy', 'action' => 'eth_getTransactionByHash'])
    {
        $this->setContractAddress($contractAddress);
        $this->setQueryData($query, ['txhash' => $txHash,'chainid' => $this->chainId], 'eth');
        return $this->callToApi();
    }

    public function getEtherscanTransactionByBlockResponse($blockNumber = 0, $ethAddress = '', $txHash = '', $contractAddress = '', array $query = ['module' => 'account', 'action' => 'tokentx', 'page' => 1,'offset' => 1000,'sort' => 'desc']){
        $this->setContractAddress($contractAddress);
        $startblock = $blockNumber - 1;
	    $endblock = $blockNumber + 1;
        $this->setQueryData($query, [ 'address' => $ethAddress,'startblock' => $startblock,'endblock' => $endblock,'txhash' => $txHash,'chainid' => $this->chainId], 'eth');
        return $this->callToApi();
    }
}
