<?php
include_once $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'config.php';
include_once $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'api'.DIRECTORY_SEPARATOR.'bitAPI.php';

//instantiate ModelClassEx
$system = new System();

//instantiate api class
$bitAPI = new BitAPI();

//error_log paths
$apiPath 		= dirname(SYSTEM_PATH).DIRECTORY_SEPARATOR.'api';
$responseUrl 	= $apiPath.DIRECTORY_SEPARATOR.'Logs'.DIRECTORY_SEPARATOR.'Bitcoin'.DIRECTORY_SEPARATOR.'response';
$responseDbUrl 	= $apiPath.DIRECTORY_SEPARATOR.'Logs'.DIRECTORY_SEPARATOR.'Bitcoin'.DIRECTORY_SEPARATOR.'db_response';
$errorUrl 	    = $apiPath.DIRECTORY_SEPARATOR.'Logs'.DIRECTORY_SEPARATOR.'Bitcoin'.DIRECTORY_SEPARATOR.'error';
$accessLogUrl 	= $apiPath.DIRECTORY_SEPARATOR.'Logs'.DIRECTORY_SEPARATOR.'Bitcoin'.DIRECTORY_SEPARATOR.'access';

//check if directory exists if not, create directory
if(!file_exists($responseUrl)) {
    mkdir($responseUrl, 0777, true);
}

if(!file_exists($responseDbUrl)) {
    mkdir($responseDbUrl, 0777, true);
}

if(!file_exists($errorUrl)) {
    mkdir($errorUrl, 0777, true);
}

if(!file_exists($accessLogUrl)) {
    mkdir($accessLogUrl, 0777, true);
}

//log the error details
error_log(date("[Y-m-d H:i:s]")."\r\n".'Accessed' ."\r\n\r\n", 3, $accessLogUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log');
chmod($accessLogUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log',511);

//Get bitcoin rate
$ch = curl_init('https://api.atmoszero.com/crypto/rate/BTC/EUR');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($ch);
$data1 = json_decode($data);
$rate = $data1->{'data'}->{'EUR'};


//check get parameters
if(!empty($_GET)){
    //get response parameters
    $uri_response = $_SERVER['REQUEST_URI'];
	$responseArray = explode("?", $uri_response);
	$response = $responseArray[1];


    //validate first the signature from the response
    $is_valid = $bitAPI -> verifyCallbackToken($_GET['wallet_address'], $_GET['token']);

    //get transaction from database
    $res = $system -> getRowData($system -> accessSelect('SELECT_TEMP_DEPOSIT_BIT', array("bit_address", $_GET['wallet_address'])));

    //get necessary details from result
    $transactionNumber = $system -> getColumnData($res, 'transaction_number'); //transaction number
    $userAccount       = $system -> getColumnData($res, 'user_account'); //user account
    $userFullName      = $system -> getColumnData($res, 'user_fullname'); //user fullname
    $language          = $system -> getColumnData($res, 'language'); //language
    $currency          = $system -> getColumnData($res, 'currency'); //currency
    $date_created      = $system -> getColumnData($res, 'create_time'); //currency
	$date_updated      = date('Y-m-d H:i:s');

    //if token is valid
    if($is_valid) {
        //check if status is approved
        if($_GET['status'] == 'approved') {
            //do computation of fees

            $recievedAmount   = floatval($_GET['amount']);
            $convertedAmount   = bcmul($recievedAmount, $rate, 4);
            $fee              = bcmul($convertedAmount, VAL_STR_BIT_FEE_VAL, 4);
			$feeVal	= round(bcdiv($fee, DIGIT_PERCENT, 4), 2);

            $iwlDepositAmount = $convertedAmount - floatval($feeVal);

            //insert to deposit table
            $insertArray = array();

            $insertArray['Model']['transaction_number']     = $transactionNumber;
            $insertArray['Model']['user_account']           = $userAccount;
            $insertArray['Model']['amount']                 = number_format($iwlDepositAmount, 2,"","");
            $insertArray['Model']['currency']               = $currency;
            $insertArray['Model']['method']                 = 'BIT';
            $insertArray['Model']['deposit_bank']           = 'BTC Solution';
            $insertArray['Model']['deposit_date']           = $date_updated;
            $insertArray['Model']['fee']                    = 0;
            $insertArray['Model']['message']                = 'Cryptocurrency Solution';
            $insertArray['Model']['comment']                = $response."   conversion_rate:".$rate."  converted_amount:".$convertedAmount."  fee:".$feeVal;
            $insertArray['Model']['create_time']            = $date_created;
            $insertArray['Model']['update_time']            = $date_updated;
            $insertArray['Model']['process_user']           = '9999';
            $insertArray['Model']['type']                   = '0';
            $insertArray['Model']['err_flg']                = '0';

            //instantiate sql object
            $sqlObject = new mysql($system->getConfigValue(SECTION_DB,HOST_NAME),$system->getConfigValue(SECTION_DB,USER_NAME),$system->getConfigValue(SECTION_DB,LOGIN_PASS),$system->getConfigValue(SECTION_DB,TARGET_DB_NAME),'','UTF8');

            //insert into main deposit table
            $sql = "insert into t_deposit ";
            $strsql = $sqlObject->Insertsql($insertArray['Model']);
            $sql .= $strsql;
            $sqlObject->query($sql);

            //log the db response
            error_log(date("[Y-m-d H:i:s]")."\r\n".$transactionNumber.' db_response:' ."\r\n". $sql ."\r\n", 3, $responseDbUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log');
            chmod($responseDbUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log',511);


            //create email parameters
            $params   = array();
            $params[] = $userAccount;
            $params[] = $userFullName;
            $params[] = $currency;
            $params[] = $transactionNumber;
            $params[] = $date_updated;
            $params[] = number_format($convertedAmount,2,'.','');
            $params[] = number_format($iwlDepositAmount,2,'.','');

            //send email
            $system -> sendMailByTmp($language.DIRECTORY_SEPARATOR.'bit_success.xml'
                    , $params
                    , $system -> getUserEMailCommon($userAccount)
                    , VAR_CS_MAIL_ADDRESS);

        } else {
            //log the transaction details if status is not approved
            error_log(date("[Y-m-d H:i:s]")."\r\n".$transactionNumber.' response:' ."\r\n". $response ."\r\n", 3, $responseUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log');
            chmod($responseUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log',511);
        }
    } else {
        //log the error details if token is not valid
        error_log(date("[Y-m-d H:i:s]")."\r\n".'Invalid Signature ERROR:' ."\r\n"."\r\nresponse:\r\n". $response ."\r\n", 3, $errorUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log');
        chmod($errorUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log',511);
    }

    //create update parameters (updating t_deposit_bit_temporary)
    $updateArray   = array();
    $updateArray[] = $transactionNumber;
    $updateArray[] = ($rate!==NULL) ? $rate : 0;
    $updateArray[] = ((floatval($_GET['amount']))!== NULL) ? $convertedAmount : 0;
    $updateArray[] = $date_updated;
    $updateArray[] = 1;

    //update t_deposit_bit_temporary
    $system -> accessModifyCommon('UPDATE_TEMP_DEPOSIT_BIT', $updateArray);
}
