<?php
// cms/api/appusers/list

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","offset","numofrecords");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass;
    $sessionid = $_GET["sessionid"];
    $offset = $_GET["offset"];
    $numofrecords = $_GET["numofrecords"];
    $filter = "";
    $range = "";
    $status = "";
    $reqverify = '';
    $level = "";
    $order = determinateOrder($_GET["order"]);
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 29))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
        
    //En caso de que el filter sea enviado, se construye el query
    if(isset($_GET["filter"]) && $_GET["filter"] != ""){
        // Iniciamos la cadena del query
        $filterCompany = " AND ( ";
        $filter = " AND ( ";
        $filterPerson = " AND ( ";
        
        //Separamos el filtro por el simbolo +
        $filterEl = separateFilter($_GET["filter"]);
        
        //Recorremos cada elemento
        foreach($filterEl as $index => $el){
            
            //Si la fecha tiene / lo partimos en mil
            if(strpos($el, '/') !== false){
                $dateelements = explode("/",$el);
                
                foreach($dateelements as $i => $element){
                    if($i == 0){
                        $dateConverted .= $element;
                    }else{
                        $dateConverted .= "-".$element;
                    }
                }
                
                $dateel = strftime("%Y-%m-%d", strtotime($dateConverted));
            }else{
                $dateel = strftime("%Y-%m-%d", strtotime($el));
            }
            
            if($index == 0){
                $filterCompany .= " users.usr LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "                   OR usercompanies.doc LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "                   OR CONCAT(usercompanies.name,' / ', usercompanies.comercialname) LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "                   OR CONCAT('Nivel ', users.level) LIKE '".mysqli_real_escape_string($db, $el)."%' ".
                "                   OR DATE(users.lastsession) = DATE('".mysqli_real_escape_string($db, $dateel)."')";
                
                $filterPerson .= " users.usr LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "               OR userpersons.doc LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "               OR CONCAT(userpersons.fname,' ', userpersons.flastname) LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "               OR CONCAT(userpersons.sname,' ', userpersons.slastname) LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "               OR CONCAT('Nivel ', users.level) LIKE '".mysqli_real_escape_string($db, $el)."%' ".
                "               OR DATE(users.lastsession) = DATE('".mysqli_real_escape_string($db, $dateel)."')";
                
                $filter .= " users.usr LIKE '%".mysqli_real_escape_string($db, $el)."%' OR ".
                "           CONCAT(userpersons.fname,' ', userpersons.flastname) LIKE '%".mysqli_real_escape_string($db, $el)."%' OR ".
                "           CONCAT(usercompanies.name,' / ', usercompanies.comercialname) LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "           OR CONCAT(userpersons.sname,' ', userpersons.slastname) LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "           OR CONCAT('Nivel ', users.level) LIKE '".mysqli_real_escape_string($db, $el)."%' ".
                "           OR DATE(users.lastsession) = DATE('".mysqli_real_escape_string($db, $dateel)."')";
                
            }else{
                $filterCompany .= " OR users.usr LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "                   OR usercompanies.doc LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "                   OR CONCAT(usercompanies.name,' / ', usercompanies.comercialname) LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "                   OR CONCAT('Nivel ', users.level) LIKE '".mysqli_real_escape_string($db, $el)."%' ".
                "                   OR DATE(users.lastsession) = DATE('".mysqli_real_escape_string($db, $dateel)."')";
                
                $filterPerson .= " OR users.usr LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "               OR userpersons.doc LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "               OR CONCAT(userpersons.fname,' ', userpersons.flastname) LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "               OR CONCAT(userpersons.sname,' ', userpersons.slastname) LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "               OR CONCAT('Nivel ', users.level) LIKE '".mysqli_real_escape_string($db, $el)."%' ".
                "               OR DATE(users.lastsession) = DATE('".mysqli_real_escape_string($db, $dateel)."')";
                
                $filter .= " OR users.usr LIKE '%".mysqli_real_escape_string($db, $el)."%' OR ".
                "           CONCAT(userpersons.fname,' ', userpersons.flastname) LIKE '%".mysqli_real_escape_string($db, $el)."%' OR ".
                "           CONCAT(usercompanies.name,' / ', usercompanies.comercialname) LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "           OR CONCAT(userpersons.sname,' ', userpersons.slastname) LIKE '%".mysqli_real_escape_string($db, $el)."%' ".
                "           OR CONCAT('Nivel ', users.level) LIKE '".mysqli_real_escape_string($db, $el)."%' ".
                "           OR DATE(users.lastsession) = DATE('".mysqli_real_escape_string($db, $dateel)."')";
                
            }
        }
        
        $filterCompany .= " ) ";
        $filter .= " ) ";
        $filterPerson .= " ) ";
        
    }
    
    //En caso de que el range sea enviado, se construye el query
    if(isset($_GET["range"]) && $_GET["range"] != ""){
        $range = determinateRange($_GET["range"]);
    }
    
    //En caso de que el status sea enviado, se construye el query
    if(isset($_GET["status"]) && $_GET["status"] != ""){
        $status = " AND users.status = ".mysqli_real_escape_string($db, $_GET["status"]);
    }
    
    //En caso de que el level sea enviado, se construye el query
    if(isset($_GET["level"]) && $_GET["level"] != ""){
        $level = " AND users.level = ".mysqli_real_escape_string($db, $_GET["level"]);
    }
    
    //En caso de que el level sea enviado, se construye el query
    if(isset($_GET['reqverify']) && $_GET['reqverify'] != ""){
        $reqverify = " AND users.reqverify = ".mysqli_real_escape_string($db, $_GET['reqverify']);
    }
    
    $sql = "SELECT COUNT(userid) AS qty FROM (SELECT users.id AS userid, ".
    "       users.usr AS userusr, ".
    "       users.login2fa AS login2fa, ".
    "       users.op2fa AS op2fa, ".
    "       users.datecreated AS userdatecreated, ".
    "       IF(payusers.userid IS NOT NULL AND payusers.lastsession > users.lastsession, payusers.lastsession, users.lastsession) AS userlastsession, ".
    "       users.status AS userstatus, ".
    "       users.type AS usertype, ".
    "       users.level AS userlevel, ".
    "       usercompanies.name AS name, ".
    "       usercompanies.comercialname AS secondname ".
    "       FROM usercompanies, users ".
    "       LEFT JOIN payusers ON payusers.userid = users.id ".
    "       WHERE users.id > 0 ".
    "       AND usercompanies.usrid = users.id AND users.type IS NOT NULL".
    "       ".$filterCompany.
    "       ".$status.
    "       ".$level.
    "       ".$reqverify.
    "       ".$range.
    "".
    "UNION ALL".
    "".
    "       SELECT users.id AS userid, ".
    "       users.usr AS userusr, ".
    "       users.login2fa AS login2fa, ".
    "       users.op2fa AS op2fa, ".
    "       users.datecreated AS userdatecreated, ".
    "       IF(payusers.userid IS NOT NULL AND payusers.lastsession > users.lastsession, payusers.lastsession, users.lastsession) AS userlastsession, ".
    "       users.status AS userstatus, ".
    "       users.type AS usertype, ".
    "       users.level AS userlevel, ".
    "       CONCAT(userpersons.fname,' ', userpersons.sname) AS name, ".
    "       CONCAT(userpersons.flastname, ' ', userpersons.slastname) AS secondname ".
    "       FROM userpersons, users ".
    "       LEFT JOIN payusers ON payusers.userid = users.id ".
    "       WHERE users.id > 0 ".
    "       AND userpersons.usrid = users.id AND users.type IS NOT NULL".
    "       ".$filterPerson.
    "       ".$status.
    "       ".$level.
    "       ".$reqverify.
    "       ".$range.
    " ) A     ";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    //Retornamos el total
    $out->numofrecords = (int)$row["qty"];
    
    //Consultamos los detalles de los usuarios
    $sql = "SELECT * FROM (SELECT users.id AS userid, ".
    "       users.login2fa AS login2fa, ".
    "       users.op2fa AS op2fa, ".
    "       users.usr AS userusr, ".
    "       users.datecreated AS userdatecreated, ".
    "       IF(payusers.userid IS NOT NULL AND payusers.lastsession > users.lastsession, payusers.lastsession, users.lastsession) AS userlastsession, ".
    "       users.status AS userstatus, ".
    "       users.type AS usertype, ".
    "       users.level AS userlevel, ".
    "       usercompanies.name AS name, ".
    "       usercompanies.comercialname AS secondname, ".
    "       usercompanies.doc AS doc ".
    "       FROM usercompanies, users ".
    "       LEFT JOIN payusers ON payusers.userid = users.id ".
    "       WHERE users.id > 0 ".
    "       AND usercompanies.usrid = users.id AND users.type IS NOT NULL".
    "       ".$filterCompany.
    "       ".$status.
    "       ".$level.
    "       ".$reqverify.
    "       ".$range.
    "".
    "UNION ALL".
    "".
    "       SELECT users.id AS userid, ".
    "       users.login2fa AS login2fa, ".
    "       users.op2fa AS op2fa, ".
    "       users.usr AS userusr, ".
    "       users.datecreated AS userdatecreated, ".
    "       IF(payusers.userid IS NOT NULL AND payusers.lastsession > users.lastsession, payusers.lastsession, users.lastsession) AS userlastsession, ".
    "       users.status AS userstatus, ".
    "       users.type AS usertype, ".
    "       users.level AS userlevel, ".
    "       userpersons.fname AS name, ".
    "       userpersons.flastname AS secondname, ".
    "       userpersons.doc AS doc ".
    "       FROM userpersons, users ".
    "       LEFT JOIN payusers ON payusers.userid = users.id ".
    "       WHERE users.id > 0 ".
    "       AND userpersons.usrid = users.id AND users.type IS NOT NULL".
    "       ".$filterPerson.
    "       ".$status.
    "       ".$level.
    "       ".$reqverify.
    "       ".$range.
    ") A      ".$order.
    "       LIMIT ".$offset.", ".$numofrecords;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    //Ordenamos los datos del usuario
    while($userdata = $rs->fetch_assoc()){

        $record = new stdClass();
        $record->id = (int)$userdata["userid"];
        $record->usr = $userdata["userusr"];
        
        if($userdata["usertype"] == 1){
            $record->name = $userdata["name"];
            $record->lastname = $userdata["secondname"];
            $record->fullname = $record->name.($record->lastname == "" ? "" : " ".$record->lastname);
        }else{
            $record->name = $userdata["name"];
            $record->lastname = $userdata["secondname"];
            $record->fullname = $record->name.($record->lastname == "" ? "" : " / ".$record->lastname);
        }
        
        // Vamos a ver si tiene archivos subidos en un tipo que no sea el suyo
        // Se hace con IN porque la factura por ejemplo es compartida
        $sql = "SELECT COUNT(US.userid) AS qty ".
        "       FROM useruploads US".
        "       JOIN cmsprefuploads CMSUP ON CMSUP.id = US.prefuploadid ".
        "       AND NOT INSTR(CMSUP.type,".($userdata["usertype"] == 1 ? '1' : '2').") ".
        "       WHERE US.userid = ".$record->id;
        
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $resUpload = $res->fetch_assoc();
        
        if ($resUpload['qty'] > 0) {
            
            $urlfolder = "../../../uploads/users/".$record->id;
            $filesfromdir = glob($urlfolder.'/*');
            
            $sql = "SELECT CMSUP.id ".
            "       FROM useruploads US".
            "       JOIN cmsprefuploads CMSUP ON CMSUP.id = US.prefuploadid ".
            "       AND NOT INSTR(CMSUP.type,".($userdata["usertype"] == 1 ? '1' : '2').") ".
            "       WHERE US.userid = ".$record->id;
            
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                    
            while($rowUpload = $res->fetch_assoc()){
                
                // Recorremos los archivos de su directorio
                foreach($filesfromdir as $filefromdir){
        
                    $extfromdir = pathinfo($filefromdir, PATHINFO_EXTENSION);
                    $filename = basename($filefromdir,".".$extfromdir);
                    
                    if ($filename == str_pad($rowUpload["id"], 2, "0", STR_PAD_LEFT)) {
                        $record->ajaa3 [] = $filename;
                        //Eliminamos registro
                        $sql = "DELETE FROM useruploads WHERE".
                        "       userid=".$record->id." AND".
                        "       prefuploadid = ".$rowUpload["id"];
                        if (!$db->query($sql))
                            badEnd("500", array("msg"=>determinateDBError($db)));
                        
                        
                        //Eliminamos fichero
                        unlink($filefromdir);
                    }
                }
            }
        }
            
        
        $record->doc = $userdata['doc'];
        
        $record->datecreated = date("Y-m-d", strtotime($userdata["userdatecreated"]));
        
        $record->lastsession = new stdClass();
        $record->lastsession->date = $userdata["userlastsession"] == null ? null : date("Y-m-d H:i", strtotime($userdata["userlastsession"]));
        $record->lastsession->formatted = $userdata["userlastsession"] == null ? null :  date("d/m/Y", strtotime($userdata["userlastsession"]))." - ".date("h:i a", strtotime($userdata["userlastsession"]));
        
        $record->status = new stdClass();
        $record->status->id = (int)$userdata["userstatus"];
        $record->status->dsc = $record->status->id == 1 ? "Activo" : "Inactivo";
        
        $record->type = new stdClass();
        $record->type->id = $userdata["usertype"] == null ? null : (int)$userdata["usertype"];
        $record->type->dsc = $userdata["usertype"] == null ? null : determinateType($record->type->id);
        
        // Obtenemos el row del level
        $sql = "SELECT * FROM levels WHERE id = ".$userdata['userlevel'];
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $resLevel = $res->fetch_assoc();
        
        $record->level = new stdClass();
        $record->level->id = (int)$resLevel['id'];
        $record->level->dsc = "Nivel ".$resLevel['orden'];
        
        $record->login2fa = (int)$userdata['login2fa'];
        $record->op2fa = (int)$userdata['op2fa'];
        
        //Consultamos dependiendo del tipo de usuario junto su id
        if($userdata["usertype"] !== null){
            if($userdata["usertype"] == 1){
                $sqlU = "SELECT *".
                "       FROM userpersons".
                "       WHERE usrid = ".$userdata["userid"];
                if (!$rsU=$db->query($sqlU))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                $userdetail = $rsU->fetch_assoc();
                
            }else if($userdata["usertype"] == 2){
                $sqlU = "SELECT *".
                "       FROM usercompanies".
                "       WHERE usrid = ".$userdata["userid"];
                if (!$rsU=$db->query($sqlU))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                $userdetail = $rsU->fetch_assoc();
                
            }
            
            $rejecteds = explode(",",$userdetail["rejected"]);
            $approveds = explode(",",$userdetail["approved"]);
            
            $record->modified = false;
            
            $validPolitical = false;
            foreach($userdetail as $index => $result){
                    
                if($index == "politicallyexposed" && intval($result) == 1){
                    $validPolitical = true;
                }
                        
                //#NEW AGREGADO POR CAMBIOS DE REGISTRO
                $newvalid = true;
                if($userdata["usertype"] == 1){
                    if($index == 'sname' || $index == 'slastname' || $index == 'domicile'){
                        $newvalid = false;
                    }
                }
                
                if($index != 'rejected' && $index != 'approved' && $index != 'independentdealer' && $index != 'usrid' 
                    && $index != 'step' && $index != 'lastupdate' && $index != 'doctype' 
                    && $index != 'ctype'&& $index != 'partners'  && $newvalid && $index != 'reppartner'
                ){
                    $out->conquienfue = $result." | ".$index."| 1 ".$record->usr;
                    if(validateField($index, $rejecteds, $approveds) == 0 && $result != '' && $result != null){
                        
                        if($validPolitical){
                            $record->modified = true;
                            $record->conquienfue2 = $result." | ".$index."| 2";
                            break;
                        }else{
                            if($index != 'affiliationbody' && $index != 'positionheld' && $index != 'pepcountryid' && $index != 'peprelatedid' && $index != 'modifiedat'){
                                $record->modified = true;
                                $record->conquienfue3 = $result." | ".$index."| 3";
                                break;
                            }
                        }
                        
                    }  
                }
            }
            
            
            
            //Si el usuario no posee un 0, validamos ahora las iamgenes
            if(!$record->modified){
                $sql = "SELECT * FROM useruploads ".
                "       WHERE userid = ".$userdata["userid"];
                if (!$rsI=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                while($uploaddetail = $rsI->fetch_assoc()){
                    if($uploaddetail["validated"] == 0){
                        $out->conquienfue4 = $result." | ".$index."| 4 ".$record->usr;
                        $out->test4 = $uploaddetail;
                        $record->modified = true;
                        break;
                    }
                }
            }
            
            
            
            //Si el usuario esta validado, recorremos las cuentas
            if(!$record->modified){
                
                $sql = "SELECT * FROM accounts ".
                "       WHERE userid = ".$userdata['userid'].
                "       AND paymentmethodid > 0 ";
                if (!$rsA=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                while($accountdetail = $rsA->fetch_assoc()){    
                    
                    // Obtenemos el paymentmethod para ver que campos se validan
                    $sql = "SELECT * ".
                    "       FROM paymentmethods ".
                    "       WHERE id = ".$accountdetail['paymentmethodid'];
                    if (!$rsP=$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                        
                    $paymentmethod = $rsP->fetch_assoc();
                
                    $rejecteds = explode(",",$accountdetail["rejected"]);
                    $approveds = explode(",",$accountdetail["approved"]);
                
                    foreach($accountdetail as $index => $result){
                    
                        $out->conquienfue5 = $result." | ".$index."| 5 ".$record->usr;
                        if($index == 'details1' || $index == 'details2' || $index == 'details3' || $index == 'details4'){
                            
                            if($paymentmethod[$index] != null){
                                if(validateField($index, $rejecteds, $approveds) == 0 && $result != '' && $result != null){
                                    $record->modified = true;
                                    $out->conquienfue6 = $result." | ".$index."| 6 ".$record->usr;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            
            
            
        
            if($userdata["usertype"] == 2 && !$record->modified){
                //Arreglo con los campos a recorres
                $partnerfield = ["name","doc","phone","politicallyexposed","affiliationbody","positionheld","pepcountryid","peprelatedid"];
                
                $sql = "SELECT * FROM usercompanypartners ".
                "       WHERE companyid = ".$userdata["userid"];
                if (!$rsP=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                while($partnerdetail = $rsP->fetch_assoc()){
                    
                    $rejecteds = explode(",",$partnerdetail["rejected"]);
                    $approveds = explode(",",$partnerdetail["approved"]);
            
                    $qtyfields = sizeof($partnerfield);
            
                    for($i = 0; $i < $qtyfields; $i++){
                        //Recorro el arreglo con todos los campos
                        if($partnerfield[$i] == "politicallyexposed" && $partnerdetail["politicallyexposed"] == 0 && validateField($partnerfield[$i], $rejecteds, $approveds) != 0){
                            $record->modified = false;
                            $out->conquienfue7 = $result." | ".$index."| 7 ".$record->usr;
                            $i += 99999;
                        }else if(validateField($partnerfield[$i], $rejecteds, $approveds) == 0){
                            $record->modified = true;
                            $out->conquienfue7 = $result." | ".$index."| 7 ".$record->usr;
                            $i += 99999;
                        }    
                    }
                }
            }
            
            
        }
        
        if($record->modified){
            reqverifyuser($userdata["userid"], $db, true);
        }else{
            reqverifyuser($userdata["userid"], $db, false);
        }
        
    
        $records [] = $record;
    }
    
    $out->records = $records;
    
    //Privilegios del usuario actual CMS
    $access = new stdClass();
    $access->statuschange = tienePrivilegio($db, $sessionid, 27);
    $access->levelchange = tienePrivilegio($db, $sessionid, 28);
    $access->read = tienePrivilegio($db, $sessionid, 29);
    $out->privileges = $access;

    //Agregado modified para obtener cambios del usuario

    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /*  Funcion para determinar el tipo de usuario, si:
    *   $id = 1: Retorna Natural
    *   $id = 2: Retorna Juridico
    *
    */
    function determinateType($id){
        $str = "";
        
        switch($id){
            case 1:
                $str = "Natural";
                break;
            case 2:
                $str = "Juridico";
                break;
        }
        
        return $str;
    }
    
    /*  Funcion para determinar el orden de los resultados
    *   Esta recibe un parametro que retorna dependiendo del valor:
    *   0 = Ultimo usuario que inicio sesion
    *   1 = Correo del usuario ASCENDENTE
    *   2 = Nivel del usuario ASCENDENTE
    *   3 = Status del usuario ASCENDENTE
    *   -1 = Correo del usuario DESCENDENTE
    *   -2 = Nivel del usuario DESCENDENTE
    *   -3 = Status del usuario DESCENDENTE
    */
    function determinateOrder($order){
        $str = "";
        
        switch($order){
            case 0:
                $str = "ORDER BY userlastsession DESC";
                break;
            case 1:
                $str = "ORDER BY name ASC";
                break;
            case 2:
                $str = "ORDER BY userlevel ASC";
                break;
            case 3:
                $str = "ORDER BY userstatus ASC";
                break;
            case 4:
                $str = "ORDER BY userlastsession ASC";
                break;
            case -1:
                $str = "ORDER BY name DESC";
                break;
            case -2:
                $str = "ORDER BY userlevel DESC";
                break;
            case -3:
                $str = "ORDER BY userstatus DESC";
                break;
            case -4:
                $str = "ORDER BY userlastsession DESC";
                break;
        }
        
        return $str;
    }
    
    /*  Funcion para filtras resultados dependiendo del rango:
    *   1 = Today
    *   2 = Last 7 days
    *   3 = Last 30 days
    *
    */
    function determinateRange($range){
        $str = "";
        
        switch($range){
            case 1:
                $str = " AND DATE(users.lastsession) >= DATE_ADD(NOW(), INTERVAL -1 DAY)";
                break;
            case 2:
                $str = " AND DATE(users.lastsession) >= DATE_ADD(NOW(), INTERVAL -7 DAY)";
                break;
            case 3:
                $str = " AND DATE(users.lastsession) >= DATE_ADD(NOW(), INTERVAL -30 DAY)";
                break;
        }
        
        return $str;
    }
    /*  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;
    }
?>