<?php
// cms/api/appusers/entry

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","id");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass();
    $sessionid = $_GET["sessionid"];
    $id = $_GET["id"];
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Consulta de los datos iniciales
    $sql = "SELECT *".
    "       FROM users".
    "       WHERE id = ".mysqli_real_escape_string($db, $id);
    if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
    $userdata = $rs->fetch_assoc();
    
    if($userdata["id"] == null){
        badEnd("204", array("msg"=>"No se encuentra el registro"));
    }
    
    if (tienePrivilegio($db, $sessionid, 29)) {
        //Creamos el objecto de salida y asignamos los datos principales
        $out->entry = new stdClass();
        $out->entry->id = (int)$userdata["id"];
        $out->entry->usr = $userdata["usr"];
        $out->entry->datecreated = $userdata["datecreated"];
        $out->entry->lastsession = $userdata["lastsession"] == null ? null :  date("d/m/Y", strtotime($userdata["lastsession"]))." - ".date("h:i a", strtotime($userdata["lastsession"]));
        
        //Describimos status
        $out->entry->status = new stdClass();
        $out->entry->status->id = (int)$userdata["status"];
        $out->entry->status->dsc = $out->entry->status->id == 0 ? "Inactivo" : "Activo";
        
        //Describimos type
        $out->entry->type = new stdClass();
        $out->entry->type->id = $userdata["type"] == null ? 0 : (int)$userdata["type"];
        
        if($out->entry->type->id == 2){
            $out->entry->type->dsc = "Jurídica";
        }else if($out->entry->type->id == 1){
            $out->entry->type->dsc = "Natural";
        }else{
            $out->entry->type->dsc = null;
        }
        
        // Preferencias de pago de terceros
        $out->entry->paymentstothirdsparty = json_decode($userdata['paymentstothirdsparty'], true);
        
        //Describimos el nivel
        $out->entry->level = new stdClass();
        $out->entry->level->id = (int)$userdata["level"];
        $out->entry->level->dsc = "Nivel ".$out->entry->level->id;
        
        //Describimos el risklevel
        $out->entry->risklevel = new stdClass();
        $out->entry->risklevel->id = (int)$userdata["risklevel"];
        $out->entry->risklevel->dsc = "Nivel ".$out->entry->risklevel->id;
        
        $out->entry->tags = $userdata["tag"];
        
        //Termminos y condiciones
        $out->entry->terms = new stdClass();
        $out->entry->terms->value = $userdata["terms"];
        $out->entry->terms->valid = $userdata["terms"] != null ? 1 : 0;
        
        //Declaracion jurada
        $out->entry->declaration = new stdClass();
        $out->entry->declaration->value = $userdata["declaration"];
        $out->entry->declaration->valid = $userdata["declaration"] != null ? 1 : 0;
        
        //Consultamos dependiendo del tipo de usuario junto su id
        if($out->entry->type->id == 1){
            $sql = "SELECT *".
            "       FROM userpersons".
            "       WHERE usrid = ".$out->entry->id;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $userdetail = $rs->fetch_assoc();
            //Al ser usuario natural se coloca el out de company como null
            $out->entry->company = null;
        }else if($out->entry->type->id == 2){
            $sql = "SELECT *".
            "       FROM usercompanies".
            "       WHERE usrid = ".$out->entry->id;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $userdetail = $rs->fetch_assoc();
            //Al ser usuario juridico se coloca el out de person como null
            $out->entry->person = null;
        }else{
            badEnd("304", array("msg"=>"Usuario no activado"));
        }
        
        
        //Procedemos a construir la salida de datos
        if($out->entry->type->id == 1){
            $rejecteds = explode(",",$userdetail["rejected"]);
            $approveds = explode(",",$userdetail["approved"]);
            
            $out->entry->approved = $userdetail["approved"];
            $out->entry->rejected = $userdetail["rejected"];
            
            $out->entry->person = new stdClass();
    
            $out->entry->person->step = (int)$userdetail["step"];
            
            //Validamos el primer nombre de la persona
            $out->entry->person->firstname = new stdClass();
            $out->entry->person->firstname->value = $userdetail["fname"];
            $out->entry->person->firstname->valid = validateField("fname", $rejecteds, $approveds);
            $out->entry->person->firstname->update = "fname";
            
            //Validamos el segundo nombre de la persona
            $out->entry->person->secondname = new stdClass();
            $out->entry->person->secondname->value = $userdetail["sname"];
            $out->entry->person->secondname->valid = validateField("sname", $rejecteds, $approveds);
            $out->entry->person->secondname->update = "sname";
            
            //Validamos el primer apellido de la persona
            $out->entry->person->firstlastname = new stdClass();
            $out->entry->person->firstlastname->value = $userdetail["flastname"];
            $out->entry->person->firstlastname->valid = validateField("flastname", $rejecteds, $approveds);
            $out->entry->person->firstlastname->update = "flastname";
            
            //Validamos el segundo apellido de la persona
            $out->entry->person->secondlastname = new stdClass();
            $out->entry->person->secondlastname->value = $userdetail["slastname"];
            $out->entry->person->secondlastname->valid = validateField("slastname", $rejecteds, $approveds);
            $out->entry->person->secondlastname->update = "slastname";
            
            $out->entry->person->document = new stdClass();
            
            //Validamos la descripcion del documento de identidad
            $out->entry->person->document->dsc = new stdClass();
            $out->entry->person->document->dsc->value = $userdetail["doc"];
            $out->entry->person->document->dsc->valid = validateField("doc", $rejecteds, $approveds);
            $out->entry->person->document->dsc->update = "doc";
            
            //Validamos el tipo de documento de identidad
            $out->entry->person->document->type = new stdClass();
            $out->entry->person->document->type = validateDoc($userdetail["doctype"]);
            $out->entry->person->document->type->valid = validateField("doctype", $rejecteds, $approveds);
            $out->entry->person->document->type->update = "doctype";
            
            //Validamos el pais del documento de identidad
            $out->entry->person->document->country = new stdClass();
            $out->entry->person->document->country = getCountry($userdetail["doccountryid"], $db);
            $out->entry->person->document->country->valid = validateField("doccountryid", $rejecteds, $approveds);
            $out->entry->person->document->country->update = "doccountryid";
            
            //Validamos la fecha de impresion del documento de identidad
            $out->entry->person->document->datecreated = new stdClass();
            $out->entry->person->document->datecreated->date = $userdetail["docissue"] == null ? null : date("Y-m-d", strtotime($userdetail["docissue"]));
            $out->entry->person->document->datecreated->formatted = $userdetail["docissue"] == null ? null : date("d/m/Y", strtotime($userdetail["docissue"]));
            $out->entry->person->document->datecreated->valid = validateField("docissue", $rejecteds, $approveds);
            $out->entry->person->document->datecreated->update = "docissue";
            
            //Validamos la fecha de expiracion del documento de identidad
            $out->entry->person->document->dateexpiration = new stdClass();
            $out->entry->person->document->dateexpiration->date = $userdetail["docexpiry"] == null ? null : date("Y-m-d", strtotime($userdetail["docexpiry"]));
            $out->entry->person->document->dateexpiration->formatted = $userdetail["docexpiry"] == null ? null : date("d/m/Y", strtotime($userdetail["docexpiry"]));
            $out->entry->person->document->dateexpiration->valid = validateField("docexpiry", $rejecteds, $approveds);
            $out->entry->person->document->dateexpiration->update = "docexpiry";
            
            //Validamos el genero de la persona (je)
            $out->entry->person->gender = new stdClass();
            $out->entry->person->gender->value = $userdetail["gender"];
            $out->entry->person->gender->valid = validateField("gender", $rejecteds, $approveds);
            $out->entry->person->gender->update = "gender";
            
            //Validamos el estado civil de la persona (ju)
            $out->entry->person->maritalstatus = new stdClass();
            $out->entry->person->maritalstatus = validateMarital($userdetail["maritalstatus"], strtoupper($userdetail["gender"]));
            $out->entry->person->maritalstatus->valid = validateField("maritalstatus", $rejecteds, $approveds);
            $out->entry->person->maritalstatus->update = "maritalstatus";
            
            //Validamos la fecha de nacimiento de la persona
            $out->entry->person->birthdate = new stdClass();
            $out->entry->person->birthdate->date = $userdetail["birthdate"] == null ? null : date("Y-m-d", strtotime($userdetail["birthdate"]));
            $out->entry->person->birthdate->formatted = $userdetail["birthdate"] == null ? null : date("d/m/Y", strtotime($userdetail["birthdate"]));
            $out->entry->person->birthdate->valid = validateField("birthdate", $rejecteds, $approveds);
            $out->entry->person->birthdate->update = "birthdate";
            
            //Validamos el pais de nacimiento de la persona
            $out->entry->person->birthcountry = new stdClass();
            $out->entry->person->birthcountry = getCountry($userdetail["birthcountryid"], $db);
            $out->entry->person->birthcountry->valid = validateField("birthcountryid", $rejecteds, $approveds);
            $out->entry->person->birthcountry->update = "birthcountryid";
            
            //Validamos el telefono de la persona
            $out->entry->person->phone = new stdClass();
            $out->entry->person->phone->value = $userdetail["phone"];
            $out->entry->person->phone->valid = validateField("phone", $rejecteds, $approveds);
            $out->entry->person->phone->update = "phone";
            
            //Validamos el pais de residencia de la persona
            $out->entry->person->country = new stdClass();
            $out->entry->person->country = getCountry($userdetail["countryid"], $db);
            $out->entry->person->country->valid = validateField("countryid", $rejecteds, $approveds);
            $out->entry->person->country->update = "countryid";
            
            //Validamos el estado de residencia de la persona
            $out->entry->person->region = new stdClass();
            $out->entry->person->region = getRegion($userdetail["regionid"], $db);
            $out->entry->person->region->valid = validateField("regionid", $rejecteds, $approveds);
            $out->entry->person->region->update = "regionid";
            
            //Validamos la ciudad de residencia de la persona
            $out->entry->person->city = new stdClass();
            $out->entry->person->city = getCity($userdetail["cityid"], $db);
            $out->entry->person->city->valid = validateField("cityid", $rejecteds, $approveds);
            $out->entry->person->city->update = "cityid";
            
            //Validamos la calle donde reside la persona
            $out->entry->person->street = new stdClass();
            $out->entry->person->street->value = $userdetail["street"];
            $out->entry->person->street->valid = validateField("street", $rejecteds, $approveds);
            $out->entry->person->street->update = "street";
            
            //Validamos el domicilio de la persona
            $out->entry->person->home = new stdClass();
            $out->entry->person->home->value = $userdetail["domicile"];
            $out->entry->person->home->valid = validateField("domicile", $rejecteds, $approveds);
            $out->entry->person->home->update = "domicile";
            
            //Validamos el codigo postal de la persona
            $out->entry->person->postalcode = new stdClass();
            $out->entry->person->postalcode->value = $userdetail["postalcode"];
            $out->entry->person->postalcode->valid = validateField("postalcode", $rejecteds, $approveds);
            $out->entry->person->postalcode->update = "postalcode";
            
            //Validamos la profesion de la persona
            $out->entry->person->profession = new stdClass();
            $out->entry->person->profession->value = $userdetail["profession"];
            $out->entry->person->profession->valid = validateField("profession", $rejecteds, $approveds);
            $out->entry->person->profession->update = "profession";
            
            //Validamos la ocupacion de la persona
            $out->entry->person->ocupation = new stdClass();
            $out->entry->person->ocupation = getOcupation($userdetail["ocupation"], $db);
            $out->entry->person->ocupation->valid = validateField("ocupation", $rejecteds, $approveds);
            $out->entry->person->ocupation->update = "ocupation";
            
            //Validamos si la persona es politicamente expuesta
            $out->entry->person->politicalexposed = new stdClass();
            $out->entry->person->politicalexposed->value = $userdetail["politicallyexposed"] == null ? null : getDscBool($userdetail["politicallyexposed"]);
            $out->entry->person->politicalexposed->valid = validateField("politicallyexposed", $rejecteds, $approveds);
            $out->entry->person->politicalexposed->update = "politicallyexposed";
            
            //Validamos affiliationbody(????? no recuerdo que era este campo)
            $out->entry->person->affiliationbody = new stdClass();
            $out->entry->person->affiliationbody->value = $userdetail["affiliationbody"];
            $out->entry->person->affiliationbody->valid = validateField("affiliationbody", $rejecteds, $approveds);
            $out->entry->person->affiliationbody->update = "affiliationbody";
            
            //Validamos la positionheld??
            $out->entry->person->positionheld = new stdClass();
            $out->entry->person->positionheld->value = $userdetail["positionheld"];
            $out->entry->person->positionheld->valid = validateField("positionheld", $rejecteds, $approveds);
            $out->entry->person->positionheld->update = "positionheld";
            
            //Validamos el pais de la pep
            $out->entry->person->pepcountryid = new stdClass();
            $out->entry->person->pepcountryid = getCountry($userdetail["pepcountryid"], $db);
            $out->entry->person->pepcountryid->valid = validateField("pepcountryid", $rejecteds, $approveds);
            $out->entry->person->pepcountryid->update = "pepcountryid";
            
            //Validamos la identificacion del pep
            $out->entry->person->peprelatedid = new stdClass();
            $out->entry->person->peprelatedid->value = $userdetail["peprelatedid"];
            $out->entry->person->peprelatedid->valid = validateField("peprelatedid", $rejecteds, $approveds);
            $out->entry->person->peprelatedid->update = "peprelatedid";
            
            //Validamos si es un comerciante independiente
            $out->entry->person->independentdealer = new stdClass();
            $out->entry->person->independentdealer->value = $userdetail["independentdealer"] == null ? null : getDscBool($userdetail["independentdealer"]);
            $out->entry->person->independentdealer->valid = validateField("independentdealer", $rejecteds, $approveds);
            $out->entry->person->independentdealer->update = "independentdealer";
            
            //Validamos la compania en la que trabaja
            $out->entry->person->company = new stdClass();
            $out->entry->person->company->value = $userdetail["company"];
            $out->entry->person->company->valid = validateField("company", $rejecteds, $approveds);
            $out->entry->person->company->update = "company";
            
            //Validamos el ingreso anual de la persona
            $out->entry->person->anualincome = new stdClass();
            $out->entry->person->anualincome->number = $userdetail["anualincome"] == null ? null : (float)$userdetail["anualincome"];
            $out->entry->person->anualincome->formatted = $userdetail["anualincome"] == null ? null : number_format($out->entry->person->anualincome->number,2,",",".");
            $out->entry->person->anualincome->valid = validateField("anualincome", $rejecteds, $approveds);
            $out->entry->person->anualincome->update = "anualincome";
            
            //Validamos el patrimonio de la persona
            $out->entry->person->patrimony = new stdClass();
            $out->entry->person->patrimony->number = $userdetail["patrimony"] == null ? null : (float)$userdetail["patrimony"];
            $out->entry->person->patrimony->formatted = $userdetail["patrimony"] == null ? null : number_format($out->entry->person->patrimony->number,2,",",".");
            $out->entry->person->patrimony->valid = validateField("patrimony", $rejecteds, $approveds);
            $out->entry->person->patrimony->update = "patrimony";
            
            //Validamos la actividad economica de la persona
            $out->entry->person->economicalactivity = new stdClass();
            $out->entry->person->economicalactivity = getEconomicActs($userdetail["economicactivity"],$db);
            $out->entry->person->economicalactivity->valid = validateField("economicactivity", $rejecteds, $approveds);
            $out->entry->person->economicalactivity->update = "economicactivity";
            
            //Validamos la cantidad de operaciones que realiza al mes
            $out->entry->person->qtyoperationsmothly = new stdClass();
            $out->entry->person->qtyoperationsmothly->value = $userdetail["qtymonthlyop"];
            $out->entry->person->qtyoperationsmothly->valid = validateField("qtymonthlyop", $rejecteds, $approveds);
            $out->entry->person->qtyoperationsmothly->update = "qtymonthlyop";
            
            //Validamos el monto al mes de la persona
            $out->entry->person->amooperationsmonthly = new stdClass();
            $out->entry->person->amooperationsmonthly->number = $userdetail["amountmonthlyop"];
            //$out->entry->person->amooperationsmonthly->formatted = number_format($userdetail["amountmonthlyop"],2,",",".");
            $out->entry->person->amooperationsmonthly->valid = validateField("amountmonthlyop", $rejecteds, $approveds);
            $out->entry->person->amooperationsmonthly->update = "amountmonthlyop";
            
            //Validamos la operacion de preferencia del usuario
            $out->entry->person->preferoptype = new stdClass();
            $out->entry->person->preferoptype->id = $userdetail["prefertypeop"] == null ? null : $userdetail["prefertypeop"];
            $out->entry->person->preferoptype->dsc = "";
            $out->entry->person->preferoptype->valid = validateField("prefertypeop", $rejecteds, $approveds);
            $out->entry->person->preferoptype->update = "prefertypeop";
            
            //Validamos si tiene relaciones economicas
            $out->entry->person->economicrelation = new stdClass();
            $out->entry->person->economicrelation->value = $userdetail["economicrelation"] == null ? null : getDscBool($userdetail["economicrelation"]);
            $out->entry->person->economicrelation->valid = validateField("economicrelation", $rejecteds, $approveds);
            $out->entry->person->economicrelation->update = "economicrelation";
            
            //Validamos si es americano
            $out->entry->person->american = new stdClass();
            $out->entry->person->american->value = $userdetail["american"] != null ? getDscBool($userdetail["american"]) : null;
            $out->entry->person->american->valid = validateField("american", $rejecteds, $approveds);
            $out->entry->person->american->update = "american";
            
            //Validamos si es venezolano
            $out->entry->person->venezuelan = new stdClass();
            $out->entry->person->venezuelan->value = $userdetail["venezuelan"] != null ? getDscBool($userdetail["venezuelan"]) : null;
            $out->entry->person->venezuelan->valid = validateField("venezuelan", $rejecteds, $approveds);
            $out->entry->person->venezuelan->update = "venezuelan";
            
            //Consultamos los datos de cada tipo de documento
            $sql = "SELECT * FROM cmsprefuploads".
            "       WHERE type LIKE '%".$out->entry->type->id."%'";
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                    
            while($uploadarr = $rs->fetch_assoc()){
                $upload = new stdClass();
                //Generamos el id de salida
                $upload->id = str_pad($uploadarr["id"], 2, "0", STR_PAD_LEFT);
                $upload->dsc = $uploadarr["dsc"];
                
                //Consultamos para saber si el usuario posee el documento
                $sql = "SELECT count(userid) AS qty FROM useruploads".
                "       WHERE userid = ".$out->entry->id.
                "       AND prefuploadid = ".$uploadarr["id"];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $uploaddetailqty = $res->fetch_assoc();
                
                if($uploaddetailqty["qty"] > 0){
                    //Consultamos para saber si el usuario posee el documento
                    $sql = "SELECT * FROM useruploads".
                    "       WHERE userid = ".$out->entry->id.
                    "       AND prefuploadid = ".$uploadarr["id"];
                    if (!$res=$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                    
                    $uploaddetail = $res->fetch_assoc();
                
                    //Buscamos el archivo para obtener su nombre y extension
                    $filestest = glob("../../../uploads/users/".$out->entry->id."/".$upload->id.".{jpg,png,jpeg,pdf,PNG,JPG,JPEG,PDF}", GLOB_BRACE);
                
                    //El primer resultado
                    $info = pathinfo($filestest[0]);
                    $upload->type = ".".pathinfo($filestest[0], PATHINFO_EXTENSION);
                    ///$out->files [] = $info;
                    if($info['basename'] == ""){
                        $upload->url = "";
                        $upload->validated = 0;
                    }else{
                        //Url dentro de la carpeta api
                        //$upload->url = $uploadsURL."users/".$out->entry->id."/".$info["basename"];
                        $upload->url = $uploadsURLcms."?upid=". $upload->id."&sessionid=".$sessionid."&usrid=".$out->entry->id;
                        $upload->validated = (int)$uploaddetail["validated"];
                    }
                }else{
                    $upload->url = "";
                    $upload->validated = 0;
                }
                
                $upload->level = new stdClass();
                
                //Consultamos los datos del nivel
                $sql = "SELECT * FROM levels";
                if (!$resUp=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                
                while($levelsTemp = $resUp->fetch_assoc()){
                    
                    $levelsarrTemp = explode("-",$levelsTemp["cmsprefuploads"]);
                    foreach($levelsarrTemp as $whichlevel){
                        if($uploadarr["id"] == $whichlevel){
                            $upload->level->id = (int)$levelsTemp["orden"];
                            $upload->level->dsc = "Nivel ".$upload->level->id;
                        }
                    }
                    
                }
                
                $arrRequiresUp = explode("-",$levels["cmsprefuploads"]);
                $upload->required = validateUpload($uploadarr["prefuploadid"],$arrRequiresUp);
                
                $uploads[] = $upload;
            }
            
            $out->entry->person->uploads = $uploads;
        }else if($out->entry->type->id == 2){
            $rejecteds = explode(",",$userdetail["rejected"]);
            $approveds = explode(",",$userdetail["approved"]);
            
            $out->entry->approved = $userdetail["approved"];
            $out->entry->rejected = $userdetail["rejected"];
            
            $out->entry->company = new stdClass();
            
            $out->entry->company->step = (int)$userdetail["step"];
            
            //Validamos el nombre de la empresa
            $out->entry->company->name = new stdClass();
            $out->entry->company->name->value = $userdetail["name"];
            $out->entry->company->name->valid = validateField("name", $rejecteds, $approveds);
            $out->entry->company->name->update = "name";
            
            //Validamos el nombre comercial de la empresa
            $out->entry->company->comercialname = new stdClass();
            $out->entry->company->comercialname->value = $userdetail["comercialname"];
            $out->entry->company->comercialname->valid = validateField("comercialname", $rejecteds, $approveds);
            $out->entry->company->comercialname->update = "comercialname";
            
            //Validamos la fecha de creacion de la empresa
            $out->entry->company->datecreated = new stdClass();
            $out->entry->company->datecreated->date = $userdetail["creationdate"] == null ? null : date("Y-m-d", strtotime($userdetail["creationdate"]));
            $out->entry->company->datecreated->formatted = $userdetail["creationdate"] == null ? null : date("d/m/Y", strtotime($userdetail["creationdate"]));
            $out->entry->company->datecreated->valid = validateField("creationdate", $rejecteds, $approveds);
            $out->entry->company->datecreated->update = "creationdate";
            
            //Validamos la descripcion del documento de identificacion
            $out->entry->company->document = new stdClass();
            $out->entry->company->document->dsc = new stdClass();
            $out->entry->company->document->dsc->value = $userdetail["doc"];
            $out->entry->company->document->dsc->valid = validateField("doc", $rejecteds, $approveds);
            $out->entry->company->document->dsc->update = "doc";
            
            //Validamos el pais del documento de identificacion
            $out->entry->company->document->country = new stdClass();
            $out->entry->company->document->country = getCountry($userdetail["doccountryid"], $db);
            $out->entry->company->document->country->valid = validateField("doccountryid", $rejecteds, $approveds);
            $out->entry->company->document->country->update = "doccountryid";
            
            //Validamos el estado del documento de identificacion
            $out->entry->company->document->region = new stdClass();
            $out->entry->company->document->region = getRegion($userdetail["docregionid"], $db);
            $out->entry->company->document->region->valid = validateField("docregionid", $rejecteds, $approveds);
            $out->entry->company->document->region->update = "docregionid";
            
            //Validamos la ciudad del documento de identificacion
            $out->entry->company->document->city = new stdClass();
            $out->entry->company->document->city = getCity($userdetail["doccityid"], $db);
            $out->entry->company->document->city->valid = validateField("doccityid", $rejecteds, $approveds);
            $out->entry->company->document->city->update = "doccityid";
            
            //Validamos el codigo postal del documento de identificacion
            $out->entry->company->document->postalcode = new stdClass();
            $out->entry->company->document->postalcode->value = $userdetail["postalcode"];
            $out->entry->company->document->postalcode->valid = validateField("postalcode", $rejecteds, $approveds);
            $out->entry->company->document->postalcode->update = "postalcode";
            
            //Validamos el tipo de empresa
            $out->entry->company->type = new stdClass();
            $out->entry->company->type = getCompanyType($userdetail["ctype"]);
            $out->entry->company->type->valid = validateField("ctype", $rejecteds, $approveds);
            $out->entry->company->type->update = "ctype";
            
            //Validamos la pagina web de la empresa
            $out->entry->company->website = new stdClass();
            $out->entry->company->website->value = $userdetail["website"];
            $out->entry->company->website->valid = validateField("website", $rejecteds, $approveds);
            $out->entry->company->website->update = "website";
            
            //Validamos la cantidad de oficinas de la empresa
            $out->entry->company->branchoffices = new stdClass();
            $out->entry->company->branchoffices->value = $userdetail["branchoffices"] == null ? null : (int)$userdetail["branchoffices"];
            $out->entry->company->branchoffices->valid = validateField("branchoffices", $rejecteds, $approveds);
            $out->entry->company->branchoffices->update = "branchoffices";
            
            //Validamos la cantidad de socios
            $out->entry->company->partnersnumber = new stdClass();
            $out->entry->company->partnersnumber->value = (int)$userdetail["partners"];
            $out->entry->company->partnersnumber->valid = validateField("partners", $rejecteds, $approveds);
            $out->entry->company->partnersnumber->update = "partners";
            
            //Validamos si la empresa es venezolana
            $out->entry->company->venezuelan = new stdClass();
            $out->entry->company->venezuelan->value = $userdetail["venezuelan"] == null ? null : getDscBool($userdetail["venezuelan"]);
            $out->entry->company->venezuelan->valid = validateField("venezuelan", $rejecteds, $approveds);
            $out->entry->company->venezuelan->update = "venezuelan";
    
            //##NEW
            $out->entry->company->reppartner = new stdClass();
            $out->entry->company->reppartner->value = $userdetail["reppartner"] == null ? null : getDscBool($userdetail["reppartner"]);
            $out->entry->company->reppartner->valid = validateField("reppartner", $rejecteds, $approveds);
            $out->entry->company->reppartner->update = "reppartner";
            
            //Consulta para obtener socios
            $sql = "SELECT * FROM usercompanypartners".
            "       WHERE companyid = ".$out->entry->id;
            if (!$partnerrow=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            while($partnerdata = $partnerrow->fetch_assoc()){
                $partnerrejecteds = explode(",",$partnerdata["rejected"]);
                $partnerapproveds = explode(",",$partnerdata["approved"]);
            
                $partner = new stdClass();
                $partner->id = (int)$partnerdata["id"];
                
                $partner->name = new stdClass();
                $partner->name->value = $partnerdata["name"];
                $partner->name->valid = validateField("name", $partnerrejecteds, $partnerapproveds);
                $partner->name->update = "name";
                
                $partner->document = new stdClass();
                $partner->document->value = $partnerdata["doc"];
                $partner->document->valid = validateField("doc", $partnerrejecteds, $partnerapproveds);
                $partner->document->update = "doc";
                
                $partner->phone = new stdClass();
                $partner->phone->value = $partnerdata["phone"];
                $partner->phone->valid = validateField("phone", $partnerrejecteds, $partnerapproveds);
                $partner->phone->update = "phone";
                
                $partner->legalrep = new stdClass();
                $partner->legalrep->value = (int)$partnerdata["legalrep"];
                $partner->legalrep->valid = validateField("legalrep", $partnerrejecteds, $partnerapproveds);
                $partner->legalrep->update = "legalrep";
                
                $partner->politicalexposed = new stdClass();
                $partner->politicalexposed->value = $partnerdata["politicallyexposed"] == null ? null : getDscBool($partnerdata["politicallyexposed"]);
                $partner->politicalexposed->valid = validateField("politicallyexposed", $partnerrejecteds, $partnerapproveds);
                $partner->politicalexposed->update = "politicallyexposed";
                
                $partner->affiliationbody = new stdClass();
                $partner->affiliationbody->value = $partnerdata["affiliationbody"];
                $partner->affiliationbody->valid = validateField("affiliationbody", $partnerrejecteds, $partnerapproveds);
                $partner->affiliationbody->update = "affiliationbody";
                
                $partner->positionheld = new stdClass();
                $partner->positionheld->value = $partnerdata["positionheld"];
                $partner->positionheld->valid = validateField("positionheld", $partnerrejecteds, $partnerapproveds);
                $partner->positionheld->update = "positionheld";
                
                $partner->pepcountryid = new stdClass();
                $partner->pepcountryid = getCountry($partnerdata["pepcountryid"], $db);
                $partner->pepcountryid->valid = validateField("pepcountryid", $partnerrejecteds, $partnerapproveds);
                $partner->pepcountryid->update = "pepcountryid";
                
                $partner->peprelatedid = new stdClass();
                $partner->peprelatedid->value = $partnerdata["peprelatedid"];
                $partner->peprelatedid->valid = validateField("peprelatedid", $partnerrejecteds, $partnerapproveds);
                $partner->peprelatedid->update = "peprelatedid";
                
                $partners[] = $partner;
            }
            
            $out->entry->company->partners = $partners;
            
            //Validamos el numero de teleono de la empresa
            $out->entry->company->phone = new stdClass();
            $out->entry->company->phone->value = $userdetail["phone"];
            $out->entry->company->phone->valid = validateField("phone", $rejecteds, $approveds);
            $out->entry->company->phone->update = "phone";
            
            //Valida el pais base de la empresa
            $out->entry->company->country = new stdClass();
            $out->entry->company->country = getCountry($userdetail["countryid"], $db);
            $out->entry->company->country->valid = validateField("countryid", $rejecteds, $approveds);
            $out->entry->company->country->update = "countryid";
            
            //Validamos la region base de la empresa
            $out->entry->company->region = new stdClass();
            $out->entry->company->region = getRegion($userdetail["regionid"], $db);
            $out->entry->company->region->valid = validateField("regionid", $rejecteds, $approveds);
            $out->entry->company->region->update = "regionid";
            
            //Validamos la ciudad base de la empresa
            $out->entry->company->city = new stdClass();
            $out->entry->company->city = getCity($userdetail["cityid"], $db);
            $out->entry->company->city->valid = validateField("cityid", $rejecteds, $approveds);
            $out->entry->company->city->update = "cityid";
            
            //Validamos la calle de la empresa
            $out->entry->company->street = new stdClass();
            $out->entry->company->street->value = $userdetail["street"];
            $out->entry->company->street->valid = validateField("street", $rejecteds, $approveds);
            $out->entry->company->street->update = "street";
            
            //Validamos el sitio de la empresa
            $out->entry->company->home = new stdClass();
            $out->entry->company->home->value = $userdetail["domicile"];
            $out->entry->company->home->valid = validateField("domicile", $rejecteds, $approveds);
            $out->entry->company->home->update = "domicile";
            
            //Validamos si es un comerciante independiente
            $out->entry->company->independentdealer = new stdClass();
            $out->entry->company->independentdealer->value = $userdetail["independentdealer"] == null ? null : (int)$userdetail["independentdealer"];
            $out->entry->company->independentdealer->valid = validateField("independentdealer", $rejecteds, $approveds);
            $out->entry->company->independentdealer->update = "independentdealer";
            
            //Validamos si se encuentras politicamente expuestos
            $out->entry->company->politicalexposed = new stdClass();
            $out->entry->company->politicalexposed->value = $userdetail["politicallyexposed"] == null ? null : getDscBool($userdetail["politicallyexposed"]);
            $out->entry->company->politicalexposed->valid = validateField("politicallyexposed", $rejecteds, $approveds);
            $out->entry->company->politicalexposed->update = "politicallyexposed";
            
            //Por que todos los campos tienen que validarse:(
            
            //Validamos el ingreso anual de la empresa
            $out->entry->company->anualincome = new stdClass();
            $out->entry->company->anualincome->number = $userdetail["anualincome"] == null ? null : (float)$userdetail["anualincome"];
            $out->entry->company->anualincome->formatted = $userdetail["anualincome"] == null ? null : number_format($out->entry->company->anualincome->number,2,",",".");
            $out->entry->company->anualincome->valid = validateField("anualincome", $rejecteds, $approveds);
            $out->entry->company->anualincome->update = "anualincome";
            
            //Validamos el patrimonio de la empresa
            $out->entry->company->patrimony = new stdClass();
            $out->entry->company->patrimony->number = $userdetail["patrimony"] == null ? null : (float)$userdetail["patrimony"];
            $out->entry->company->patrimony->formatted = $userdetail["patrimony"] == null ? null : number_format($out->entry->company->patrimony->number,2,",",".");
            $out->entry->company->patrimony->valid = validateField("patrimony", $rejecteds, $approveds);
            $out->entry->company->patrimony->update = "patrimony";
            
            //Validamos la actividad economica
            $out->entry->company->economicalactivity = new stdClass();
            $out->entry->company->economicalactivity = getEconomicActs($userdetail["economicactivity"],$db);
            $out->entry->company->economicalactivity->valid = validateField("economicactivity", $rejecteds, $approveds);
            $out->entry->company->economicalactivity->update = "economicactivity";
            
            //Validamos la cantidad de operaciones mensuales
            $out->entry->company->qtyoperationsmothly = new stdClass();
            $out->entry->company->qtyoperationsmothly->value = $userdetail["qtymonthlyop"];
            $out->entry->company->qtyoperationsmothly->valid = validateField("qtymonthlyop", $rejecteds, $approveds);
            $out->entry->company->qtyoperationsmothly->update = "qtymonthlyop";
            
            //Validamos el monto por operaciones mensuales
            $out->entry->company->amooperationsmonthly = new stdClass();
            $out->entry->company->amooperationsmonthly->number = $userdetail["amountmontlyop"];
            $out->entry->company->amooperationsmonthly->valid = validateField("amountmontlyop", $rejecteds, $approveds);
            $out->entry->company->amooperationsmonthly->update = "amountmontlyop";
            //$out->entry->company->amooperationsmonthly->formatted = number_format($out->entry->company->amooperationsmonthly->number,2,",",".");
            
            //Validamos el tipo de operacion preferida
            $out->entry->company->preferoptype = new stdClass();
            $out->entry->company->preferoptype->id = $userdetail["prefertypeop"] == null ? null : $userdetail["prefertypeop"];
            $out->entry->company->preferoptype->dsc = "";
            $out->entry->company->preferoptype->valid = validateField("prefertypeop", $rejecteds, $approveds);
            $out->entry->company->preferoptype->update = "prefertypeop";
            
            //Validamos si tiene relaciones economicas
            $out->entry->company->economicrelation = new stdClass();
            $out->entry->company->economicrelation->value =  $userdetail["economicrelation"] == null ? null : getDscBool($userdetail["economicrelation"]);
            $out->entry->company->economicrelation->valid = validateField("economicrelation", $rejecteds, $approveds);
            $out->entry->company->economicrelation->update = "economicrelation";
            
            //Consultamos los datos de cada tipo de documento
            $sql = "SELECT * FROM cmsprefuploads".
            "       WHERE type LIKE '%".$out->entry->type->id."%'";
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                    
            while($uploadarr = $rs->fetch_assoc()){
                $upload = new stdClass();
                //Generamos el id de salida
                $upload->id = str_pad($uploadarr["id"], 2, "0", STR_PAD_LEFT);
                $upload->dsc = $uploadarr["dsc"];
                
                //Consultamos para saber si el usuario posee el documento
                $sql = "SELECT count(userid) AS qty FROM useruploads".
                "       WHERE userid = ".$out->entry->id.
                "       AND prefuploadid = ".$uploadarr["id"];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $uploaddetailqty = $res->fetch_assoc();
                
                if($uploaddetailqty["qty"] > 0){
                    //Consultamos para saber si el usuario posee el documento
                    $sql = "SELECT * FROM useruploads".
                    "       WHERE userid = ".$out->entry->id.
                    "       AND prefuploadid = ".$uploadarr["id"];
                    if (!$res=$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                    
                    $uploaddetail = $res->fetch_assoc();
                
                    //Buscamos el archivo para obtener su nombre y extension
                    $filestest = glob("../../../uploads/users/".$out->entry->id."/".$upload->id.".{jpg,png,jpeg,pdf,PNG,JPG,JPEG,PDF}", GLOB_BRACE);
                
                    //El primer resultado
                    $info = pathinfo($filestest[0]);
                    $upload->type = ".".pathinfo($filestest[0], PATHINFO_EXTENSION);
                    ///$out->files [] = $info;
                    if($info['basename'] == ""){
                        $upload->url = "";
                        $upload->validated = 0;
                    }else{
                        //Url dentro de la carpeta api
                        //$upload->url = $uploadsURL."users/".$out->entry->id."/".$info["basename"];
                        $upload->url = $uploadsURLcms."?upid=". $upload->id."&sessionid=".$sessionid."&usrid=".$out->entry->id;
                        $upload->validated = (int)$uploaddetail["validated"];
                    }
                }else{
                    $upload->url = "";
                    $upload->validated = 0;
                }
                
                $upload->level = new stdClass();
                
                //Consultamos los datos del nivel
                $sql = "SELECT * FROM levels";
                if (!$resUp=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                
                while($levelsTemp = $resUp->fetch_assoc()){
                    
                    $levelsarrTemp = explode("-",$levelsTemp["cmsprefuploads"]);
                    foreach($levelsarrTemp as $whichlevel){
                        if($uploadarr["id"] == $whichlevel){
                            $upload->level->id = (int)$levelsTemp["orden"];
                            $upload->level->dsc = "Nivel ".$upload->level->id;
                        }
                    }
                    
                }
                
                $arrRequiresUp = explode("-",$levels["cmsprefuploads"]);
                $upload->required = validateUpload($uploadarr["prefuploadid"],$arrRequiresUp);
                
                $uploads[] = $upload;
            }
            
            $out->entry->company->uploads = $uploads;
        }
        
        //Consultamos las cuentas que posee el usuario
        $sql = "SELECT accounts.id AS accountid, ".
        "       accounts.details1 AS accountdetail1, ".
        "       accounts.details2 AS accountdetail2, ".
        "       accounts.details3 AS accountdetail3, ".
        "       accounts.details4 AS accountdetail4, ".
        "       accounts.currencyid AS currencyid, ".
        "       accounts.status AS accountstatus, ".
        "       accounts.paymentmethodid AS accountpaymentmethod, ".
        "       accounts.rejected AS accountrejected, ".
        "       accounts.approved AS accountapproved, ".
        "       currencies.name AS currencyname, ".
        "       currencies.symbol AS currencysymbol, ".
        "       paymentmethods.dsc AS paymentmethodname, ".
        "       paymentmethods.details1 AS paymentmethoddetail1, ".
        "       paymentmethods.details2 AS paymentmethoddetail2, ".
        "       paymentmethods.details3 AS paymentmethoddetail3, ".
        "       paymentmethods.details4 AS paymentmethoddetail4 ".
        "       FROM accounts, currencies, paymentmethods ".
        "       WHERE accounts.currencyid = currencies.id ".
        "       AND paymentmethods.id = accounts.paymentmethodid ".
        "       AND paymentmethods.id > 0 ".
        "       AND accounts.userid = ".$id ;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        //Ordenamos los datos de las cuentas
        while($row = $rs->fetch_assoc()){
            $account = new stdClass();
            $account->id = (int)$row["accountid"];
            
            $account->status = new stdClass();
            $account->status->id = (int)$row["accountstatus"];
            $account->status->dsc = $account->status->id == 0 ? "Inactivo" : "Activo";
            
            $account->currency = new stdClass();
            $account->currency->id = (int)$row["currencyid"];
            $account->currency->name = $row["currencyname"];
            $account->currency->symbol = $row["currencysymbol"];
            //$account->valid = (int)$row["accountvalid"];
            
            $account->paymentmethod = new stdClass();
            $account->paymentmethod->id = (int)$row["accountpaymentmethod"];
            $account->paymentmethod->name = $row["paymentmethodname"];
            $account->paymentmethod->details1 = $row["paymentmethoddetail1"];
            $account->paymentmethod->details2 = $row["paymentmethoddetail2"];
            $account->paymentmethod->details3 = $row["paymentmethoddetail3"];
            $account->paymentmethod->details4 = $row["paymentmethoddetail4"];
            
            $cant = 0;
            if($row["paymentmethoddetails1"] !== null)$cant = $cant + 1;
            if($row["paymentmethoddetails2"] !== null)$cant = $cant + 1;
            if($row["paymentmethoddetails3"] !== null)$cant = $cant + 1;
            if($row["paymentmethoddetails4"] !== null)$cant = $cant + 1;
            
            if($row["accountrejected"] != null){
                $account->valid = -1;
            }else if($row["accountapproved"] != null && $row["accountrejected"] == null && $cant==count(explode(",", $row["accountapproved"]))){
                $account->valid = 1;
            }else{
                $account->valid = 0;
            }
            
            $rejecteddetails = explode(",", $row["accountrejected"]);
            $approveddetails = explode(",", $row["accountapproved"]);
            
            $account->details1 = new stdClass();
            $account->details1->valid = validateField("details1", $rejecteddetails, $approveddetails);
            $account->details1->value = $row["accountdetail1"];
            
            $account->details2 = new stdClass();
            $account->details2->valid = validateField("details2", $rejecteddetails, $approveddetails);;
            $account->details2->value = $row["accountdetail2"];
            
            $account->details3 = new stdClass();
            $account->details3->valid = validateField("details3", $rejecteddetails, $approveddetails);;
            $account->details3->value = $row["accountdetail3"];
            
            $account->details4 = new stdClass();
            $account->details4->valid = validateField("details4", $rejecteddetails, $approveddetails);;
            $account->details4->value = $row["accountdetail4"];
            
            $accounts [] = $account;
        }
        
        $out->entry->accounts = $accounts;
        
        //Cargamos los datos de cada nivel
        $sql = "SELECT * FROM levels";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        while($leveldata = $rs->fetch_assoc()){
            $levelfield = new stdClass();
            
            $levelfield->level = (float)$leveldata["orden"];
            $levelfield->partnerfields = $leveldata["usercompanypartners"];
            
            if($out->entry->type->id == 1){
                $levelfield->typefields = $leveldata["userpersons"];
            }else if($out->entry->type->id == 2){
                $levelfield->typefields = $leveldata["usercompanies"];
            }
            
            $sql = "SELECT * FROM cmsprefuploads".
            "       WHERE type LIKE '%".$out->entry->type->id."%'";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $uploadsrequired = "";
            while($cmsuploads = $res->fetch_assoc()){
                $uploadsrequired .= $cmsuploads["id"]."-";
            }
            
            $uploadsrequired = substr($uploadsrequired, 0, -1);
            $uploadsrequired = explode("-",$uploadsrequired);
            $uploadsforlevel = explode("-",$leveldata["cmsprefuploads"]);
            
            $uploadId = "";
            
            foreach($uploadsrequired as $uploadrequired){
                foreach($uploadsforlevel as $uploadforlevel){
                if(!empty($uploadforlevel)){
                    if($uploadrequired == $uploadforlevel){
                        $uploadId .= $uploadforlevel."-";
                    }    
                }
            }
            }
            
            
            $levelfield->uploadsId = $uploadId == "" ? $uploadId : substr($uploadId, 0, -1);
            
            $levelfields [] = $levelfield;
        }
        
        $out->entry->levelfields = $levelfields;  
    } else {
        $out->entry = null;
    }
    
    // Validamos si puede ver sus exonerados del portfolio
    if (tienePrivilegio($db, $sessionid, 96)) {
        $out->currencies = new stdClass();
        $currs = [];
        
        $sql = "SELECT *".
        "       FROM users".
        "       WHERE id = ".mysqli_real_escape_string($db, $id);
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
                
        $userdata = $rs->fetch_assoc();
        
        // Consultamos todas las monedas activas
        $sql = "SELECT * FROM currencies ".
        "       WHERE id > 0 ".
        "       AND status = 1";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        while($row = $rs->fetch_assoc()){
            $currency = new stdClass();
            
            $currency->id = (int)$row['id'];
            $currency->name = $row['name'];
            $currency->symbol = $row['symbol'];
            
            //Consultamos las comisiones con los datos del usuario
            $sql = "SELECT * FROM cmspreffees ".
            "       WHERE levelid = ".($userdata['level'] == 0 ? 1 : $userdata['level']).
            "       AND currencyid = ".$row['id'].
            "       AND usertype = ".$userdata["type"];
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                    
            $feedata = $res->fetch_assoc();
            
            $currency->fees = new stdClass();
            
            //Comisiones para depositos
            $currency->fees->deposits = new stdClass();
            
            if($feedata["pctfeedeposits"] == 0){
                $currency->fees->deposits->pctfee = null;
                
                $currency->fees->deposits->nmalfee = new stdClass();
                $currency->fees->deposits->nmalfee->field = "nmlfeedeposits";
                $currency->fees->deposits->nmalfee->number = (float)number_format($feedata["nmlfeedeposits"],$row['decimals'],'.','');
                $currency->fees->deposits->nmalfee->formatted = numberFormatt($feedata["nmlfeedeposits"],$row['decimals']);
                
                // Obtenemos este detalle si existe
                $sql = "SELECT * FROM userportfolioprefs ".
                "       WHERE userid = ".$userdata['id'].
                "       AND preffeesfield = 'nmlfeedeposits'".
                "       AND currencyid = ".$row['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $prefRow = $res->fetch_assoc();
                
                if ($prefRow['currencyid'] != null) {
                    $currency->fees->deposits->nmalfee->exonerated = new stdClass();
                    $currency->fees->deposits->nmalfee->exonerated->number = (float)number_format($prefRow["exonerated"], 2,'.','');
                    $currency->fees->deposits->nmalfee->exonerated->formatted = numberFormatt($prefRow["exonerated"], 2);
                } else {
                    $currency->fees->deposits->nmalfee->exonerated = null;
                }
                
            }else{
                $currency->fees->deposits->pctfee = new stdClass();
                $currency->fees->deposits->pctfee->field = "pctfeedeposits";
                $currency->fees->deposits->pctfee->number = (float)number_format($feedata["pctfeedeposits"], 2,'.','');
                $currency->fees->deposits->pctfee->formatted = number_format($feedata["pctfeedeposits"],2,",",".");
                
                // Obtenemos este detalle si existe
                $sql = "SELECT * FROM userportfolioprefs ".
                "       WHERE userid = ".$userdata['id'].
                "       AND preffeesfield = 'pctfeedeposits'".
                "       AND currencyid = ".$row['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $prefRow = $res->fetch_assoc();
                
                if ($prefRow['currencyid'] != null) {
                    $currency->fees->deposits->pctfee->exonerated = new stdClass();
                    $currency->fees->deposits->pctfee->exonerated->number = (float)number_format($prefRow["exonerated"], 2,'.','');
                    $currency->fees->deposits->pctfee->exonerated->formatted = numberFormatt($prefRow["exonerated"], 2);
                } else {
                    $currency->fees->deposits->pctfee->exonerated = null;
                }
                
                $currency->fees->deposits->nmalfee = null;
            }
            
            
            //Comisiones para retiros
            $currency->fees->withdrawals = new stdClass();
            
            if($feedata["pctfeewithdrawals"] == 0){
                $currency->fees->withdrawals->pctfee = null;
                
                $currency->fees->withdrawals->nmalfee = new stdClass();
                $currency->fees->withdrawals->nmalfee->field = "nmlfeewithdrawals";
                $currency->fees->withdrawals->nmalfee->number = (float)number_format($feedata["nmlfeewithdrawals"], $row['decimals'],'.','');
                $currency->fees->withdrawals->nmalfee->formatted = numberFormatt($feedata["nmlfeewithdrawals"],$row['decimals']);
                
                // Obtenemos este detalle si existe
                $sql = "SELECT * FROM userportfolioprefs ".
                "       WHERE userid = ".$userdata['id'].
                "       AND preffeesfield = 'nmlfeewithdrawals'".
                "       AND currencyid = ".$row['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $prefRow = $res->fetch_assoc();
                
                if ($prefRow['currencyid'] != null) {
                    $currency->fees->withdrawals->nmalfee->exonerated = new stdClass();
                    $currency->fees->withdrawals->nmalfee->exonerated->number = (float)number_format($prefRow["exonerated"], 2,'.','');
                    $currency->fees->withdrawals->nmalfee->exonerated->formatted = numberFormatt($prefRow["exonerated"], 2);
                } else {
                    $currency->fees->withdrawals->nmalfee->exonerated = null;
                }
            
            }else{
                $currency->fees->withdrawals->pctfee = new stdClass();
                $currency->fees->withdrawals->pctfee->field = "pctfeewithdrawals";
                $currency->fees->withdrawals->pctfee->number = (float)number_format($feedata["pctfeewithdrawals"], 2,'.','');
                $currency->fees->withdrawals->pctfee->formatted = number_format($feedata["pctfeewithdrawals"],2,",",".");
                
                // Obtenemos este detalle si existe
                $sql = "SELECT * FROM userportfolioprefs ".
                "       WHERE userid = ".$userdata['id'].
                "       AND preffeesfield = 'pctfeewithdrawals'".
                "       AND currencyid = ".$row['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $prefRow = $res->fetch_assoc();
                
                if ($prefRow['currencyid'] != null) {
                    $currency->fees->withdrawals->pctfee->exonerated = new stdClass();
                    $currency->fees->withdrawals->pctfee->exonerated->number = (float)number_format($prefRow["exonerated"], 2,'.','');
                    $currency->fees->withdrawals->pctfee->exonerated->formatted = numberFormatt($prefRow["exonerated"], 2);
                } else {
                    $currency->fees->withdrawals->pctfee->exonerated = null;
                }
                
                $currency->fees->withdrawals->nmalfee = null;
            }
            
            //Comisiones para retiros
            $currency->fees->xfer = new stdClass();
            
            if($feedata["pctfeexfer"] == 0){
                $currency->fees->xfer->pctfee = null;
                
                $currency->fees->xfer->nmalfee = new stdClass();
                $currency->fees->xfer->nmalfee->field = "nmlfeesxfer";
                $currency->fees->xfer->nmalfee->number = (float) number_format($feedata["nmlfeesxfer"], $row['decimals'],'.','');
                $currency->fees->xfer->nmalfee->formatted = numberFormatt($feedata["nmlfeesxfer"],$row['decimals']);
                
                // Obtenemos este detalle si existe
                $sql = "SELECT * FROM userportfolioprefs ".
                "       WHERE userid = ".$userdata['id'].
                "       AND preffeesfield = 'nmlfeesxfer'".
                "       AND currencyid = ".$row['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $prefRow = $res->fetch_assoc();
                
                if ($prefRow['currencyid'] != null) {
                    $currency->fees->xfer->nmalfee->exonerated = new stdClass();
                    $currency->fees->xfer->nmalfee->exonerated->number = (float)number_format($prefRow["exonerated"], 2,'.','');
                    $currency->fees->xfer->nmalfee->exonerated->formatted = numberFormatt($prefRow["exonerated"], 2);
                } else {
                    $currency->fees->xfer->nmalfee->exonerated = null;
                }
                
            }else{
                $currency->fees->xfer->pctfee = new stdClass();
                $currency->fees->xfer->pctfee->field = "pctfeexfer";
                $currency->fees->xfer->pctfee->number = (float)number_format($feedata["pctfeexfer"], 2,'.','');
                $currency->fees->xfer->pctfee->formatted = number_format($feedata["pctfeexfer"],2,",",".");
                
                // Obtenemos este detalle si existe
                $sql = "SELECT * FROM userportfolioprefs ".
                "       WHERE userid = ".$userdata['id'].
                "       AND preffeesfield = 'pctfeexfer'".
                "       AND currencyid = ".$row['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $prefRow = $res->fetch_assoc();
                
                if ($prefRow['currencyid'] != null) {
                    $currency->fees->xfer->pctfee->exonerated = new stdClass();
                    $currency->fees->xfer->pctfee->exonerated->number = (float)number_format($prefRow["exonerated"], 2,'.','');
                    $currency->fees->xfer->pctfee->exonerated->formatted = numberFormatt($prefRow["exonerated"], 2);
                } else {
                    $currency->fees->xfer->pctfee->exonerated = null;
                }
                
                $currency->fees->xfer->nmalfee = null;
            }
            
            $currs [] = $currency;
        }
        
        $out->currencies = $currs;
    } else {
        $out->currencies = null;
    }
    
    // Validamos si puede ver sus exonerados de intercambios
    if (tienePrivilegio($db, $sessionid, 95)) {
        $out->pairs = new stdClass();
        $pairs = [];
        
        $sql = "SELECT *".
        "       FROM users".
        "       WHERE id = ".mysqli_real_escape_string($db, $id);
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
                
        $userdata = $rs->fetch_assoc();
        
        // Obtenemos el nombre del par
        $sql = "SELECT CONCAT(currencies.symbol,'/',cursec.symbol) AS pairdsc, par.id AS id, ".
        "       currencies.decimals AS currendecimals, cursec.decimals AS cursecdecimals".
        "       FROM currencies, pairs par ".
        "       LEFT JOIN currencies cursec ON cursec.id = par.currencyid ".
        "       WHERE par.refcurrencyid = currencies.id ".
        "       AND par.status = 1";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        while($pairInfo = $rs->fetch_assoc()){
            $pair = new stdClass();
            $pair->id = (int)$pairInfo['id'];
            $pair->name = $pairInfo['pairdsc'];
            
            // Consultamos los datos de ese par
            $sql = "SELECT * FROM cmspreffees ".
            "       WHERE cmspreffees.levelid = ".($userdata['level'] == 0 ? 1 : $userdata['level']).
            "       AND cmspreffees.pairid = ".$pair->id.
            "       AND cmspreffees.usertype = ".$userdata["type"];
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $fees = $res->fetch_assoc();
            
            $pair->fees = new stdClass();
            
            $pair->fees->limit = new stdClass();
            
            // Comision orden limit
            if ($fees['pctlimitfee'] != null){
                $pair->fees->limit->pctfee = new stdClass();
                $pair->fees->limit->pctfee->field = 'pctlimitfee';
                $pair->fees->limit->pctfee->number = (float)$fees['pctlimitfee'];
                $pair->fees->limit->pctfee->formatted = numberFormatt($fees['pctlimitfee'], 2);
                
                $pair->fees->limit->nmalfee = null;
                
                // Obtenemos este detalle si existe
                $sql = "SELECT * FROM userxchgprefs ".
                "       WHERE userid = ".$userdata['id'].
                "       AND preffeesfield = 'pctlimitfee'".
                "       AND pairid = ".$pairInfo['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $prefRow = $res->fetch_assoc();
                
                if ($prefRow['pairid'] != null) {
                    $pair->fees->limit->pctfee->exonerated = new stdClass();
                    $pair->fees->limit->pctfee->exonerated->number = (float)number_format($prefRow["exonerated"], 2,'.','');
                    $pair->fees->limit->pctfee->exonerated->formatted = numberFormatt($prefRow["exonerated"], 2);
                } else {
                    $pair->fees->limit->pctfee->exonerated = null;
                }
            } else {
                $pair->fees->limit->nmalfee = new stdClass();
                $pair->fees->limit->nmalfee->field = 'nmllimitfee';
                $pair->fees->limit->nmalfee->number = (float)$fees['nmllimitfee'];
                $pair->fees->limit->nmalfee->formatted = numberFormatt($fees['nmllimitfee'], 10);
                
                $pair->fees->limit->pctfee = null;
                
                // Obtenemos este detalle si existe
                $sql = "SELECT * FROM userxchgprefs ".
                "       WHERE userid = ".$userdata['id'].
                "       AND preffeesfield = 'nmllimitfee'".
                "       AND pairid = ".$pairInfo['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $prefRow = $res->fetch_assoc();
                
                if ($prefRow['pairid'] != null) {
                    $pair->fees->limit->nmalfee->exonerated = new stdClass();
                    $pair->fees->limit->nmalfee->exonerated->number = (float)number_format($prefRow["exonerated"], 2,'.','');
                    $pair->fees->limit->nmalfee->exonerated->formatted = numberFormatt($prefRow["exonerated"], 2);
                } else {
                    $pair->fees->limit->nmalfee->exonerated = null;
                }
            }
            
            $pair->fees->market = new stdClass();
            
            if ($fees['pctmktfee'] == null) {
                $pair->fees->market->nmalfee = new stdClass();
                $pair->fees->market->nmalfee->field = 'nmlmktfee';
                $pair->fees->market->nmalfee->number = (float)$fees['nmlmktfee'];
                $pair->fees->market->nmalfee->formatted = numberFormatt($fees['nmlmktfee'], 10);
                
                $pair->fees->market->pctfee = null;
                
                // Obtenemos este detalle si existe
                $sql = "SELECT * FROM userxchgprefs ".
                "       WHERE userid = ".$userdata['id'].
                "       AND preffeesfield = 'nmlmktfee'".
                "       AND pairid = ".$pairInfo['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $prefRow = $res->fetch_assoc();
                
                if ($prefRow['pairid'] != null) {
                    $pair->fees->market->nmalfee->exonerated = new stdClass();
                    $pair->fees->market->nmalfee->exonerated->number = (float)number_format($prefRow["exonerated"], 2,'.','');
                    $pair->fees->market->nmalfee->exonerated->formatted = numberFormatt($prefRow["exonerated"], 2);
                } else {
                    $pair->fees->market->nmalfee->exonerated = null;
                }
            } else {
                $pair->fees->market->pctfee = new stdClass();
                $pair->fees->market->pctfee->field = 'pctmktfee';
                $pair->fees->market->pctfee->number = (float)$fees['pctmktfee'];
                $pair->fees->market->pctfee->formatted = numberFormatt($fees['pctmktfee'], 2);
                
                $pair->fees->market->nmalfee = null;
                
                // Obtenemos este detalle si existe
                $sql = "SELECT * FROM userxchgprefs ".
                "       WHERE userid = ".$userdata['id'].
                "       AND preffeesfield = 'pctmktfee'".
                "       AND pairid = ".$pairInfo['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $prefRow = $res->fetch_assoc();
                
                if ($prefRow['pairid'] != null) {
                    $pair->fees->market->pctfee->exonerated = new stdClass();
                    $pair->fees->market->pctfee->exonerated->number = (float)number_format($prefRow["exonerated"], 2,'.','');
                    $pair->fees->market->pctfee->exonerated->formatted = numberFormatt($prefRow["exonerated"], 2);
                } else {
                    $pair->fees->market->pctfee->exonerated = null;
                }
            }
            
            $pairs [] = $pair;
        }
        
        $out->pairs = $pairs;
    } else {
        $out->pairs = null;
    }
    
    //Privilegios del usuario actual CMS
    $access = new stdClass();
    
    $access->updateuser = tienePrivilegio($db, $sessionid, 28);
    $access->readportfoliofees = tienePrivilegio($db, $sessionid, 96);
    $access->readxchgfees = tienePrivilegio($db, $sessionid, 95);
    $access->updateportfoliofees = tienePrivilegio($db, $sessionid, 93);
    $access->updatexchgfees = tienePrivilegio($db, $sessionid, 94);
    $access->updatepaythirdsparty = tienePrivilegio($db, $sessionid, 97);
    
    $access->readuser = tienePrivilegio($db, $sessionid, 29);
    $access->validateuser = tienePrivilegio($db, $sessionid, 27);
    
    $out->privileges = $access;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
     /* UTILIDAD */
    
    /*  Funcion para validar el tipo de empresa, donde se recibe:
    *   -ctype: ID para determinar el tipo de empresa
    *   donde:
    *   1 = Privada
    *   2 = Gubernametal
    *   3 = Mixta
    */
    function getCompanyType($ctype){
        $type = new stdClass();
        $type->id = (int)$ctype;
        
        if($type->id == 1){
            $type->dsc = "Privada";
        }else if($type->id == 2){
            $type->dsc = "Gubernamental";
        }else if($type->id == 3){
            $type->dsc = "Mixta";
        }
        
        return $type;
    }
    
    /* Funcion para validar el tipo de documento que fue ingresado, donde:
    * 1 = CI
    * 2 = Passport
    * 3 = Driver license
    * el parametro typeid es el id del tipo de documento
    */
    function validateDoc($typeid){
        $type = new stdClass();
        $type->id = (int)$typeid;
        
        if($type->id == 1){
            $type->dsc = "Cédula";
        }else if($type->id == 2){
            $type->dsc = "Pasaporte";
        }else if($type->id == 3){
            $type->dsc = "Licencia de conducir";
        }else if($type->id == 0){
            $type->dsc = null;
        }
        
        return $type;
    }
    
    /* Funcion para validar el tipo de estado civil, donde:
    * 1 = Soltero/Soltera
    * 2 = Casado/Casada
    * 3 = Divorciado/Divorciada
    * 4 = Viudo/Viuda
    * la funciona recibe dos parametros que son:
    * -gender = genero de la persona que se esta consultando
    * -maritalid = id del estado civil que sera evaluado
    */
    function validateMarital($maritalid, $gender){
        //	1 Single | 2 Married | 3 Divorced | 4 Widower
        $maritalstatus = new stdClass();
        $maritalstatus->id = (int)$maritalid;
        
        if($maritalstatus->id == 1){
            $maritalstatus->dsc = $gender == "F" ? "Soltera" : "Soltero";
        }else if($maritalstatus->id == 2){
            $maritalstatus->dsc = $gender == "F" ? "Casada" : "Casado";
        }else if($maritalstatus->id == 3){
            $maritalstatus->dsc = $gender == "F" ? "Divorciada" : "Divorciado";
        }else if($maritalstatus->id == 4){
            $maritalstatus->dsc = $gender == "F" ? "Viuda" : "Viudo";
        }else if($maritalstatus->id == 0){
            $maritalstatus->dsc = null;
        }
        
        return $maritalstatus;
    }
    
    /* Funcion para obtener el pais por su id devolviendo un objeto:
    *  country: {
    *        id: id del pais,
    *        dsc: nombre del pais
    *   }
    *   
    *   Los parametros que recibe son countryid siendo el id del pais, y la conexion de la BD
    */
    function getCountry($countryid, $db){
        if($countryid != 0){
            $sql = "SELECT id, name".
            "       FROM countries".
            "       WHERE id = ".$countryid;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $countrydata = $rs->fetch_assoc();
        
            $countryformatted = new stdClass();
            $countryformatted->id = (int)$countrydata["id"];
            $countryformatted->dsc = $countrydata["name"];
        }else{
            $countryformatted = new stdClass();
            $countryformatted->id = null;
            $countryformatted->dsc = null;
        }
        
        return $countryformatted;
    }
    
    /* Funcion para obtener el estado por su id devolviendo un objeto:
    *  region: {
    *        id: id del estado,
    *        dsc: nombre del estado
    *   }
    *   
    *   Los parametros que recibe son regionid siendo el id del estado, y la conexion de la BD
    */
    function getRegion($regionid, $db){
        if($regionid != 0){
            $sql = "SELECT id, name".
            "       FROM regions".
            "       WHERE id = ".$regionid;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $regiondata = $rs->fetch_assoc();
        
            $regionformatted = new stdClass();
            $regionformatted->id = (int)$regiondata["id"];
            $regionformatted->dsc = $regiondata["name"];
        }else{
            $regionformatted = new stdClass();
            $regionformatted->id = null;
            $regionformatted->dsc = null;
        }
        
        return $regionformatted;
    }
    
    /* Funcion para obtener la ciudad por su id devolviendo un objeto:
    *  region: {
    *        id: id de la ciudad,
    *        dsc: nombre de la ciudad
    *   }
    *   
    *   Los parametros que recibe son cityid siendo el id de la ciudad, y la conexion de la BD
    */
    function getCity($cityid, $db){
        if($cityid != 0){
            $sql = "SELECT id, name".
            "       FROM cities".
            "       WHERE id = ".$cityid;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $citydata = $rs->fetch_assoc();
        
            $cityformatted = new stdClass();
            $cityformatted->id = (int)$citydata["id"];
            $cityformatted->dsc = $citydata["name"];
        }else{
            $cityformatted = new stdClass();
            $cityformatted->id = null;
            $cityformatted->dsc = null;
        }
        
        return $cityformatted;
    }
    
    /*  Funcion que valida el campo si fue rechazado, aceptado o sigue en espera
    *   $field = Campo que se esta validando
    *   $rejecteds = arreglo con campos rechazados
    *   $approveds = arreglo con campos aceptados
    */
    function validateField($field, $rejecteds, $approveds){
        
        foreach($rejecteds as $rejected){
            if($rejected == $field){
                return -1;
            }
        }
        
        foreach($approveds as $approved){
            if($approved == $field){
                return 1;
            }
        }
        
        return 0;
    }
    
    /*  Funcion que valida si una imagen es requerida para subir de nivel o no
    *   $field = Campo que se esta validando
    *   $rejecteds = arreglo con imagenes requeridas
    */
    function validateUpload($field, $requireds){
        
        foreach($requireds as $required){
            if($required == $field){
                return true;
            }
        }
        
        return false;
    }
    
    /* Funcion para obtener la ocupacion por su id devolviendo un objeto:
    *  ocupation: {
    *        id: id de la ocupacion,
    *        dsc: dsc de la ocupacion
    *   }
    *   
    *   Los parametros que recibe son ocupationid siendo el id de la ocupacion, y la conexion de la BD
    */
    function getOcupation($ocupationid, $db){
        if($ocupationid != 0){
            $sql = "SELECT id, dsc, dsc_eng".
            "       FROM ocupations".
            "       WHERE id = ".$ocupationid;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $ocupationdata = $rs->fetch_assoc();
        
            $ocupationformatted = new stdClass();
            $ocupationformatted->id = (int)$ocupationdata["id"];
            $ocup = $ocupationdata["dsc"];
            if(empty($ocup)){
                $ocup = $ocupationdata["dsc_eng"];
            }
            $ocupationformatted->dsc = $ocup;
        }else{
            $ocupationformatted = new stdClass();
            $ocupationformatted->id = null;
            $ocupationformatted->dsc = null;
        }
        
        return $ocupationformatted;
    }
    /* Funcion para obtener la actividad economica por su id devolviendo un objeto:
    *  ocupation: {
    *        id: id de la actividad,
    *        dsc: dsc de la actividad
    *   }
    *   
    *   Los parametros que recibe son ocupationid siendo el id de la ocupacion, y la conexion de la BD
    *
    *   Clonado de ocupaciones
    */
    function getEconomicActs($ocupationid, $db){
        if($ocupationid != 0){
            $sql = "SELECT id, dsc, dsc_eng ".
            "       FROM economicactivities".
            "       WHERE id = ".$ocupationid;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $ocupationdata = $rs->fetch_assoc();
        
            $ocupationformatted = new stdClass();
            $ocupationformatted->id = (int)$ocupationdata["id"];
            $ocup = $ocupationdata["dsc"];
            if(empty($ocup)){
                $ocup = $ocupationdata["dsc_eng"];
            }
            $ocupationformatted->dsc = $ocup;
        }else{
            $ocupationformatted = new stdClass();
            $ocupationformatted->id = null;
            $ocupationformatted->dsc = null;
        }
        
        return $ocupationformatted;
    }
    /**
     * Devuelve si o no según valor 1 o 0
     * $val = valor 1 o 0 (true o false)
     */
    function getDscBool($val){
        if($val){
            return "Si";
        }else{
            return "No";
        }
    }
?>
