<?php
// cms/api/appusers/validate

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    require '../../hooks/PHPMailer5/PHPMailerAutoload.php';
    date_default_timezone_set('Etc/UTC');
    
    // parametros obligatorios
    $parmsob = array("sessionid","id");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out = new stdClass();
    $sessionid = mysqli_real_escape_string($db, $_GET["sessionid"]);
    $id = mysqli_real_escape_string($db, $_GET["id"]);
    
    $isRejected = 0;
    $isAcepted = 0;
    
    //OJO ESTO DEBERÍA ARMARSE DE LA TABLA DE NIVELES PARA NO TENER QUE RECORDAR AJUSTARLO MANUALMENTE EN ADICIÓN DE CAMPOS #NEW
    // ESTO SON LOS PASOS DEL REGISTRO PARA SABER A DONDE REINICIARLO
    //ARREGLO CON CAMPOS DE CADA PASO PERSON
    $questionperson = array(
        "1"=>"declaration,fname,flastname,doctype,doc,countryid,phone,venezuelan",
        "2"=>"company,doccountryid,docissue,docexpiry,gender,maritalstatus,american,profession,economicactivity,independentdealer,ocupation,politicallyexposed,regionid,cityid,street,postalcode,american",
        "3"=>"anualincome,patrimony",
        "4"=>"qtymonthlyop,amountmonthlyop,prefertypeop,economicrelation"
    );
    $uploadsperson = array("1"=>"1,2","2"=>"9","4"=>"8,3");
    $maxstepperson = 5;
    
    //ARREGLO CON CAMPOS DE CADA PASO COMPANY
    $questioncompany = array(
        "1"=>"ctype,doc,name,comercialname,venezuelan,phone,website",
        "2"=>"creationdate,doccountryid,docregionid,doccityid,postalcode",
        "3"=>"partners,reppartner",
        "4"=>"economicactivity,anualincome,patrimony",
        "5"=>"declaration",        
        "6"=>"countryid,regionid,cityid,street,domicile,branchoffices",
        "7"=>"qtymonthlyop,prefertypeop,amountmontlyop,economicrelation"
    );
    $uploadscompany = array("5"=>"4,5,6,7","6"=>"9","7"=>"10");
    $questionpartners = array("3"=>"name,doc,phone,politicallyexposed,affiliationbody,positionheld,pepcountryid,peprelatedid");
    $maxstepcompany = 8;
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 27))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    //Consultamos si el usuario existe
    $sql = "SELECT id, type FROM users".
    "       WHERE id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $userdata = $rs->fetch_assoc();
    
    if($userdata["id"] == null){
        badEnd("204", array("msg"=>"Registro no encontrado"));
    }
    //Arreglo con los id de imagenes que tenemos
    $arruploadids = array();
    
    //Si recibimos los id de los archivos aprobados, ejecutamos el query
    if(isset($_GET["approveduploadids"]) && $_GET["approveduploadids"] != ""){
        $approveduploads = explode("-",$_GET["approveduploadids"]);
        
        //A cada id se le coloca a validated el valor 1
        foreach($approveduploads as $approvedupload){
            $sql = "UPDATE useruploads SET".
            "       validated = 1 ".
            "       WHERE prefuploadid = ".$approvedupload.
            "       AND userid = ".$id;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            array_push($arruploadids, $approvedupload);
            
            if($db->affected_rows > 0){
                $isAcepted = 1;
                $out->msg [] = "testing 1";
            }
        }
    }
    
    //Si recibimos los id de los archivos rechazados, ejecutamos el query
    if(isset($_GET["rejecteduploadids"]) && $_GET["rejecteduploadids"] != ""){
        $rejecteduploads = explode("-",$_GET["rejecteduploadids"]);
        
        //Validamos el tipo de usuario para determinar el paso
        foreach($rejecteduploads as $rejectedupload){
            if($userdata["type"] == 1){
                foreach($uploadsperson as $index => $uploadperson){
                    $uploadidsperson = explode(",",$uploadperson);
                    foreach($uploadidsperson as $uploadid){
                        if($rejectedupload == $uploadid){
                            $maxstepperson = $index;
                            break;
                        }
                    }
                }
            }else if($userdata["type"] == 2){
                foreach($uploadscompany as $index => $uploadcompany){
                    $uploadidscompany = explode(",",$uploadcompany);
                    foreach($uploadidscompany as $uploadid){
                        if($rejectedupload == $uploadid){
                            $maxstepcompany = $index;
                            break;
                        }
                    }
                }
            }
            
            $sql = "UPDATE useruploads SET".
            "       validated = -1 ".
            "       WHERE prefuploadid = ".$rejectedupload.
            "       AND userid = ".$id;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            array_push($arruploadids, $rejectedupload);
            
            if($db->affected_rows > 0){
                $isRejected = 1;
                $out->msg [] = "testing 2";
            }
        }
    }
    
    //Consultamos todos los id del usuario
    $sql = "SELECT * FROM useruploads".
    "       WHERE userid = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    while($row = $rs->fetch_assoc()){
        $isNot = false;
        
        foreach($arruploadids as $uploadid){
            if($uploadid == $row["prefuploadid"]){
                $isNot = true;
            }
        }
        
        if(!$isNot){
            $sql = "UPDATE useruploads SET".
            "       validated = 0 ".
            "       WHERE prefuploadid = ".$row["prefuploadid"].
            "       AND userid = ".$id;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
        }
    }
    
    //Si recibimos los campos aprobados de la persona, guardamos la cadena completa
    if(isset($_GET["approved"])){
        
        if($userdata["type"] == 1){
            
            // Obtenemos el string con los campos
            $sql = "SELECT approved, doc, doctype FROM userpersons WHERE usrid = ".$id;
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $rowUserTmp = $res->fetch_assoc();
            
            if(strpos($_GET['approved'], ',doc,')){
                // Validamos que no exista la cedula que se esta validando en otro usuario
                $sql = "SELECT usrid, fname FROM userpersons ".
                "       WHERE doc = '".$rowUserTmp["doc"]."'".
                "       AND doctype = ".$rowUserTmp["doctype"].
                "       AND usrid != ".$id.
                "       AND (rejected NOT LIKE '%,doc,%' AND rejected NOT LIKE '%doc%') ";
                if (!$rs=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                
                $validateDoc = $rs->fetch_assoc();
                
                // Retornamos 409 cuando doc esta duplicado
                if($validateDoc["usrid"] != null){
                    badEnd("409", array("msg"=>"Documento de identificacion duplicado","usr"=>$validateDoc));
                }
            }
            
            $sql = "UPDATE userpersons SET".
            "       approved = '".$_GET["approved"]."'".
            "       WHERE usrid = ".$id;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            if($db->affected_rows > 0 && strlen($rowUserTmp['approved']) < strlen($_GET['approved']) ){
                $isAcepted = 1;
                $out->msg [] = "testing 3";
            }
                
        }else if($userdata["type"] == 2){
            
            // Obtenemos el string con los campos
            $sql = "SELECT approved, doc FROM usercompanies WHERE usrid = ".$id;
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $rowUserTmp = $res->fetch_assoc();
            
            if(strpos($_GET['approved'], ',doc,')){
                // Validamos que no exista la cedula que se esta validando en otro usuario
                $sql = "SELECT usrid FROM usercompanies ".
                "       WHERE doc = '".$rowUserTmp["doc"]."'".
                "       AND usrid != ".$id.
                "       AND (rejected NOT LIKE '%,doc,%' AND rejected NOT LIKE '%doc%') ";
                if (!$rs=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                
                $validateDoc = $rs->fetch_assoc();
                
                // Retornamos 409 cuando doc esta duplicado
                if($validateDoc["usrid"] != null){
                    badEnd("409", array("msg"=>"Documento de identificacion duplicado","usr"=>$validateDoc));
                }
            }
            
            $sql = "UPDATE usercompanies SET".
            "       approved = '".$_GET["approved"]."'".
            "       WHERE usrid = ".$id;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            if($db->affected_rows > 0  && strlen($rowUserTmp['approved']) < strlen($_GET['approved']) ){
                $isAcepted = 1;
                $out->msg [] = "testing 4";
            }    
        }
    }
    
    if(isset($_GET["rejected"])){
        
        if($userdata["type"] == 1){
            
            $docSend = false;
            
            foreach($questionperson as $index => $questionlabel){
                $questionlabelarr = explode(",",$questionlabel);
                $rejectedfields = explode(",",$_GET["rejected"]);
                
                foreach($rejectedfields as $fieldreject){
                    if($fieldreject == "doc"){
                        $out->testing [] = $fieldreject;
                        $docSend = true;
                    }
                    foreach($questionlabelarr as $labelquestion){
                        if(!empty($fieldreject)){
                            if(strpos($fieldreject, $labelquestion) !== false && $maxstepperson > $index){
                                $maxstepperson = $index;
                            }
                        }
                    }
                }
            }
            
            // Obtenemos el string con los campos
            $sql = "SELECT rejected FROM userpersons WHERE usrid = ".$id;
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $rowUserTmp = $res->fetch_assoc();
            
            if($docSend){
                // Validamos que no exista la cedula que se esta validando en otro usuario
                $sql = "UPDATE userpersons SET ".
                "       doc = '' ".
                "       WHERE usrid = ".$id;
                if (!$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
            }
            
            $sql = "UPDATE userpersons SET".
            "       rejected = '".$_GET["rejected"]."', ".
            "       step = ". $maxstepperson .
            "       WHERE usrid = ".$id;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            if($db->affected_rows > 0 && strlen($rowUserTmp['rejected']) < strlen($_GET['rejected']) ){
                $isRejected = 1;
                $out->msg [] = "testing 5";
            }
    
        }else if($userdata["type"] == 2){
            
            $docSend = false;
            
            foreach($questioncompany as $index => $questionlabel){
                $questionlabelarr = explode(",",$questionlabel);
                $rejectedfields = explode(",",$_GET["rejected"]);
                
                foreach($rejectedfields as $fieldreject){
                    
                    if($fieldreject == "doc"){
                        $out->testing [] = $fieldreject;
                        $docSend = true;
                    }
                    
                    foreach($questionlabelarr as $labelquestion){
                        if(!empty($fieldreject)){
                            if(strpos($fieldreject, $labelquestion) !== false && $maxstepcompany > $index){
                                $maxstepcompany = $index;
                            }
                        }
                    }
                }
            }
            
            // Obtenemos el string con los campos
            $sql = "SELECT rejected FROM usercompanies WHERE usrid = ".$id;
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $rowUserTmp = $res->fetch_assoc();
            
            if($docSend){
                // Validamos que no exista la cedula que se esta validando en otro usuario
                $sql = "UPDATE usercompanies SET ".
                "       doc = '' ".
                "       WHERE usrid = ".$id;
                if (!$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
            }
            $sqlU = "SELECT *".
                    "       FROM usercompanies".
                    "       WHERE usrid = ".$userdata["id"];
                    if (!$rsU=$db->query($sqlU))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                    $userdetail = $rsU->fetch_assoc();

            $sql = "UPDATE usercompanies SET".
            "       rejected = '".$_GET["rejected"]."',".
            "       step = ". $maxstepcompany .
            "       WHERE usrid = ".$id;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            if($db->affected_rows > 0 && strlen($rowUserTmp['rejected']) < strlen($_GET['rejected'])){
                $isRejected = 1;
                $out->msg [] = "testing 6";
            }
        }
        
    }
    
    //Si recibimos los id de las cuentas, ejecutamos el query
    if(isset($_GET["accountids"]) && $_GET["accountids"] != ""){
        $accountids = explode("-",$_GET["accountids"]);
        $approved = "";
        $rejected = "";
        foreach($accountids as $indexprin => $accountid){
            if(isset($_GET["account".($indexprin + 1)]) && $_GET["account".($indexprin + 1)] != ""){
                $validRejected = explode("|", $_GET["account".($indexprin + 1)]);
                foreach($validRejected as $indexsecu => $field){
                    $fields = explode(",", $field);
                    if($indexsecu == 0){
                        $approved = "";
                        foreach($fields as $validatedField){
                            if($validatedField != ""){
                                $approved .= "".$validatedField.",";
                            }
                        }
                    }else if($indexsecu == 1){
                        $rejected = "";
                        foreach($fields as $rejectedField){
                            if($rejectedField != ""){
                                $rejected .= "".$rejectedField.",";
                            }
                        }
                    }
                }
                
                // Obtenemos los datos de la cuenta del usuario
                $sql = "SELECT * FROM accounts ".
                "       WHERE id = ".$accountid;
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $rowAccTmp = $res->fetch_assoc();
                
                //Actualizamos los datos de la cuenta
                $sql = "UPDATE accounts SET ".
                "       approved = ".($approved == "" ? "NULL" : "'".(substr($approved, 0, -1))."'").", ".
                "       rejected = ".($rejected == "" ? "NULL" : "'".(substr($rejected, 0, -1))."'")." ".
                "       WHERE id = ".$accountid;
                if (!$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                if($approved != ""){
                    if($db->affected_rows > 0 && strlen($rowAccTmp['approved']) < strlen($approved)){
                        $isAcepted = 1;
                        $out->msg [] = "testing 7";
                    }
                }
                
                if($rejected != ""){
                    if($db->affected_rows > 0 && strlen($rowAccTmp['rejected']) < strlen($rejected)){
                        $isRejected = 1;
                        $out->msg [] = "testing 8";
                    }
                }
                    
            }
        }
    }
    
    //Si recibimos los id de los socios, ejecutamos el query
    if(isset($_GET["partnerids"]) && $_GET["partnerids"] != ""){
        $partnerids = explode("-",$_GET["partnerids"]);
        $approved = "";
        $rejected = "";
        foreach($partnerids as $indexprin => $partnerid){
            if(isset($_GET["partner".($indexprin + 1)]) && $_GET["partner".($indexprin + 1)] != ""){
                $validRejected = explode("|", $_GET["partner".($indexprin + 1)]);
                foreach($validRejected as $indexsecu => $field){
                    $fields = explode(",", $field);
                    if($indexsecu == 0){
                        $approved = "";
                        foreach($fields as $validatedField){
                            if($validatedField != ""){
                                $approved .= "".$validatedField.",";
                            }
                        }
                    }else if($indexsecu == 1){
                        $rejected = "";
                        foreach($fields as $rejectedField){
                            if($rejectedField != ""){
                                $rejected .= "".$rejectedField.",";
                            }
                        }
                    }
                }

                //#NEW AGREGADO LA SECCIÓN DE SOCIOS NO REFRESCABA LA PANTALLA DE ATERRIZAJE
                foreach($questionpartners as $index => $questionlabel){
                    $questionlabelarr = explode(",",$questionlabel);
                    $rejectedfields = explode(",",$rejected);
                    
                    foreach($rejectedfields as $fieldreject){
                        foreach($questionlabelarr as $labelquestion){
                            if(!empty($fieldreject)){
                                if(strpos($fieldreject, $labelquestion) !== false && $maxstepcompany > $index){
                                    $maxstepcompany = $index;
                                }
                            }
                        }
                    }
                }
                $sqlU = "SELECT *".
                    "       FROM usercompanies".
                    "       WHERE usrid = ".$userdata["id"];
                    if (!$rsU=$db->query($sqlU))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                    $userdetail = $rsU->fetch_assoc();

                $sql = "UPDATE usercompanies SET".
                "       step = ".($maxstepcompany).
                "       WHERE usrid = ".$id;
                if (!$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                
                
                
                // Obtenemos los datos del socio
                $sql = "SELECT * FROM usercompanypartners WHERE id = ".$partnerid;
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $rowPartnerTmp = $res->fetch_assoc();
                
                //Actualizamos los datos de la cuenta
                $sql = "UPDATE usercompanypartners SET ".
                "       approved = ".($approved == "" ? "NULL" : "'".(substr($approved, 0, -1))."'").", ".
                "       rejected = ".($rejected == "" ? "NULL" : "'".(substr($rejected, 0, -1))."'")." ".
                "       WHERE id = ".$partnerid;
                if (!$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                if($approved != ""){
                    if($db->affected_rows > 0 && strlen($rowPartnerTmp['approved']) < strlen($approved)){
                        $isAcepted = 1;
                        $out->msg [] = "testing 8";
                    }
                }
                
                if($rejected != ""){
                    if($db->affected_rows > 0 && strlen($rowPartnerTmp['rejected']) < strlen($rejected)){
                        $isRejected = 1;
                        $out->msg [] = "testing 9";
                    }
                }
                    
            }
        }
    }
    
    $out->id = (int)$id;
    
    //Consultamos los datos de el usuario
    $sql = "SELECT id AS userid, ".
    "       type AS usertype ".
    "       FROM users WHERE id = ".$id;
    if(!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $userdata = $rs->fetch_assoc();
    
    // Luego de que se validaron los campos, validamos los campos por completo para verificar su estado con campos pendientes
    //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"]);
        
        $modified = false;
        reqverifyuser($userdata['userid'], $db, true);
        
        $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' && $index != 'doctype' 
                && $index != 'ctype'&& $index != 'partners'
            ){
                $out->conquienfue = $result." | ".$index."| 1";
                if(validateField($index, $rejecteds, $approveds) == 0 && $result != '' && $result != null){
                    
                    if($validPolitical){
                        $modified = true;
                        $out->conquienfue = $result." | ".$index."| 2";
                        reqverifyuser($userdata['userid'], $db, true);
                        break;
                    }else{
                        if($index != 'affiliationbody' && $index != 'positionheld' && $index != 'pepcountryid' && $index != 'peprelatedid'){
                            $modified = true;
                            $out->conquienfue = $result." | ".$index."| 3";
                            reqverifyuser($userdata['userid'], $db, true);
                            break;
                        }
                    }
                    
                }  
            }
        }
        
        
        //Si el usuario no posee un 0, validamos ahora las iamgenes
        if(!$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){
                    $modified = true;
                    reqverifyuser($userdata['userid'], $db, true);
                    break;
                }
            }
        }
        
        //Si el usuario esta validado, recorremos las cuentas
        if(!$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->conquienfue = $result." | ".$index;
                    if($index == 'details1' || $index == 'details2' || $index == 'details3' || $index == 'details4'){
                        
                        if($paymentmethod[$index] != null){
                            if(validateField($index, $rejecteds, $approveds) == 0 && $result != '' && $result != null){
                                $modified = true;
                                $out->conquienfue = $result." | ".$index;
                                reqverifyuser($userdata['userid'], $db, true);
                                break;
                            }
                        }
                    }
                }
            }
        }
        
    
        if($userdata["usertype"] == 2 && !$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){
                        $modified = false;
                        reqverifyuser($userdata['userid'], $db, false);
                        $i += 99999;
                    }else if(validateField($partnerfield[$i], $rejecteds, $approveds) == 0){
                        $modified = true;
                        $out->conquienfue [] = "se cayowey";
                        reqverifyuser($userdata['userid'], $db, true);
                        $i += 99999;
                    }    
                }
            }
        }
    }
    
    // Obtenemos el nombre del usuario
    $sql = "SELECT users.usr AS email, IF(userpersons.fname IS NULL, usercompanies.name, CONCAT(userpersons.fname,' ',userpersons.flastname)) AS name, ".
    "       IF(users.type = 1, userpersons.phone, usercompanies.phone) AS phone, " .
    "       users.level AS level, users.lang AS lang ".
    "       FROM users ".
    "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
    "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
    "       WHERE id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $userdata = $rs->fetch_assoc(); 
    
    //auditoria
    setAudit($db, "USUARIOS APP", $sessionid, "CMS", "Se validaron datos del usuario ".$userdata['name']);
    
    if($isRejected == 1){
        
        // Consultamos los datos del mensaje
        $sql = "SELECT * FROM cmsmessages WHERE id = 2";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $data = $rs->fetch_assoc();
        
        // Validamos que el usuario tenga las notificaciones activas
        $sql = "SELECT * FROM usermessages ".
        "       WHERE categoryid = ".$data['category'].
        "       AND usrid = ".$id;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $userPref = $rs->fetch_assoc();
        
        if($userPref['email'] == null || $userPref['email'] == 1){
            $subject = $userdata['lang'] == 'esp' ? $data['name_esp'] : $data['name_eng'];
            $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
            $body = "<div class='emailBox'>".
            "           <img class='afxLogo' src='".$homeurlCMS."./settings/img/logo-email.png'/>".
            "           <div class='mainBox'>".
            "               <h1 class='titleEmail'>".
            "                   ".($userdata['lang'] == "esp" ? "Hola" : "Hello")." ".$userdata['name'].
            "               </h1>".
            "               <p class='msgEmail'>".
            "                   ".($userdata['lang'] == 'esp' ? $data['dsc_esp'] : $data['dsc_eng']).
            "               </p>".
            "           </div>".
            "           <p class='copy'>".$footerEmails."</p>".
            "       </div>";
            
            $body = templateEmail($body, $STANDAR_STYLE_EMAIL);
                    
            enviarCorreo2($fromeMail, strtolower($userdata['email']), $subject, $body);
        }
        // Se valida la preferenca del mensaje y se envía según el idioma
        if($userPref['sms'] == null || $userPref['sms'] == 1){
            $msg = $userdata['lang'] == 'esp' ? $data['sms_esp'] : $data['sms_eng'];
            enviarSMS($userdata['phone'], $msg);
        }
        
        if($userPref['system'] == null || $userPref['system'] == 1){
            
            $email = '';
            $sms = '';
            
            // Si se envia por correo obtenemos el correo del usuario
            if($userPref['email'] == null || $userPref['email'] == 1){
                $sql = "SELECT usr ".
                "       FROM users ".
                "       WHERE id = ".$id;
                if (!$resPref=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $rowPrefCom = $resPref->fetch_assoc();
                
                $email = $rowPrefCom['usr'];
            }
            
            // SI se envia por sms, obtenemos el numero del usuario
            if($userPref['sms'] == null || $userPref['sms'] == 1){
                $sql = "SELECT IF(users.type = 1, userpersons.phone, usercompanies.phone) AS phone ".
                "       FROM users ".
                "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
                "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
                "       WHERE users.id = ".$id;
                if (!$resPref=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $rowPrefCom = $resPref->fetch_assoc();
                
                $sms = $rowPrefCom['phone'];
                
            }
                            
            // Enviamos el mensaje por la mensajeria interna
            $msg = ( $userdata['lang'] == 'esp' ? $data['dsc_esp'] : $data['dsc_eng']);
            saveInternalMsg($db, $msg, $id, $email, $sms);
        }
    }
    
    /*
    if($isAcepted == 1){
        // Consultamos los datos del mensaje
        $sql = "SELECT * FROM cmsmessages WHERE id = 3";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $data = $rs->fetch_assoc();
        
        // Validamos que el usuario tenga las notificaciones activas
        $sql = "SELECT * FROM usermessages ".
        "       WHERE categoryid = ".$data['category'].
        "       AND usrid = ".$id;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $userPref = $rs->fetch_assoc();
        
        if($userPref['email'] == null || $userPref['email'] == 1){
            $subject = $userdata['lang'] == 'esp' ? $data['name_esp'] : $data['name_eng'];
            $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
            $body = "<div class='emailBox'>".
            "           <img class='afxLogo' src='".$homeurlCMS."./settings/img/logo-email.png'/>".
            "           <div class='mainBox'>".
            "               <h1 class='titleEmail'>".
            "                   ".($userdata['lang'] == "esp" ? "Hola" : "Hello")." ".$userdata['name'].
            "               </h1>".
            "               <p class='msgEmail'>".
            "                   ".($userdata['lang'] == 'esp' ? $data['dsc_esp'] : $data['dsc_eng']).
            "               </p>".
            "           </div>".
            "           <p class='copy'>".$footerEmails."</p>".
            "       </div>";
            
            $body = templateEmail($body, $STANDAR_STYLE_EMAIL);
                    
            enviarCorreo2($fromeMail, strtolower($userdata['email']), $subject, $body);
        }
        // Se valida la preferenca del mensaje y se envía según el idioma
        if($userPref['sms'] == null || $userPref['sms'] == 1){
            $msg = $userdata['lang'] == 'esp' ? $data['sms_esp'] : $data['sms_eng'];
            enviarSMS($userdata['phone'], $msg);
        }
        
        if($userPref['system'] == null || $userPref['system'] == 1){
            
            $email = '';
            $sms = '';
            
            // Si se envia por correo obtenemos el correo del usuario
            if($userPref['email'] == null || $userPref['email'] == 1){
                $sql = "SELECT usr ".
                "       FROM users ".
                "       WHERE id = ".$id;
                if (!$resPref=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $rowPrefCom = $resPref->fetch_assoc();
                
                $email = $rowPrefCom['usr'];
            }
            
            // SI se envia por sms, obtenemos el numero del usuario
            if($userPref['sms'] == null || $userPref['sms'] == 1){
                $sql = "SELECT IF(users.type = 1, userpersons.phone, usercompanies.phone) AS phone ".
                "       FROM users ".
                "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
                "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
                "       WHERE users.id = ".$id;
                if (!$resPref=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $rowPrefCom = $resPref->fetch_assoc();
                
                $sms = $rowPrefCom['phone'];
                
            }
                            
            // Enviamos el mensaje por la mensajeria interna
            $msg = ( $userdata['lang'] == 'esp' ? $data['dsc_esp'] : $data['dsc_eng']);
            saveInternalMsg($db, $msg, $id, $email, $sms);
        }
    }
    */
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /*  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;
    }
?>