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

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../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 '%".$el."%' OR ".
                "                   CONCAT(usercompanies.name,' / ', usercompanies.comercialname) LIKE '%".$el."%' ".
                "                   OR CONCAT('Nivel ', users.level) LIKE '".$el."%' ".
                "                   OR DATE(users.lastsession) = DATE('".$dateel."')";
                
                $filterPerson .= " users.usr LIKE '%".$el."%' OR ".
                "               CONCAT(userpersons.fname,' ', userpersons.flastname) LIKE '%".$el."%' ".
                "               OR CONCAT(userpersons.sname,' ', userpersons.slastname) LIKE '%".$el."%' ".
                "               OR CONCAT('Nivel ', users.level) LIKE '".$el."%' ".
                "               OR DATE(users.lastsession) = DATE('".$dateel."')";
                
                $filter .= " users.usr LIKE '%".$el."%' OR ".
                "           CONCAT(userpersons.fname,' ', userpersons.flastname) LIKE '%".$el."%' OR ".
                "           CONCAT(usercompanies.name,' / ', usercompanies.comercialname) LIKE '%".$el."%' ".
                "           OR CONCAT(userpersons.sname,' ', userpersons.slastname) LIKE '%".$el."%' ".
                "           OR CONCAT('Nivel ', users.level) LIKE '".$el."%' ".
                "           OR DATE(users.lastsession) = DATE('".$dateel."')";
                
            }else{
                $filterCompany .= " OR users.usr LIKE '%".$el."%' OR ".
                "                   CONCAT(usercompanies.name,' / ', usercompanies.comercialname) LIKE '%".$el."%' ".
                "                   OR CONCAT('Nivel ', users.level) LIKE '".$el."%' ".
                "                   OR DATE(users.lastsession) = DATE('".$dateel."')";
                
                $filterPerson .= " OR users.usr LIKE '%".$el."%' OR ".
                "               CONCAT(userpersons.fname,' ', userpersons.flastname) LIKE '%".$el."%' ".
                "               OR CONCAT(userpersons.sname,' ', userpersons.slastname) LIKE '%".$el."%' ".
                "               OR CONCAT('Nivel ', users.level) LIKE '".$el."%' ".
                "               OR DATE(users.lastsession) = DATE('".$dateel."')";
                
                $filter .= " OR users.usr LIKE '%".$el."%' ".
                "           OR CONCAT(userpersons.fname,' ', userpersons.flastname) LIKE '%".$el."%' ".
                "           OR CONCAT(userpersons.sname,' ', userpersons.slastname) LIKE '%".$el."%' ".
                "           OR CONCAT(usercompanies.name,' / ', usercompanies.comercialname) LIKE '%".$el."%' ".
                "           OR CONCAT('Nivel ', users.level) LIKE '".$el."%' ".
                "           OR DATE(users.lastsession) = DATE('".$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 = ".$_GET["status"];
    }
    
    //En caso de que el level sea enviado, se construye el query
    if(isset($_GET["level"]) && $_GET["level"] != ""){
        $level = " AND users.level = ".$_GET["level"];
    }
    
    //En caso de que el level sea enviado, se construye el query
    if(isset($_GET['reqverify']) && $_GET['reqverify'] != ""){
        $reqverify = " AND users.reqverify = ".$_GET['reqverify'];
    }
    
    //Consultamos la cantidad de usuarios existentes
    $sql = "SELECT COUNT(users.id) AS qty".
    "       FROM users".
    "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
    "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id".
    "       WHERE users.id > 0 AND users.type IS NOT NULL ".
    "       ".$filter.
    "       ".$status.
    "       ".$level.
    "       ".$reqverify.
    "       ".$range;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
        
    $row = $rs->fetch_assoc();
    //Retornamos el total
    $out->numofrecords = (int)$row["qty"];
    
    //Consultamos los detalles de los usuarios
    $sql = "SELECT users.id AS userid, ".
    "       users.usr AS userusr, ".
    "       users.datecreated AS userdatecreated, ".
    "       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 users, usercompanies ".
    "       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.datecreated AS userdatecreated, ".
    "       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 users,userpersons ".
    "       WHERE users.id > 0 ".
    "       AND userpersons.usrid = users.id AND users.type IS NOT NULL".
    "       ".$filterPerson.
    "       ".$status.
    "       ".$level.
    "       ".$reqverify.
    "       ".$range.
    "       ".$order.
    "       LIMIT ".$offset.", ".$numofrecords;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
        
    //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);
        }
        
        $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);
        
        $record->level = new stdClass();
        $record->level->id = (int)$userdata["userlevel"];
        $record->level->dsc = "Nivel ".$record->level->id;
        
        //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"=>$db->error));
                $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"=>$db->error));
                $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;
                }
                    
                if($index != 'rejected' && $index != 'approved' && $index != 'independentdealer' && $index != 'usrid' && $index != 'step' && $index != 'lastupdate'){
                    $record->conquienfue = $result." | ".$index;
                    if(validateField($index, $rejecteds, $approveds) == 0 && $result != '' && $result != null){
                        
                        if($validPolitical){
                            $record->modified = true;
                            $record->conquienfue = $result." | ".$index;
                            break;
                        }else{
                            if($index != 'affiliationbody' && $index != 'positionheld' && $index != 'pepcountryid' && $index != 'peprelatedid'){
                                $record->modified = true;
                                $record->conquienfue = $result." | ".$index;
                                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"=>$db->error));
                    
                while($uploaddetail = $rsI->fetch_assoc()){
                    if($uploaddetail["validated"] == 0){
                        $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"=>$db->error));
                    
                while($accountdetail = $rsA->fetch_assoc()){    
                    $rejecteds = explode(",",$accountdetail["rejected"]);
                    $approveds = explode(",",$accountdetail["approved"]);
                
                    foreach($accountdetail as $index => $result){
                    
                        $record->conquienfue = $result." | ".$index;
                        if($index == 'details1' || $index == 'details2' || $index == 'details3' || $index == 'details4'){
                        
                            if(validateField($index, $rejecteds, $approveds) == 0 && $result != '' && $result != null){
                                $record->modified = true;
                                $record->conquienfue = $result." | ".$index;
                                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"=>$db->error));
                    
                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;
                            $i += 99999;
                        }else if(validateField($partnerfield[$i], $rejecteds, $approveds) == 0){
                            $record->modified = true;
                            $i += 99999;
                        }    
                    }
                }
            }
        }
            
        $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;
    }
?>