<?php
// afx api/utils

//tcv key
$TCV_URL="https://tcvex.tcv.com.ve:443/api";
$TCV_JWT="eyJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE1ODkyOTY5MjAsImV4cCI6MTU4OTI5NjkyMCwic3ViIjoic2Vzc2lvbiIsImlzcyI6ImJhcm9uZyIsImF1ZCI6WyJwZWF0aW8iLCJiYXJvbmciXSwianRpIjoiRUE0ODhBQTY5NzQ1MTg2RTdCRTNGMjVDIiwidWlkIjoiSUQ5MUNDMkRBQ0U2IiwiZW1haWwiOiJhc2Vzb3JpYWZpbmFuY2llcmFjLmEyMDE4QGdtYWlsLmNvbSIsInJvbGUiOiJtZW1iZXIiLCJsZXZlbCI6Miwic3RhdGUiOiJhY3RpdmUifQ.u_ZrUoDRJ90EXmXI5WNwvnzovs6ZP3ImeuKD2VdqLkWHdcAh2IKvfuzvi4X0oSB45mRY6kibbvMk1ReLd6oE28oKXi5baanTfUcLbyxMbGv5W_ErO7GvtXDbp8laM8sVcQ76I63pynj-oXkbNVlyBnhTcRPwkn6LGIKgqmvm1xS7nJmnSKL9Ydw0oLcDxdJfUSjpnK03QM6CGNWvrrzBjOF7Se1HmeIB6BSX2PYtQZw3EbaiogsmoNYJ4ucZw0hMStUzWFESUIBItLFuXN32e1fHPafRzZkBzoRPM5y944sAoPQiDyTqhWfflbpSGE3FgxFAfm3O5Hnf8SaQV4fg5w";
$VERSION_API = 'v2';

// BTC key
$BTC_URL = "http://69.28.92.225/services/callrpc.php";

//Cargar menu
function getMenu($db, $father=0){
    if ($father==0)
        $sql =  "SELECT id, dsc, content, icon FROM cmsmenus WHERE father IS NULL ORDER BY id";
    else
        $sql =  "SELECT id, dsc, content, icon FROM cmsmenus WHERE father = " . $father . " ORDER BY orden";
    if (!$rs=$db->query($sql))
        badEnd("500", array("sql"=>$sql,"msg"=>$db->error));

    $records = array();
    
    while ($row = $rs->fetch_assoc()){
        $record = new stdClass;
        $record->id=(integer)$row["id"];
        $record->dsc=$row["dsc"];  
        $record->content = $row["content"] == null ? "" : $row["content"];
        $record->icon = $row["icon"] == null ? "" : $row["icon"];
        $record->submenu = getMenu($db, (integer)$row["id"]);  
        $records[] = $record;
    }
    
    return($records);
}

