<?php

class CryptApi extends CFormModel
{
    public $type = 'cryptapi';
    private $currencies = array('TRC20_USDT'); // LTC

    public $amount;
    public $transferTo;
    public $currency;
    public $transaction_id;
    private $my_address_currencies;

    private $my_address;
    private $salt = 'vaRB3/IRNkp7';


    //callback
    public $md5;
    public $value_forwarded_coin;
    public $coin;
    public $value_coin;
    public $result;
    public $pending;
    public $clientName;


    public function rules(){
		return array(
			array('amount, account, currency', 'required', 'on' => 'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),
			array('currencyCode', 'in', 'range' => $this->currencies, 'message' => Yii::t("sp","120_not_listed")),

            array('md5, amount, transferTo, currency, transaction_id, value_forwarded_coin, coin, value_coin, pending, clientName, result', 'required', 'on' => 'callback',  'message'=> Yii::t("main","36_cannot_be_blank")),
		);
	}

    public function init()
	{
        require_once $_SERVER["DOCUMENT_ROOT"]."/protected/config/CryptAPI/CryptAPI.php";
        $this->my_address_currencies = Yii::app()->params['cryptapi_keys'];
        if(count($this->currencies) === 1) {
            $this->currency = $this->currencies[0];
        }
	}
	
    public function getAttribute($name){
		return $this->$name;
	}

    public function initData($data)
    {
        $this->transaction_id = uniqid().'_'.Yii::app()->params['type'];
        $res = $this->newTransaction((int)$data['transferTo'], (float)$data["amount"], $this->transaction_id);

        if(Yii::app()->params['cryptapi_qr'] != ''){
            $url = "https://api.blockbee.io/trc20/usdt/estimate/";

            $response = file_get_contents($url);

            if($response === false){
                $message = Yii::t("funds","446_use_cryptapi_address");
            }else{
                $data = json_decode($response, true);
                if (isset($data['estimated_cost_currency']['USD'])) {
                    $message = Yii::t("funds","446_use_cryptapi_address_dynamic", array('{amount}'=>$data['estimated_cost_currency']['USD'] . " USD"));
                } else {
                    $message = Yii::t("funds","446_use_cryptapi_address");
                }
            }

            return [
                "message" => $message,
                "type" => $this->type,
                "key" => Yii::app()->params['cryptapi_purse'],
                "qrcode" => Yii::app()->params['cryptapi_qr']
            ];
        }

        $data2 = [];

        $http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
        $callback_url = $http.'//'.$_SERVER['HTTP_HOST'].'/callbackTrans?type='.$this->type;

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($callback_url);die();
        }*/

        $this->currency = strtolower($data["currency"]);


        $this->my_address = $this->my_address_currencies[strtolower($this->currency)];

        $this->amount = (float)$data["amount"];

        $Registration = new Registration('Individual');
        $Registration->initIndv();

        $parameters = [
            'clientName' => $Registration->firstName.' '.$Registration->lastName,
            'transaction_id' => $this->transaction_id,
            'transferTo' => (int)$data['transferTo'],
            'currency' => $this->currency,
            'amount' => $this->amount,
            'md5' => md5($this->amount.$this->currency.(int)$data['transferTo'].$this->transaction_id.$this->salt),
        ];

        $cryptapi_params = [];

        $ca = new CryptAPI\CryptAPI($this->currency, $this->my_address, $callback_url, $parameters, $cryptapi_params);

        $payment_address = $ca->get_address();





        if(is_string($payment_address)) {
            $url = "https://api.blockbee.io/trc20/usdt/estimate/";

            $response = file_get_contents($url);

            if($response === false){
                $message = Yii::t("funds","446_use_cryptapi_address");
            }else{
                $data = json_decode($response, true);
                if (isset($data['estimated_cost_currency']['USD'])) {
                    $message = Yii::t("funds","446_use_cryptapi_address_dynamic", array('{amount}'=>$data['estimated_cost_currency']['USD'] . " USD"));
                } else {
                    $message = Yii::t("funds","446_use_cryptapi_address");
                }
            }

            $data2["message"] = $message;
            $data2['type'] = $this->type;
            $data2['key'] = $payment_address;
        }

        $qrcodeData = $ca->get_qrcode(false, 200);



        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump('qr', $qrcodeData);die();
        }*/

