<?php
// app/api/users/entry
    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");

    // parametros obligatorios
    $parmsob = array("sessionid");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    //definimos las variables y las rellenamos con los datos recibidos del GET
    $sessionid = $_GET["sessionid"];
    $out = new stdClass();    
    
    //Validamos la session
    isSessionValid($db, $sessionid);
    
    // Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    //Consulta de los datos iniciales
    $sql = "SELECT *".
    "       FROM users".
    "       WHERE sessionid = '".$sessionid."'";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
            
    $userdata = $rs->fetch_assoc();
    
    if($userdata["id"] == null){
        badEnd("204", array("msg"=>determinateMsgFail(array(
            "esp"=>"No se encuentra el registro",
            "eng"=>"Cannot find the record"), $lang, "No se encuentra el registro")));
    }
    
    //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->view = (int)$userdata['view'];
    
    //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;
    }
    
    // Consultamos el nivel para obtener su descripcion
    $sql = "SELECT * FROM levels WHERE id = ".$userdata['level'];
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
            
    $leveldata = $rs->fetch_assoc();
    
    //Describimos el nivel
    $out->entry->level = new stdClass();
    $out->entry->level->id = (int)$leveldata["id"];
    $out->entry->level->name = $leveldata['name'];
    $out->entry->level->dsc = $leveldata['dsc'];
    
    //Termminos y condiciones
    $out->entry->terms = $userdata["terms"];
    
    //Declaracion jurada
    $out->entry->declaration = $userdata["declaration"];
    
    //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"=>$db->error));
            
        $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"=>$db->error));
            
        $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"=>determinateMsgFail(array(
            "esp"=>"Usuario no activado",
            "eng"=>"User not activated"), $lang, "Usuario no activado")));
    }
    
    //Consultamos los datos del siguiente nivel
    $sql = "SELECT * FROM levels ".
    "       WHERE orden = ".($out->entry->level->id + 1);
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
            
    $levels = $rs->fetch_assoc();
    
    //Procedemos a construir la salida de datos
    if($out->entry->type->id == 1){
        
        $rejecteds = explode(",",$userdetail["rejected"]);
        $approveds = explode(",",$userdetail["approved"]);
        
        $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 = date("Y-m-d H:i", strtotime($userdetail["docissue"]));
        $out->entry->person->document->datecreated->formatted = date("d/m/Y h:i a", 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 = date("Y-m-d H:i", strtotime($userdetail["docexpiry"]));
        $out->entry->person->document->dateexpiration->formatted = date("d/m/Y h:i a", 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 = date("Y-m-d H:i", strtotime($userdetail["birthdate"]));
        $out->entry->person->birthdate->formatted = date("d/m/Y h:i a", 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->value = $userdetail["ocupation"];
        $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 : (int)$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->value = (int)$userdetail["pepcountryid"];
        $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 : (int)$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->value = $userdetail["economicactivity"];
        $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 : (int)$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 ? (int)$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 ? (int)$userdetail["venezuelan"] : null;
        $out->entry->person->venezuelan->valid = validateField("venezuelan", $rejecteds, $approveds);
        $out->entry->person->venezuelan->update = "venezuelan";
        
        //Consulta para obtener los documentos que ha subido el usuario 
        $sql = "SELECT * FROM useruploads".
        "       WHERE userid = ".$out->entry->id;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
            
        while($uploadarr = $rs->fetch_assoc()){
            $upload = new stdClass();
            //Generamos el id de salida
            $upload->id = str_pad($uploadarr["prefuploadid"], 2, "0", STR_PAD_LEFT);
            
            //Consultamos los datos de cada tipo de documento
            $sql = "SELECT * FROM cmsprefuploads".
            "       WHERE id = ".$uploadarr["prefuploadid"];
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
            
            $uploaddetail = $res->fetch_assoc();
            
            $upload->dsc = $uploaddetail["dsc"];
            
            //$extention = explode("/",$uploadarr["filetype"]);
            
            //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);
            
            //Url dentro de la carpeta api
            $upload->url = "./api/uploads/users/".$out->entry->id."/".$info["basename"];
            
            $upload->level = new stdClass();
            
            //Consultamos los datos del nivel
            $sql = "SELECT * FROM levels";
            if (!$resUp=$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
            
            while($levelsTemp = $resUp->fetch_assoc()){
                
                $levelsarrTemp = explode("-",$levelsTemp["cmsprefuploads"]);
                foreach($levelsarrTemp as $whichlevel){
                    if($uploadarr["prefuploadid"] == $whichlevel){
                        $upload->level->id = (int)$levelsTemp["orden"];
                        $upload->level->dsc = $levelsTemp["name"];
                    }
                }
            }
            
            $upload->validated = (int)$uploadarr["validated"];
            
            $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->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 = date("Y-m-d H:i", strtotime($userdetail["creationdate"]));
        $out->entry->company->datecreated->formatted = date("d/m/Y h:i a", 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 : (int)$userdetail["venezuelan"];
        $out->entry->company->venezuelan->valid = validateField("venezuelan", $rejecteds, $approveds);
        $out->entry->company->venezuelan->update = "venezuelan";
        
        //Consulta para obtener socios
        $sql = "SELECT * FROM usercompanypartners".
        "       WHERE companyid = ".$out->entry->id;
        if (!$partnerrow=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        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 = (int)$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->value = (int)$partnerdata["pepcountryid"];
            $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 : (int)$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->value = $userdetail["economicactivity"];
        $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 : (int)$userdetail["economicrelation"];
        $out->entry->company->economicrelation->valid = validateField("economicrelation", $rejecteds, $approveds);
        $out->entry->company->economicrelation->udpated = "economicrelation";
        
        //Consulta para obtener los documentos que ha subido el usuario 
        $sql = "SELECT * FROM useruploads".
        "       WHERE userid = ".$out->entry->id;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
            
        while($uploadarr = $rs->fetch_assoc()){
            $upload = new stdClass();
            //Generamos el id de salida
            $upload->id = str_pad($uploadarr["prefuploadid"], 2, "0", STR_PAD_LEFT);
            
            //Consultamos los datos de cada tipo de documento
            $sql = "SELECT * FROM cmsprefuploads".
            "       WHERE id = ".$uploadarr["prefuploadid"];
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
            
            $uploaddetail = $res->fetch_assoc();
            
            $upload->dsc = $uploaddetail["dsc"];
            
            //$extention = explode("/",$uploadarr["filetype"]);
            
            //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);
            
            //Url dentro de la carpeta api
            $upload->url = "./api/uploads/users/".$out->entry->id."/".$info["basename"];
            
            $upload->level = new stdClass();
            
            //Consultamos los datos del nivel
            $sql = "SELECT * FROM levels";
            if (!$resUp=$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
            
            while($levelsTemp = $resUp->fetch_assoc()){
                
                $levelsarrTemp = explode("-",$levelsTemp["cmsprefuploads"]);
                foreach($levelsarrTemp as $whichlevel){
                    if($uploadarr["prefuploadid"] == $whichlevel){
                        $upload->level->id = (int)$levelsTemp["orden"];
                        $upload->level->dsc = "Nivel ".$upload->level->id;
                    }
                }
                
            }
            
            $upload->validated = (int)$uploadarr["validated"];
            
            $arrRequiresUp = explode("-",$levels["cmsprefuploads"]);
            $upload->required = validateUpload($uploadarr["prefuploadid"],$arrRequiresUp);
            
            $uploads[] = $upload;
        }
        
        $out->entry->company->uploads = $uploads;
    }
    
    if($levels["id"] == null){
        $out->requiredLevel = null;
    }else{
        //Campos requeridos para el siguiente nivel del usuario
        
        if($out->entry->type->id == 1){
            $out->requiredLevel = $levels["userpersons"];
        }else if($out->entry->type->id == 2){
            $out->requiredLevel = $levels["usercompanies"];
            $out->partnersRequiredLvl = $levels["usercompanypartners"];
        }
    }
    
    //Cargamos los datos de cada nivel
    $sql = "SELECT * FROM levels";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    while($leveldata = $rs->fetch_assoc()){
        $levelfield = new stdClass();
        
        $levelfield->id = (int)$leveldata["orden"];
        $levelfield->dsc = "Nivel ".$leveldata['orden'];
        $levelfield->partnersRequired = $leveldata["usercompanypartners"];
        
        if($out->entry->type->id == 1){
            $levelfield->basicRequired = $leveldata["userpersons"];
        }else if($out->entry->type->id == 2){
            $levelfield->basicRequired = $leveldata["usercompanies"];
        }
        
        $sql = "SELECT * FROM cmsprefuploads".
        "       WHERE type LIKE '%".$out->entry->type->id."%'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $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->uploadRequired = $uploadId == "" ? $uploadId : substr($uploadId, 0, -1);
        
        $levelfields [] = $levelfield;
    }
    
    $out->entry->levels = $levelfields;  
    
    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";
        }
        
        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"=>$db->error));
            
            $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"=>$db->error));
            
            $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"=>$db->error));
            
            $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;
    }
?>
