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

header("Content-type:text/html; charset=utf-8");

//instantiate System class
$core = new System();

//error_log paths
$apiPath 		= dirname(SYSTEM_PATH).DIRECTORY_SEPARATOR.'api';
$callbackAccessUrl 	= $apiPath.DIRECTORY_SEPARATOR.'Logs'.DIRECTORY_SEPARATOR.'Cryptocoin'.DIRECTORY_SEPARATOR.'callback_access';
$responseDbUrl 	= $apiPath.DIRECTORY_SEPARATOR.'Logs'.DIRECTORY_SEPARATOR.'Cryptocoin'.DIRECTORY_SEPARATOR.'deposit_db_response';
$errorCallbackUrl 	= $apiPath.DIRECTORY_SEPARATOR.'Logs'.DIRECTORY_SEPARATOR.'Cryptocoin'.DIRECTORY_SEPARATOR.'callback_error_response';

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

$strInput = file_get_contents('php://input');
$responseArray = json_decode($strInput, true);

//log the transaction details
error_log(date("[Y-m-d H:i:s]")."\r\n" . $_SERVER['REMOTE_ADDR'] . "  Callback Response: \r\n". $strInput . "\r\n". implode("&",$responseArray) . "\r\n", 3, $callbackAccessUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log');
chmod($callbackAccessUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log',511);

//validate ip comming from the response
//if(in_array($_SERVER['REMOTE_ADDR'], array('3.0.109.71','121.58.194.162'))) { //live
if(in_array($_SERVER['REMOTE_ADDR'], array('13.251.212.166','13.229.245.81','122.49.220.26','127.0.0.1','121.58.194.162'))) { //test

	$responseArrayString = http_build_query($responseArray,'',', ');

	if(completePostData($responseArray)) {
		//Select transaction on crypto_temp table if is_reflected is 0
		$res = $core  -> getRowData($core  -> accessSelect('SELECT_TEMP_DEPOSIT_CRYPTO', array($responseArray['merchant_transaction_id'])));

		if(count($res) > 0){
			$transactionNumber  = $core -> getColumnData($res, 'transaction_number');
			$userAccount        = $core -> getColumnData($res, 'user_account');
			$language           = $core -> getColumnData($res, 'language');
			$amount             = $core -> getColumnData($res, 'amount');
			$fee                = $core -> getColumnData($res, 'fee');
			$depositFee         = $core -> getColumnData($res, 'fee');
			$currency           = $core -> getColumnData($res, 'currency');
			$createTime			= $core -> getColumnData($res, 'create_time');
			$depositDate        = date("Y-m-d H:i:s");

			if($responseArray['status'] == 'completed'){
				//insert on t_deposit
				$insertArray = array();

				$insertArray['Model']['transaction_number']     = $transactionNumber;
				$insertArray['Model']['user_account']           = $userAccount;
				$insertArray['Model']['amount']                 = number_format($amount, 2,"","");
				$insertArray['Model']['currency']               = $currency;
				$insertArray['Model']['method']                 = 'CRYPTOCOIN';
				$insertArray['Model']['deposit_bank']           = 'Cryptocoin Solution';
				$insertArray['Model']['deposit_date']           = $depositDate;
				$insertArray['Model']['fee']                    = 0;
				$insertArray['Model']['message']                = 'Cryptocoin Solution';
				$insertArray['Model']['comment']                = $responseArrayString;
				$insertArray['Model']['create_time']            = $createTime;
				$insertArray['Model']['update_time']            = $depositDate;
				$insertArray['Model']['process_user']           = '9999';
				$insertArray['Model']['type']                   = '0';
				$insertArray['Model']['err_flg']                = '0';

				//instantiate sql object
				$sqlObject = new mysql($core ->getConfigValue(SECTION_DB,HOST_NAME), $core ->getConfigValue(SECTION_DB,USER_NAME), $core ->getConfigValue(SECTION_DB,LOGIN_PASS),$core ->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);

				//update temporary crypto table
				$updateParam[]=$transactionNumber;
				$updateParam[]=$responseArray['crypto_currency'];
				$updateParam[]=$responseArray['crypto_value'];
				$updateParam[]=$responseArray['exchange_rate'];
				$updateParam[]=$depositDate;
				$updateParam[]='1';
				$core  -> accessModifyCommon('UPDATE_TEMP_DEPOSIT_CRYPTO', $updateParam);

				//set email params
				$params   = array();
	            $params[] = $userAccount;
	            $params[] = $core -> getColumnData($res, 'user_fullname');
	            $params[] = $currency;
	            $params[] = $transactionNumber;
	            $params[] = $depositDate;
	            $params[] = number_format($amount + $fee,2,'.','');
	            $params[] = number_format($amount,2,'.','');

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

			}else if ($responseArray['status'] == 'expired'){
				//log error
				error_log(date("[Y-m-d H:i:s]")."\r\n".$transactionNumber.' STATUS EXPIRED FAIL:' ."\r\n". implode("&",$responseArray) ."\r\n", 3, $errorCallbackUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log');
				chmod($errorCallbackUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log',511);
				//update temp crypto table
				$updateParam[]=$transactionNumber;
				$updateParam[]='';
				$updateParam[]=0;
				$updateParam[]=0;
				$updateParam[]=$depositDate;
				$updateParam[]='1';
				$core  -> accessModifyCommon('UPDATE_TEMP_DEPOSIT_CRYPTO', $updateParam);

				//set email params
				$params   = array();
				$params[] = $userAccount;
				$params[] = $core -> getColumnData($res, 'user_fullname');

				//send success email
				$core -> sendMailByTmp($language.DIRECTORY_SEPARATOR.'crypto_fail.xml'
						, $params
						, $core -> getUserEMailCommon($userAccount)
						, VAR_CS_MAIL_ADDRESS);
			}
		}else{
			//log error, NO VALID temp db entry
			error_log(date("[Y-m-d H:i:s]")."\r\n NO VALID TEMP DB ENTRY FAIL: \r\n". implode("&",$responseArray) ."\r\n", 3, $errorCallbackUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log');
			chmod($errorCallbackUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log',511);
		}
	}else{
		//log Incomplete request details error
		error_log(date("[Y-m-d H:i:s]")."\r\n Incomplete request details error \r\n".$responseArrayString."\r\n", 3, $errorCallbackUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log');
		chmod($errorCallbackUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log',511);
	}
}else{
	//log IP error
	error_log(date("[Y-m-d H:i:s]")."\r\n Invalid IP error \r\n\r\n", 3, $errorCallbackUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log');
	chmod($errorCallbackUrl.DIRECTORY_SEPARATOR.'Log_'.date("Y-m-d").'.log',511);
}

function completePostData($responseData) {
	$rtn = true;

	if(!isset($responseData['id']) ||
		!isset($responseData['merchant_transaction_id']) ||
		!isset($responseData['amount']) ||
		!isset($responseData['status'])){

		$rtn = false;
	}

	return $rtn;
}