$fromeMail = "noresponder@totalsoftware.com.ve";
// Para los push
//$server_key="AAAAjYD41YY:APA91bHN5azipdeCnTs5gyRLBwCe9gfks0_JAfAmDnEpRTE54OZixI6bznNp6s3qjK5vByAVVfi9EKn5r8zImz3GYsqDQRF8204P2h3ZmiAoAm5d9YSfQU8b_80ARt6mrWDWR6n_do8Y";
function randomString($length = 10) {
//    return (substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length));
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
function getValidator(){
    return("00000000");
}

function nvl($var, $default)
{
    return isset($var) ? $var
                       : $default;
}

function dlookup($db, $campo, $tabla, $where){
    try {
        $sql = "SELECT `" . $campo . "` retval " . 
               "FROM   `" . $tabla . "` " . 
               "WHERE  " . $where;
        $rs = $db->query($sql);
        $row = $rs->fetch_assoc();
        return($row["retval"]);
    } catch (Exception $e){
        return(null);
    }
}
function isSessionValidCMS($db, $sessionid){
    // Validar sessionid activo
    $sql =  "SELECT id " .
            "FROM   cmsusers " .
            "WHERE  sessionid = '" . $sessionid . "' " .
            "AND    validthru > NOW() ";
    if (!$rs = $db->query($sql)){
        header("HTTP/1.1 500");
        echo (json_encode(array(msg=>$db->error)));
        die();
    }
    $row = $rs->fetch_assoc();
    if (!$row["id"]){
        header("HTTP/1.1 401");
        echo (json_encode(array("msg"=>"Sesión inválida o expirada")));
        die();
    }
    return($row["id"]);
}
function setAudit($db, $module, $sessionid, $application, $dsc, $ipaddress = "NULL"){
    try {
        if ($sessionid != ""){
            // obtener usuario
            $sql = "SELECT id " . 
                   "FROM   cmsusers " . 
                   "WHERE  sessionid = '" . $sessionid . "' ";
            $rs = $db->query($sql);
            $row = $rs->fetch_assoc();
            $userid = $row["id"];
        }else{
            $userid = 0;
        }
        
        // incluir auditoria
        $sql = "INSERT INTO audit (application, module, userid, dsc, ipaddress) " .
               "VALUES            ('".$application."','" . $module . "', '" . $userid . "', '" . $dsc . "', ".($ipaddress != "NULL" ? "'".$ipaddress."'" : $ipaddress).")";
        if ($rs = $db->query($sql)){
            return(true);
        }else{
            return(false);
        }
    } catch (Exception $e){
        return(false);
    }
}
function tienePrivilegio($db, $sessionid, $privilegeid){
    try {
        // obtener usuario
        $sql = "SELECT id " . 
               "FROM   cmsusers " . 
               "WHERE  sessionid = '" . $sessionid . "' ";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        $row = $rs->fetch_assoc();
        $userid = $row["id"];
        
        // incluir auditoria
        $sql = "SELECT COUNT(*) cnt " .
               "FROM   userprivileges " .
               "WHERE  userid=" . $userid . " " . 
               "AND    privilegeid=" . $privilegeid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        $row = $rs->fetch_assoc();
        if ((integer) $row["cnt"] > 0){
            return(true);
        }else{
            return(false);
        }
    } catch (Exception $e){
        return(false);
    }
}
function enviarCorreo($from, $to, $subject, $body){
    $cabeceras = 'From: ' . $from . "\r\n" .
                 'Reply-To: ' . $from . "\r\n" .
                 'X-Mailer: PHP/' . phpversion()."\r\n".
                 "Content-Type: text/html; charset=UTF-8\r\n";
    mail($to, $subject, $body, $cabeceras);
}
function escribirChat($db, $offerid, $userid, $text, $pushparams=array()){
    $sql =  "INSERT INTO chats " .
    "               (offerid, text, userid) " .
    "        VALUES (" .
    "                '" . $offerid . "'," .
    "                '" . $text . "'," .
    "                '" . $userid . "'" .
    "               )";
    if (!$db->query($sql)){
        if ($db->errno == 1062){
            badEnd("304", array("msg"=>"Registro Duplicado"));
        }else{
            badEnd("500", array("sql"=>$sql,"msg"=>$db->error));
        }
    }
    // enviarPush
    if (!is_null($pushparams)) {
        $message_status = enviarPush($db,$pushparams['userid'],$pushparams['message'],$pushparams['title'],$pushparams);

        if ($message_status ===FALSE)
            badEnd("400", array("msg"=>"Fallo la funcion enviarPush"));
    }
    //enviarPush(....)
    
    return($db->insert_id);
}
function parametrosValidos($parms, $campos){
    $out = true;
    foreach ($campos as $campo){
        if ($out)
            $out = isset($parms[$campo]) && trim($parms[$campo])!="";
    }
    return ($out);
}
function badEnd($htmlError, $output){
    header("HTTP/1.1 ".$htmlError);
    echo (json_encode($output));
    die();
}
function date_relative($ts, $now){
    if(!ctype_digit($now))
        $now = strtotime($now);
    
    if(!ctype_digit($ts))
        $ts = strtotime($ts);

    //$diff = time() - $ts;
    $diff = $now - $ts;
    if($diff == 0)
        return 'ahora';
    elseif($diff > 0)
    {
        $day_diff = floor($diff / 86400);
        if($day_diff == 0)
        {
            if($diff < 60) return 'recién';
            if($diff < 120) return 'hace un minuto';
            if($diff < 3600) return 'hace ' . floor($diff / 60) . ' minutos';
            if($diff < 7200) return 'hace una hora';
            if($diff < 86400) return 'hace ' . floor($diff / 3600) . ' horas';
        }
        if($day_diff == 1) return 'Ayer';
        if($day_diff < 7) return 'hace ' . $day_diff . ' días';
        if($day_diff < 31) return 'hace ' . ceil($day_diff / 7) . ' semanas';
        if($day_diff < 60) return 'el mes pasado';
        return date('F Y', $ts);
    }
    else
    {
        $diff = abs($diff);
        $day_diff = floor($diff / 86400);
        if($day_diff == 0)
        {
            if($diff < 120) return 'recién';
            if($diff < 3600) return 'en ' . floor($diff / 60) . ' minutos';
            if($diff < 7200) return 'en una hora';
            if($diff < 86400) return 'en ' . floor($diff / 3600) . ' horas';
        }
        if($day_diff == 1) return 'Mañana';
        if($day_diff < 4) return date('l', $ts);
        if($day_diff < 7 + (7 - date('w'))) return 'next week';
        if(ceil($day_diff / 7) < 4) return 'in ' . ceil($day_diff / 7) . ' weeks';
        if(date('n', $ts) == date('n') + 1) return 'next month';
        return date('F Y', $ts);
    }
}
// Nueva funcion
function date_relative_2($ts, $now){
    if(!ctype_digit($now))
        $now = strtotime($now);
    
    if(!ctype_digit($ts))
        $ts = strtotime($ts);

    $diff = $now - $ts;
    if($diff == 0)
        return 'Hoy - '.date('h:i a',$ts);
    elseif($diff > 0)
    {
        $day_diff = floor($diff / 86400);
        if($day_diff == 0) return 'Hoy - '.date('h:i a',$ts);
        if($day_diff == 1) return 'Ayer - '.date('h:i a',$ts);
        return date('d/m/y - h:i a', $ts);
    }
    else
    {
        $diff = abs($diff);
        $day_diff = floor($diff / 86400);
        if($day_diff == 0)
        {
            if($diff < 120) return 'recién';
            if($diff < 3600) return 'en ' . floor($diff / 60) . ' minutos';
            if($diff < 7200) return 'en una hora';
            if($diff < 86400) return 'en ' . floor($diff / 3600) . ' horas';
        }
        if($day_diff == 1) return 'Mañana';
        if($day_diff < 4) return date('l', $ts);
        if($day_diff < 7 + (7 - date('w'))) return 'next week';
        if(ceil($day_diff / 7) < 4) return 'in ' . ceil($day_diff / 7) . ' weeks';
        if(date('n', $ts) == date('n') + 1) return 'next month';
        return date('F Y', $ts);
    }
}
// Fin nueva funcion
function enviarPush ($dbconnect, $userid, $message, $title, $pushparams=array()){
        if (is_null($title)) $title='Notificación SimonExchange';
        // Obtener la lista de tokens de un usuario para ANDROID
        $sql = "SELECT userid, GROUP_CONCAT(token) as listadetokens ".
        " FROM userequipments WHERE userid=".$userid." AND status=1 AND platform=1";

        if (!$rs = $dbconnect->query($sql)) 
            return $dbconnect->error;
            
        if($row = $rs->fetch_assoc()) 
            $tokens=$row["listadetokens"];
        else
            return "La consulta no trajo registros";
        if (is_null($tokens)) return "Usuario android no encontrado";    
        // Fin Obtener lista de tokens

        $arraytokensandroid = explode(",", $tokens);
        global $server_key;
        //$additionalData = array('userid'=>$userid, 'type'=>'chat', 'offerid'=>91);
        $url = 'https://fcm.googleapis.com/fcm/send';
        //ESTOS CAMPOS SE PUEDEN MODIFICAR AQUÍ HAY QUE AÑADIR EL ICONO 
        $fields = array(
            'registration_ids'=>$arraytokensandroid,
            'data'=>array('title'=>$title, 'message'=>$message, 'sound'=>true, 'color'=>'#0D882F', 'icon'=>'ic_stat_simonicon', 'app'=>$pushparams)
            //'notification'=>array('title'=>$title, 'body'=>$message,'sound'=>true, "color" => "#0D882F", 'icon'=>'ic_stat_simonicon')            
        );
        //LA KEY DE LA APLICACIÓN EN FIREBASE
        $headers = array(
            'Authorization:key ='.$server_key,
            'Content-Type: application/json'
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
        curl_close($ch);
        return $result;
}
function obtenerUsuarios($db,$offerid){
    // Se busca el usuario offer y el usuario market de la oferta
    /*$sql= " SELECT O.id as offerid, marketid, A.userid as userid, 'offer' as tipodeusuario    ".
          "     FROM offers O ".
          "     INNER JOIN accounts A ON A.id=O.accountid    ".
          "     WHERE O.id=$offerid    ".
          "     UNION    ".
          "     SELECT O.id as offerid, marketid, A.userid as userid, 'market' as tipodeusuario    ".
          "     FROM offers O    ".
          "     INNER JOIN market M ON O.marketid = M.id    ".
          "     INNER JOIN accounts A ON A.id=M.accountid    ".
          "     INNER JOIN users U ON A.userid=U.id    ".
          "     WHERE O.id=$offerid    " ;*/
    $sql =  "SELECT O.id AS offerid, marketid, A.userid AS userid, U.name AS username, C.name AS cntryname,  'offer' AS tipodeusuario ".
            "FROM offers O ".
            "INNER JOIN accounts A ON A.id = O.accountid ".
            "LEFT JOIN users U ON A.userid = U.id ".
            "LEFT JOIN countries C ON C.id = U.countryid ".
            "WHERE O.id =".$offerid." ".
            "UNION ".
            "SELECT O.id AS offerid, marketid, A.userid AS userid, U.name AS username, C.name AS cntryname,  'market' AS tipodeusuario ".
            "FROM offers O ".
            "INNER JOIN market M ON O.marketid = M.id ".
            "INNER JOIN accounts A ON A.id = M.accountid ".
            "LEFT JOIN users U ON A.userid = U.id ".
            "LEFT JOIN countries C ON C.id = U.countryid ".
            "WHERE O.id =".$offerid;
    if (!$rs3 = $db->query($sql))
        badEnd("500", array(sql=>$sql,msg=>$db->error));

    $offeruserid=NULL;
    $marketuserid=NULL;
    
    while ($row3 = $rs3->fetch_assoc()){
        if ($row3["tipodeusuario"]=='offer') {
            $offeruserid = $row3["userid"];
            $offername = $row3["username"];
            $offercntry = $row3["cntryname"];
            $marketid=$row3["marketid"];
        }
        else if ($row3["tipodeusuario"]=='market') {
                $marketuserid = $row3["userid"];
                $marketname = $row3["username"];
                $marketcntry = $row3["cntryname"];
                $marketid=$row3["marketid"];
        }
    }
    if (is_null($offeruserid) && is_null($marketuserid)) {
        return null;   
    }
    $offerandmarketids=array('offeruserid'=>$offeruserid, 'marketuserid'=>$marketuserid, 'marketid'=>$marketid, 
                            'marketname'=>$marketname, 'marketcntry'=>$marketcntry);
    return $offerandmarketids;
}
// Funcion para validar si una oferta está en disputa
function ofertaEnDisputa($db,$offerid){
    // Se valida si el campo disputa es TRUE
    $sql =  "SELECT IF(dispute,1,0) AS endisputa FROM `offers` WHERE id=".$offerid." ";
    if (!$rs3 = $db->query($sql))
        badEnd("500", array(sql=>$sql,msg=>$db->error));

    if ($row3 = $rs3->fetch_assoc()){
        return (integer)$row3["endisputa"];   
    }
    else {
        badEnd("400", array("msg"=>"La oferta no existe"));
    }
}
// Fin Funcion
// Inicio Funcion escribirChat2
function escribirChat2($db, $offerid, $userid, $text, $marketid,$marketuserid,$offeruserid){
    $sql =  "INSERT INTO chats " .
    "               (offerid, text, userid) " .
    "        VALUES (" .
    "                '" . $offerid . "'," .
    "                '" . $text . "'," .
    "                '" . $userid . "'" .
    "               )";
    
    if (!$db->query($sql)){
        if ($db->errno == 1062){
            badEnd("304", array("msg"=>"Registro Duplicado"));
        }else{
            badEnd("500", array("sql"=>$sql,"msg"=>$db->error));
        }
    }
    $id =$db->insert_id;

    // enviarPush
    $pushparamsmarket = array('userid'=>$marketuserid, 'offerid'=>$offerid,'marketid'=>$marketid,'type'=>1,
                      'message'=>"Tienes un nuevo mensaje", 'title'=>"Simon Exchange");
    $pushparamsoffer = array('userid'=>$offeruserid, 'offerid'=>$offerid,'marketid'=>0,'type'=>1,
                      'message'=>"Tienes un nuevo mensaje", 'title'=>"Simon Exchange");
    
    $message_status = enviarPush($db,$pushparamsmarket['userid'],$pushparamsmarket['message'],$pushparamsmarket['title'],$pushparamsmarket);
    if ($message_status ===FALSE)
        badEnd("400", array("msg"=>"Fallo la funcion enviarPush"));
    
    $message_status = enviarPush($db,$pushparamsoffer['userid'],$pushparamsoffer['message'],$pushparamsoffer['title'],$pushparamsoffer);
    if ($message_status ===FALSE)
        badEnd("400", array("msg"=>"Fallo la funcion enviarPush"));
    
    return($id);
}
// Fin Funcion escribirChat2

// Funcion actualizarCache 
function actualizarCache($db, $eventid,$module){
    // Validar que existe el registro
    $sql =  "SELECT eventid, module, version " .
            "FROM   cache " .
            "WHERE  eventid = " . $eventid." ". 
            "AND    module = '".$module."'";
    if (!$rs = $db->query($sql)){
        header("HTTP/1.1 500");
        echo (json_encode(array(msg=>$db->error)));
        die();
    }
    $row = $rs->fetch_assoc();
    if (!$row["eventid"]){
        // Insertar cache
        $sql="INSERT INTO cache (eventid,module,version,lastupdate) VALUES (".$eventid.",'".$module."',1,NOW() )";
        if (!$db->query($sql)) {
            header("HTTP/1.1 500");
            echo (json_encode(array("msg"=>$db->error)));
            die();
        }
        else
            return(1);
    }
    else {
        // Update
        $sql="UPDATE cache SET version=1+".$row["version"]." ,lastupdate=NOW() WHERE eventid=".$row["eventid"]." AND module='".$row["module"]."'";
        if (!$db->query($sql)) {
            header("HTTP/1.1 500");
            echo (json_encode(array(msg=>$db->error)));
            die();
        }
        if($db->affected_rows==0) {
            header("HTTP/1.1 500");
            echo (json_encode(array("msg"=>"affected_rows == 0")));
            die();
        }
        return(1);
    }
}
// Fin actualizarCache

// Funcion updateLang 
function updateLang($db,$id){
    $sql =  "SELECT name_esp, name_eng, name_por " .
            "FROM   events " .
            "WHERE  id = " . $id." ";
    if (!$rs = $db->query($sql))
        badEnd("500", array("sql"=>$sql,"msg"=>$db->error));
    if (!$row = $rs->fetch_assoc())
        badEnd("400", array("msg"=>"Evento no existe"));

    //Los lenguajes se activan segun los nombres activados en el evento
    $languages=array();
    if (!is_null($row["name_esp"]) && strlen(ltrim($row["name_esp"]))>0)
        $languages[]="esp";
    if (!is_null($row["name_eng"]) && strlen(ltrim($row["name_eng"]))>0)
        $languages[]="eng";
    if (!is_null($row["name_por"]) && strlen(ltrim($row["name_por"]))>0)
        $languages[]="por";
    
    //El arreglo no puede ser vacio
    if (count($languages)==0)
        badEnd("400", array("msg"=>"Se necesita un nombre para el evento"));
    return implode(",",$languages);
}
// Fin updateLang
function enviarCorreo2($from, $to, $subject, $body, $altbody=""){
    $mail = new PHPMailer;
    $mail->isSMTP();
    //Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $mail->SMTPDebug = 0;
    $mail->Debugoutput = 'html';
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = 'tls';
    $mail->Host = "smtp.gmail.com";
    $mail->Port = 587;
    $mail->SMTPAutoTLS = false;
    switch ($from){
        default:
            $mail->setFrom('noreply@afx.trade', 'noresponde');
            $mail->Username = "noreply@afx.trade";
            $mail->Password = "durueiseacievdke";
        break;
    }
    $mail->addAddress($to);
    $mail->Subject = $subject;
    $mail->Body = $body;
    if ($altbody=="")
        $mail->AltBody = $body;
    else
        $mail->AltBody = $altbody;
    //send the message, check for errors
    return ($mail->send());
}
// Formateo de numeros
function numberFormatt($number, $decimals){
    //return rtrim(rtrim(number_format($number, $decimals, ",", "."), '0'), ',');
    return number_format($number, $decimals, ",", ".");
}
// Obtener IP Address
function getRealIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP']))
        return $_SERVER['HTTP_CLIENT_IP'];
   
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
  
    return $_SERVER['REMOTE_ADDR'];
}
// Separacion de filtro (+)
function separateFilter($filter){
    return explode("+", $filter);
}

// Funcion para determinar si un valor es numerico formateado o no
function validNumberFormatted($number){
    if(preg_match('/^[0-9.,-]+$/', $number))
        return true;
    else
        return false;
}
// Funcion para validar que un numero no esta formateado
function validNumber($number){
    if(preg_match('/^[0-9.]+$/', $number))
        return true;
    else
        return false;
}
//Funcion para quitar formato a numero formateado
function parseFormattedNumber($number){
    return str_replace(',', '.', str_replace('.', '', "$number"));
}
/* Funcion para llamadas publicas a la API TCV (SIN KEY)
*   Method = metodo que se llamada de la api
*   url = direccion de la api
*   version = version de la api
*   type = SI es get o no
*   request = parametros para la llamada a la api
*/
function queryPublic($method, $url, $version, $type=false, array $request = array()){
    
    //Inicializamos el protocolo
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_USERAGENT => 'TCV PHP API Agent',
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 20,
        CURLOPT_TIMEOUT => 300)
    );
    
    // Parametros
    $postdata = http_build_query($request, '', '&');
        
    // llave de la api con su version
    $path = '/' . $version . '/' . $method;
    // make request
    curl_setopt($curl, CURLOPT_URL, $url .$path);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array());
        
    //si el type es true la llamada sera GET
    if($type){
        curl_setopt($curl, CURLOPT_URL, $url .$path . '?' . $postdata);
        curl_setopt($curl, CURLOPT_POST, false); 
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
    }
        
    //Ejecutamos la llamada
    $result = curl_exec($curl);
    if ($result === false) {
        badEnd("500",array("msg"=>'CURL error: ' . curl_error($curl)));
        //throw new \Exception('CURL error: ' . curl_error($curl));
    }
    
    // Comprueba el código de estado HTTP
    if (!curl_errno($curl)) {
        switch ($httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
            case 200:  # OK
                break;
            default:
                echo 'HTTP code: ', $httpCode, "\n";
        }
    }

    $result = json_decode($result, true);
    if (!is_array($result)) {
        badEnd("500",array("msg"=>'JSON decode error'));
        //throw new \Exception('JSON decode error');
    }
    
    // Comprueba el código de estado HTTP
    if (!curl_errno($curl)) {
        switch ($httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
            case 200:  # OK
                break;
            default:
                $result['httpres'] = $httpCode;
        }
    }
    
    curl_close($curl);

        
    return $result;
}
/* Funcion para llamadas PRIVADAS a la API TCV (CON KEY)
*   Method = metodo que se llamada de la api
*   key = llave de AFX
*   url = direccion de la api
*   version = version de la api
*   type = SI es get o no
*   request = parametros para la llamada a la api
*/
function queryPrivate($method, $key, $url, $version, $type = false, array $request = array()){
    
    //Inicializamos el protocolo
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_USERAGENT => 'TCV PHP API Agent',
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 20,
        CURLOPT_TIMEOUT => 300)
    );
    
    // parametros
    $postdata = http_build_query($request, '', '&');

    // direccion de api y version
    $path = '/' . $version . '/' . $method;
        
    // Enviamos la llave
    $headers = array(
        'Authorization: ' . $key,
    );
        
    // armamos la peticion
    curl_setopt($curl, CURLOPT_URL, $url . $path);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        
    //Si type es true la llamada sera GET
    if($type){
        curl_setopt($curl, CURLOPT_URL, $url . $path . '?' . $postdata);
        curl_setopt($curl, CURLOPT_POST, false); 
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
    }
    
    //Ejecutamos la llamada
    $result = curl_exec($curl);

    if ($result === false) {
        badEnd("500",array("msg"=>'CURL error: ' . curl_error($curl)));
    }
        
    // decode results
    $result = json_decode($result, true);
    if (!is_array($result)) {
        badEnd("500",array("msg"=>'JSON decode error'));
    }
    
    // Comprueba el código de estado HTTP
    if (!curl_errno($curl)) {
        switch ($httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
            case 200:  # OK
                break;
            default:
                $result['httpres'] = $httpCode;
        }
    }
    
    curl_close($curl);

    return $result;
}
/*  Funcion para cambiar estado de verificacion del usuario, recibe:
*   userid = ID del usuario a actualizar
*   db = conexion a la base de datos
*   turn = true o false, true para colocar 1, y false para colocar 0
*/
function reqverifyuser($userid, $db, $turn){
    
    if($turn){
        $sql = "UPDATE users SET ".
        "       reqverify = 1 ".
        "       WHERE id = ".$userid;
        if (!$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
    }else{
        $sql = "UPDATE users SET ".
        "       reqverify = 0 ".
        "       WHERE id = ".$userid;
        if (!$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
    }
}

/*  Funcion para llamada a API de BTC, la cual recibe:
*   $urlbtc = direccion de la api
*   $request = arreglo con metodo y parametros a enviar
*   array('method'=>'metodo','parms' => $arreglo);
*/
function queryServicesBTC($urlbtc, array $request = array()){
    $cURLConnection = curl_init($urlbtc);
    $request["user"] = "afxtrade";
    $request["pwd"] = "AA2LtO6bIhov0exjxsX";
        
    //attach encoded JSON string to the POST fields
    curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, json_encode($request));
    //set the content type to application/json
    curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
        
    $apiResponse = curl_exec($cURLConnection);
    if ($apiResponse === false) {
        badEnd("500",array("msg"=>'CURL error: ' . curl_error($curl)));
    }
    curl_close($cURLConnection);
        
    return $apiResponse;
}   
?>