<?php

class FinoByte extends CFormModel
{
    public $type = 'finobyte';
    private $currencies = array('TRC20_USDT'); // LTC
    private $action = 'https://psp.finobyte.solutions/api/v1/transaction/CreateTransaction';
    private $bearer = '6621550c-96ae-4658-9599-026ceffac066';

    public $amount;
    public $transferTo;
    public $currency;
    public $transaction_id;
    public $my_address;

    //callback
    public $TransactionId;
    public $OriginalAmount;
    public $Status;
    public $AmountWithoutCommission;

    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('TransactionId, OriginalAmount, Status, AmountWithoutCommission', 'required', 'on' => 'callback',  'message'=> Yii::t("main","36_cannot_be_blank")),
		);
	}

    public function init()
	{

	}
	
    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(is_string($res)){
            $fData = [
                'TransactionId' => $this->transaction_id,
                'TransactionType' => 0,
                'PlatformAccountId' => (int)$data['transferTo'],
            ];

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $this->action,
                CURLOPT_CUSTOMREQUEST => "POST",
                //CURLOPT_CONNECTTIMEOUT => 5,
                //CURLOPT_REFERER => $this->cred_ar[$this->credentials]['ref'],
                //CURLOPT_POSTFIELDS => "{\"NotificationOption\":\"LNK\",\"CustomerName\": \"Ahmed\",\"DisplayCurrencyIso\": \"KWD\", \"MobileCountryCode\":\"+965\",\"CustomerMobile\": \"92249038\",\"CustomerEmail\": \"aramadan@myfatoorah.com\",\"InvoiceValue\": 100,\"CallBackUrl\": \"https://google.com\",\"ErrorUrl\": \"https://google.com\",\"Language\": \"en\",\"CustomerReference\" :\"ref 1\",\"CustomerCivilId\":12345678,\"UserDefinedField\": \"Custom field\",\"ExpireDate\": \"\",\"CustomerAddress\" :{\"Block\":\"\",\"Street\":\"\",\"HouseBuildingNo\":\"\",\"Address\":\"\",\"AddressInstructions\":\"\"},\"InvoiceItems\": [{\"ItemName\": \"Product 01\",\"Quantity\": 1,\"UnitPrice\": 100}]}",
                CURLOPT_POSTFIELDS => json_encode($fData),
                CURLOPT_HTTPHEADER => array("Authorization: Bearer ".$this->bearer,"Content-Type: application/json"),

            ));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

            $response = json_decode(curl_exec($curl), true);
            $err = curl_error($curl);

            $this->my_address = $response['walletAddress'];



            curl_close($curl);
        }else{
            $_SESSION['message'][] = array("text" => json_encode($res), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
        }

        $data2["message"] = Yii::t("funds","446_use_finobyte_address");
        $data2['type'] = $this->type;
        $data2['key'] = $this->my_address;

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

        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);
    }
}
