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

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","id");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out = new stdClass();
    $sessionid = $_GET["sessionid"];
    $id = $_GET["id"];
    
    //ARREGLO CON CAMPOS DE CADA PASO PERSON
    $questionperson = array(
        "1"=>"fname,sname,flastname,slastname,doc,doctype,doccountryid,docissue,docexpiry,gender,maritalstatus,birthdate,birthcountryid,phone,american,venezuelan",
        "2"=>"countryid,regionid,cityid,street,domicile,postalcode",
        "3"=>"ocupation,economicactivity,politicallyexposed,independentdealer,company,anualincome,patrimony,profession,affiliationbody,positionheld,pepcountryid,peprelatedid",
        "5"=>"qtymonthlyop,prefertypeop,amountmonthlyop,economicrelation"
    );
    $uploadsperson = array("4"=>"1,2,3,8,9");
    $maxstepperson = 7;
    
    //ARREGLO CON CAMPOS DE CADA PASO COMPANY
    $questioncompany = array(
        "1"=>"ctype,doc,name,comercialname,creationdate,doccountryid,docregionid,doccityid,postalcode,phone,website,partners,venezuelan",
        "3"=>"countryid,regionid,cityid,street,domicile,branchoffices",
        "4"=>"economicactivity,anualincome,patrimony,politicallyexposed",
        "6"=>"qtymonthlyop,prefertypeop,amountmontlyop,economicrelation"
    );
    $uploadscompany = array("5"=>"4,5,6,7,9,10");
    $questionpartners = array("2"=>"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"=>$db->error));
    
    $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"=>$db->error));
                
            array_push($arruploadids, $approvedupload);
        }
    }
    
    //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;
                        }
                    }
                }
            }else if($userdata["type"] == 2){
                foreach($uploadscompany as $index => $uploadcompany){
                    $uploadidscompany = explode(",",$uploadcompany);
                    foreach($uploadidscompany as $uploadid){
                        if($rejectedupload == $uploadid){
                            $maxstepcompany = $index;
                        }
                    }
                }
            }
            
            $sql = "UPDATE useruploads SET".
            "       validated = -1 ".
            "       WHERE prefuploadid = ".$rejectedupload.
            "       AND userid = ".$id;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
                
            array_push($arruploadids, $rejectedupload);
        }
    }
    
    //Consultamos todos los id del usuario
    $sql = "SELECT * FROM useruploads".
    "       WHERE userid = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    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"=>$db->error));
        }
    }
    
    //Si recibimos los campos aprobados de la persona, guardamos la cadena completa
    if(isset($_GET["approved"])){
        
        if($userdata["type"] == 1){
            
            $sql = "UPDATE userpersons SET".
            "       approved = '".$_GET["approved"]."'".
            "       WHERE usrid = ".$id;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
                
        }else if($userdata["type"] == 2){
            
            $sql = "UPDATE usercompanies SET".
            "       approved = '".$_GET["approved"]."'".
            "       WHERE usrid = ".$id;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
                
        }
    }
    
    if(isset($_GET["rejected"])){
        
        if($userdata["type"] == 1){
            
            foreach($questionperson as $index => $questionlabel){
                $questionlabelarr = explode(",",$questionlabel);
                $rejectedfields = explode(",",$_GET["rejected"]);
                
                foreach($rejectedfields as $fieldreject){
                    foreach($questionlabelarr as $labelquestion){
                        if(!empty($fieldreject)){
                            if(strpos($fieldreject, $labelquestion) !== false && $maxstepperson > $index){
                                $maxstepperson = $index;
                            }
                        }
                    }
                }
            }
            
            $sql = "UPDATE userpersons SET".
            "       rejected = '".$_GET["rejected"]."',".
            "       step = ".$maxstepperson." ".
            "       WHERE usrid = ".$id;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
    
        }else if($userdata["type"] == 2){
            
            foreach($questioncompany as $index => $questionlabel){
                $questionlabelarr = explode(",",$questionlabel);
                $rejectedfields = explode(",",$_GET["rejected"]);
                
                foreach($rejectedfields as $fieldreject){
                    foreach($questionlabelarr as $labelquestion){
                        if(!empty($fieldreject)){
                            if(strpos($fieldreject, $labelquestion) !== false && $maxstepcompany > $index){
                                $maxstepcompany = $index;
                            }
                        }
                    }
                }
            }
            
            $sql = "UPDATE usercompanies SET".
            "       rejected = '".$_GET["rejected"]."',".
            "       step = ".$maxstepcompany." ".
            "       WHERE usrid = ".$id;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>$db->error));

        }
        
    }
    
    //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.",";
                            }
                        }
                    }
                }
                
                //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"=>$db->error));
                    
            }
        }
    }
    
    //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.",";
                            }
                        }
                    }
                }
                
                //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"=>$db->error));
                    
            }
        }
    }
    
    $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"=>$db->error));
        
    $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"=>$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"]);
        
        $modified = false;
        
        reqverifyuser($userdata['userid'], $db, 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'){
                if(validateField($index, $rejecteds, $approveds) == 0 && $result != '' && $result != null){
                    
                    if($validPolitical){
                        $modified = true;
                        reqverifyuser($userdata['userid'], $db, true);
                        break;
                    }else{
                        if($index != 'affiliationbody' && $index != 'positionheld' && $index != 'pepcountryid' && $index != 'peprelatedid'){
                            $modified = true;
                            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"=>$db->error));
                
            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"=>$db->error));
                
            while($accountdetail = $rsA->fetch_assoc()){    
                $rejecteds = explode(",",$accountdetail["rejected"]);
                $approveds = explode(",",$accountdetail["approved"]);
            
                foreach($accountdetail as $index => $result){
                
                    if($index == 'details1' || $index == 'details2' || $index == 'details3' || $index == 'details4'){
                    
                        if(validateField($index, $rejecteds, $approveds) == 0 && $result != '' && $result != null){
                            $modified = true;
                            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"=>$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){
                        $modified = false;
                        reqverifyuser($userdata['userid'], $db, false);
                        $i += 99999;
                    }else if(validateField($partnerfield[$i], $rejecteds, $approveds) == 0){
                        $modified = true;
                        reqverifyuser($userdata['userid'], $db, true);
                        $i += 99999;
                    }    
                }
            }
        }
    }
    
    // Obtenemos el nombre del usuario
    $sql = "SELECT IF(userpersons.fname IS NULL, usercompanies.name, CONCAT(userpersons.fname,' ',userpersons.flastname)) AS name, ".
    "       users.level AS level ".
    "       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"=>$db->error));
        
    $userdata = $rs->fetch_assoc(); 
    
    //auditoria
    setAudit($db, "USUARIOS APP", $sessionid, "CMS", "Se validaron datos del usuario ".$userdata['name']);
    
    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;
    }
?>
