<?php
// app/api/deposits/depositvalid

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    $out = new stdClass();
    
    $request = array('method'=>'trc20byaddress',"address" => 'TWQZ32qWk8dg5E85dntwBMeGk4RmRMYE16', 'confirmed' => true);
    $restConfirmed = json_decode(queryServicesUSDT($USDT_URL, $request), true);
    $out->url = $USDT_URL;
    //$out->aaaa = $restConfirmed;
    
    if(count($restConfirmed['data']) >0){
        foreach($restConfirmed['data'] as $deposit){
            $date = new DateTime('now', new DateTimeZone('America/Caracas'));
            $currentDate = $date->format('Y-m-d H:i:s');
            $out->testing [] = array('id'=>$deposit['transaction_id'],
                'amount'=>formattUsdtAmount($deposit['value'], $deposit['token_info']['decimals']),
);
        }
    }
    
    $sql = "SELECT * FROM currencies WHERE interface = 6 AND id > 0";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db).$sql));
        
    $currencydata = $rs->fetch_assoc();
    /*
    $date = new DateTime('now', new DateTimeZone('America/Caracas'));
                                $currentDate = $date->format('Y-m-d H:i:s');
                submitDeposit($db, array('id'=>'11122332132111111',
                                    'address'=>'TJERW5C8ipEnn4KAFyXzgf42Mqw1gGP7EP',
                                    'amount'=>formattUsdtAmount(0.01, 8),
                                    'created_at'=>date('Y-m-d H:i:s',strtotime($currentDate)),
                                    'completed_at'=>date('Y-m-d H:i:s',strtotime($currentDate)),
                                    'txid'=>'d9d55c00c9d3c4c19b1b6ed5e24aae37f0e2f162b5cb4d4cd2dfc4473dba758f1'), $currencydata);
    
    $valuestest = array(10000000000, 1000000000, 100000000, 10000000 ,1000000, 100000, 10000, 1000, 100, 10, 1);
    foreach($valuestest as $val){
        $out->formatted [] = formattUsdtAmount($val, 6);
    }
    */
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    function submitDeposit($db, $deposit, $currencydata){
        //Validamos que el deposito no este ingresado y que la wallet exista
        $sql = "SELECT COUNT(ref) AS qty ".
        "       FROM deposits ".
        "       WHERE ref = '".$deposit['id']."' OR paymentref='".$deposit['txid']."'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db).$sql));
        
        $depositdata = $res->fetch_assoc();
        
        //Consultamos que la wallet exista
        $sql = "SELECT COUNT(id) AS qty ".
        "       FROM wallets ".
        "       WHERE wallet = '".$deposit['address']."'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db).$sql));
                    
        $wallet = $res->fetch_assoc();
                        
        //Si es verdadero, consultamos los datos del usuario(cuenta, nivel, fee)
        if(intval($wallet['qty']) == 1 && intval($depositdata['qty']) == 0){
            //Consultamos los datos de la wallet para obtener el id de la account
            $accountdata = getAccountData($db, $deposit['address']);
                            
            //Consultamos los datos del usuario para determinar su fee
            $userdata = getUserdata($db, $accountdata['userid'], $deposit['address']);
            
            $level = 1;
        
            if($userdata["level"] == 0){
                $level = 1;
            }else{
                $level = $userdata["level"];
            }
            
            //Consultamos la cuenta que tiene la moneda del retiro de AFX
            $afxdata = getAccountAFX($db, $currencydata['id']);
            
            //Obtenemos el fee de cada operacion por la moneda de la cuenta
            $fee = getFee($db, $level, $currencydata['id'], $userdata["type"]);
            
            //Calculamos el monto real quitandole la comision
            if($fee["pctfeedeposits"] != null || $fee["nmlfeedeposits"] != null ){
                if($fee["pctfeedeposits"] == null){
                    
                    $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
                    "       WHERE currencyid = ".$currencydata['id'].
                    "       AND userid = ".$accountdata['userid'].
                    "       AND preffeesfield = 'nmlfeedeposits'";
                    if (!$res=$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db).$sql));
                    
                    $userExg = $res->fetch_assoc();
                    
                    $realfee = number_format($deposit['amount'] - ($deposit['amount'] - ($fee["nmlfeedeposits"] - ($fee["nmlfeedeposits"]/100 * $userExg['exonerated']) )), $currencydata['decimals'], '.', '');
                    $realamount = number_format($deposit['amount'] - $realfee, $currencydata['decimals'], '.', '');
                }else{
                    
                    $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
                    "       WHERE currencyid = ".$currencydata['id'].
                    "       AND userid = ".$accountdata['userid'].
                    "       AND preffeesfield = 'pctfeedeposits'";
                    if (!$res=$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db).$sql));
                    
                    $userExg = $res->fetch_assoc();
                    
                    $realfee = number_format((($fee["pctfeedeposits"] - ($fee["pctfeedeposits"]/100 * $userExg['exonerated']) )*$deposit['amount'])/100, $currencydata['decimals'], '.', '');
                    $realamount = number_format($deposit['amount'] - $realfee, $currencydata['decimals'], '.', '');
                }
            }else{
                $realfee = 0;
                $realamount = number_format($deposit['amount'] - $realfee, $currencydata['decimals'], '.', '');
            }
            
            $db->autocommit(FALSE);
            
            //insertamos la trasaccion del deposito
            $sql = "INSERT INTO transactions".
            "       (".
            "       datecreated, ".
            "       dsc, ".
            "       amount, ".
            "       amountghost, ".
            "       accountid, ".
            "       orderid, ".
            "       txid, ".
            "       accountorigin, ".
            "       accountdestination".
            "       )".
            "       VALUES(".
            "       NOW(), ".
            "       'Depósito', ".
            "       0, ".
            "       ".number_format($deposit['amount'],$currencydata['decimals'],'.','').", ".
            "       ".$accountdata['accountid'].", ".
            "       NULL, ".
            "       NULL, ".
            "       NULL, ".
            "       ".$accountdata['accountid'].
            "       )";
            if (!$db->query($sql)){
                $error = determinateDBError($db).$sql;
                $db->rollback();
                $db->close();
                badEnd("500", array("msg"=>$error));
            }
        
            //Guardamos el id de la transaccion de deposito
            $txid = (int)$db->insert_id;
        
            //Le colocamos a la primera transferencia el txid
            $sql = "UPDATE transactions SET".
            "       txid = ".$txid.
            "       WHERE id = ".$txid;
            if (!$db->query($sql)){
                $error = determinateDBError($db).$sql;
                $db->rollback();
                $db->close();
                badEnd("500", array("msg"=>$error));
            }
                                
            //insertamos la comision del deposito
            $sql = "INSERT INTO transactions".
            "       (".
            "       datecreated, ".
            "       dsc, ".
            "       amount, ".
            "       amountghost, ".
            "       accountid, ".
            "       orderid, ".
            "       txid, ".
            "       accountorigin, ".
            "       accountdestination".
            "       )".
            "       VALUES(".
            "       NOW(), ".
            "       'Comisión de Depósito', ".
            "       0, ".
            "       -".$realfee.", ".
            "       ".$accountdata['accountid'].", ".
            "       NULL, ".
            "       ".$txid.", ".
            "       NULL, ".
            "       ".$afxdata["id"].
            "       )";
            if (!$db->query($sql)){
                $error = determinateDBError($db).$sql;
                $db->rollback();
                $db->close();
                badEnd("500", array("msg"=>$error, "afx"=>$afxdata, "currency"=>$currencydata));
            }
                
            //insertamos la comision del deposito
            $sql = "INSERT INTO transactions".
            "       (".
            "       datecreated, ".
            "       dsc, ".
            "       amount, ".
            "       amountghost, ".
            "       accountid, ".
            "       orderid, ".
            "       txid, ".
            "       accountorigin, ".
            "       accountdestination".
            "       )".
            "       VALUES(".
            "       NOW(), ".
            "       'Comisión de Depósito', ".
            "       0, ".
            "       ".$realfee.", ".
            "       ".$afxdata["id"].", ".
            "       NULL, ".
            "       ".$txid.", ".
            "       NULL, ".
            "       ".$afxdata["id"].
            "       )";
            if (!$db->query($sql)){
                $error = determinateDBError($db).$sql;
                $db->rollback();
                $db->close();
                badEnd("500", array("msg"=>$error));
            }
            $tmpdate = explode("T",$deposit['created_at']);
            //insertamos la comision del deposito
            $sql = "INSERT INTO deposits".
            "       (".
            "       paymentref, ".
            "       paymentaccountid, ".
            "       filetype, ".
            "       paymentdate, ".
            "       createddate, ".
            "       fee, ".
            "       transactionid, ".
            "       valid, ".
            "       amount, ".
            "       ref ".
            "       )".
            "       VALUES(".
            "       '".$deposit['txid']."', ".
            "       ".$accountdata['accountid'].", ".
            "       NULL, ".
            "       '".date("Y-m-d", strtotime($deposit['created_at']))."', ".
            "       '".date("Y-m-d H:i:s", strtotime($deposit['created_at']))."', ".
            "       ".$realfee.", ".
            "       ".$txid.", ".
            "       NULL, ".
            "       ".number_format($deposit['amount'],$currencydata['decimals'],'.','').", ".
            "       '".$deposit['address']."' ".
            "       )";
            if (!$db->query($sql)){
                $error = determinateDBError($db).$sql;
                $db->rollback();
                $db->close();
                badEnd("500", array("msg"=>$error));
            }
        
            $db->commit();
            $db->autocommit(TRUE);
            
            createAlertWallet($db, $deposit['address'], $txid);
        }
    }
    
    function formattUsdtAmount($value, $decimals){
        $amount = round((($value*1)/pow(10,($decimals*1))),($decimals*1));
        /*
        
        // Si el numero es menor a los decimales, significa que el monto es decimales en USDT
        if (strlen($value) <= $decimals) {
            // Al ser decimal, empieza en 0
            $begin = 0;
            // Le agregamos la cantidad de 0 dependiento del valor
            $end = str_pad($value, $decimals, '0', STR_PAD_LEFT);
            $amount = $begin.".".$end;
        } else {
            // Tomamos los valores por delante de la cantidad de decimales
            $begin = substr($value, 0, strlen($value)-$decimals);
            // tomamos los valores por detras de la cantidad de decimales
            $end = substr($value, strlen($value)-$decimals);
            $amount = $begin.".".$end;
        }*/
        
        return $amount;
    }
    
    function getUserdata($db, $userid, $msg = ''){
        $sql = "SELECT users.*, users.usr AS email, IF(userpersons.fname IS NULL, usercompanies.name, CONCAT(userpersons.fname,' ',userpersons.flastname)) AS name,  ".
        "       IF(users.type = 1, userpersons.phone, usercompanies.phone) AS phone " .
        "       FROM users ".
        "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
        "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
        "       WHERE id = ".$userid;
        if (!$res=$db->query($sql))
            badEnd("500", array("msg2"=>$db->error));
                    
        return $res->fetch_assoc();
    }
    
    function getAccountAFX($db, $currencyid){
        $sql = "SELECT * FROM accounts WHERE userid = -1".
        "       AND currencyid = ".$currencyid.
        "       AND paymentmethodid = -3";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg3"=>determinateDBError($db).$sql));
    
        //Guardamos la data de la cuenta AFX
        return $res->fetch_assoc();
    }
    
    function getFee($db, $level, $currencyid, $usertype){
        $sql = "SELECT * FROM cmspreffees WHERE currencyid = ".$currencyid.
        "       AND levelid = ".$level.
        "       AND usertype = ".$usertype;
        if (!$res=$db->query($sql))
            badEnd("500", array("msg5"=>determinateDBError($db).$sql));
    
        //Guardamos la data de la cuenta
        return $res->fetch_assoc();
    }
    
    function getAccountData($db, $depositaddress){
        $sql = "SELECT wallets.wallet AS wallet, ".
        "       accounts.id AS accountid, ".
        "       accounts.userid AS userid ".
        "       FROM wallets, accounts ".
        "       WHERE wallets.wallet = '".$depositaddress."'".
        "       AND accounts.id = wallets.accountid ".
        "       AND accounts.entityusrid = -1 ".
        "       AND accounts.paymentmethodid = -1";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg1"=>determinateDBError($db).$sql));
        
        $rsp = $res->fetch_assoc();
        if($rsp['userid']==""||$rsp['userid']==null)$rsp = "";
        return $rsp;
    }
    
    function createAlertWallet($db, $wallet, $txid = '') {
        $sql = "SELECT COUNT(id) AS qty, id FROM blacklist ".
        "       WHERE account = '".$wallet."'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db).$sql));
                
        $row = $res->fetch_assoc();
        
        // Si existe levantamos una alerta con el id del usuario
        if ($row['qty'] > 0) {
            // Obtenemos el userid
            $useraccount = getAccountData($db, $wallet);
            
            createAlert($db, 6, $useraccount['userid'], ' Cuenta encontrada en lista negativa <span>#'.$row['id'].'</span>. Transacción nro: <span>'.$txid.'</span>');
        }
    }
    
?>