        if(isset($qrcodeData->status) && $qrcodeData->status === 'success') {
            $data2['qrcode'] = 'data:image/png;base64, ' . $qrcodeData->qr_code;

        }


        return $data2;
    }

	public function newTransaction($accountID, $value, $transactionID, $currency = 'USD') {
		$Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$transactionID.'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=35');

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$transactionID.'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=35');die();
        }*/

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/cryptapi.txt',"a");
            fwrite($f, date('Y-m-d H:i:s').' NewTransaction CryptApi  -  '.Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.$transactionID.'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=5'.' :response: '.json_encode($Info).' <br/>\n
		');

		return  $Info;
	}

	public function ApplyCryptoTransferTransaction($errorCode, $transactionid, $netValue = '0', $currency = 'USD') {
		//var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyNettellerTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue);die();

        if(strstr($transactionid, '_')){
            $tmp = explode('_', $transactionid);
            $server = (isset($tmp[1]) && in_array($tmp[1], ['t2', 'eforex', 'tm', 'gt'])) ? Yii::app()->params['json_server_eforex'] : Yii::app()->params['json_server'];
        }else{
            $server = Yii::app()->params['json_server'];
        }

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
         var_dump('success');die();
        }*/

        $Info = Yii::app()->curl->get($server.'/API/Transactions/ApplyCryptoTransferTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.($netValue == '0' ? '' :'&currency='.$currency));

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($Info, $server.'/API/Transactions/ApplyCryptoTransferTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.($netValue == '0' ? '' :'&currency='.$currency));die();
        }*/

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/cryptapi.txt',"a");
			fwrite($f, date('Y-m-d H:i:s').' ApplyCryptoTransferTransaction  -  '.$server.'/API/Transactions/ApplyCryptoTransferTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.($netValue == '0' ? '' :'&currency='.$currency).' :response: '.json_encode($Info).' <br/>\n
		');

		return  $Info;
	}

    public function confirmOnReturn(){
        return true;
    }

    public function isSuccess()
    {
        return $this->pending == '0';
    }

    public function getRedirectLink()
    {
        if($this->isSuccess()) {
            return '/transaction.html?ammount='.$this->amount.'&currency='.$this->currency.'&account='.$this->account;
        }else{
            return '/transaction.html?errorText=';
        }
    }

    public function parseCallback($json)
    {
        $payment_data = CryptAPI\CryptAPI::process_callback($json);
        $this->attributes = $payment_data;

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
         var_dump($this->checkMD5(), $this->isSuccess());die();
        }*/

        if($this->checkMD5() && $this->isSuccess()) {
            /*$conversion = CryptAPI\CryptAPI::get_convert('usd', $this->value_forwarded_coin, $this->coin, Yii::app()->params['cryptapi_keys']['trc20_usdt']);
            $conversion->value_coin;
            if(isset($conversion->status) && $conversion->status === 'success') {
                $amount = round($conversion->value_coin, 2).' '.' USD';*/
                $amount = round($this->value_forwarded_coin, 2).' '.' USD';
                $params = [
                    'type' => $this->type,
                    'clientName' => $this->clientName,
                    'account' => $this->transferTo,
                    //'rate' => $conversion->exchange_rate,
                    'amount' => $amount,
                    'receivedAmount' => $this->value_forwarded_coin.' '.strtoupper($this->coin),
                    'originalAmount' => $this->value_coin.' '.strtoupper($this->coin),
                    'md5' => md5($amount.$this->transferTo),
                    'date' => date("m/d/Y H:i"),
                ];

                $res = $this->ApplyCryptoTransferTransaction(($this->pending == '0' ? 'APPROVED' : 'FAILED'), $this->transaction_id, $this->value_coin, /*$conversion->value_coin,*/ 'usd');
                // var_dump($res);die();

                if(is_string($res) && $res == 'TransactionDoesntExist'){
                    $sendResult = stFunctions::sendMailNotLogin('trCompl', $params);

                }

                /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
                if ($ip == '78.46.17.32') {
                     // var_dump('1111111', $json, $this->attributes, $sendResult);die();
                }*/

                echo '*ok*';
                die();
            //}
        }

        // var_dump('parseCallback', $this->attributes, $conversion);die();
    }

    private function checkMD5()
    {
        return $this->md5 === md5($this->amount.$this->currency.$this->transferTo.$this->transaction_id.$this->salt);
    }
}
