<?php
// app/api/users/updatecompany

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid");
    if (!parametrosValidos($_POST, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    //Definicion de variables y almacenamiento de valores enviados por GET
    $out= new stdClass;
    $sessionid = $_POST["sessionid"];
    
    //Validamos la session
    isSessionValid($db, $sessionid);
    
    //Obtenemos los datos del usuario para saber si necesitamos actualizar el type
    $sql = "SELECT id, usr, sessionid, type FROM users WHERE sessionid='".$sessionid."'";
    if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error)); 
            
    $userdata = $rs->fetch_assoc();
    
    //Validamos que sea null para actualizar
    if($userdata["type"] == null){
        $sql = "UPDATE users".
        "       SET type=2".
        "       WHERE sessionid='".$sessionid."'";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
    }else if($userdata["type"] == 1){
        //Cambio de tipo
        //Se elimina el de la otra tabla
        $sql = "DELETE FROM userpersons WHERE usrid='".$userdata["id"]."'";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>$db->error)); 
        
        //Se modifica el tipo de la tabla principal
        $sql = "UPDATE users".
        "       SET type=2".
        "       WHERE sessionid='".$sessionid."'";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        //badEnd("304", array("msg"=>"No se pudo modificar"));
    }
    
    //Consultamos para saber si existe ya un perfil para la empresa
    $sql = "SELECT usrid FROM usercompanies WHERE usrid=".$userdata["id"];
    if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
    $validconsult = $rs->fetch_assoc();
    
    /* Si el usuario no posee datos en userpersons insertamos un nuevo registro.
    *  En caso de que ya exista, se actualiza su informacion
    */
    if($validconsult["usrid"] == null){
        
        if(isset($_POST["doc"])){
            //Consultamos para verificar que no existan registros con su cedula
            $sql = "SELECT usrid FROM usercompanies ".
            "       WHERE doc = '".$_POST["doc"]."'";
            if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
            $row = $rs->fetch_assoc();
        
            // Retornamos 409 cuando doc esta duplicado
            if($row["usrid"] != null){
                badEnd("409", array("msg"=>"Documento de identificacion duplicado"));
            }
        }
        
        //Insertamos el usuario debido a que no cuenta con registro
        $sql = "INSERT INTO usercompanies(".validValues().")".
        "       VALUES (".createInsert($userdata["id"]).")";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        // Retornamos el id que fue insertado
        $out->id =(int) $userdata["id"];
        
        reqverifyuser($userdata["id"], $db, true);
    }else{
        //Consultamos el usuario para verificar que existe el registro
        $sql = "SELECT usrid, rejected, approved FROM usercompanies WHERE usrid=".$userdata["id"];
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $uservalid = $rs->fetch_assoc();
        
        // Retornamos 204 cuando la busqueda no obtiene resutados
        if($uservalid["usrid"] == null){
            badEnd("204", array("msg"=>"No se encuentra el registro "));
        }
        
        if(isset($_POST["doc"])){
            //Consultamos para verificar que no existan registros con su cedula
            $sql = "SELECT COUNT(usrid) AS qty FROM usercompanies ".
            "       WHERE doc = '".$_POST["doc"]."'".
            "       AND usrid != ".$userdata["id"];
            if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
            $row = $rs->fetch_assoc();
        
            // Retornamos 409 cuando doc esta duplicado
            if($row["qty"] > 0){
                badEnd("409", array("msg"=>"Documento de identificacion duplicado"));
            }
        }
            
        //Actualizamos el usuario
        $sql = "UPDATE usercompanies".
        "       SET".
        "       ".createUpdate($uservalid["rejected"], $userdata["id"], $db).
        "       WHERE usrid =".$userdata["id"];
        if (!$db->query($sql))
            badEnd("500", array("msg"=>$db->error.$sql));
            
        if ($db->affected_rows == 0){
            badEnd("304", array("msg"=>"No se pudo modificar"));
        }
        
        //Actualizamos que acepto la declaracion si llego al ultimo paso
        if(validateUpdate("step") && $_POST["step"] + 1 == 8){
            $sql = "UPDATE users SET ".
            "       declaration = NOW() ".
            "       WHERE id = ".$userdata["id"].
            "       AND declaration IS NULL";
            if (!$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
        }
            
        // Retornamos el id que fue insertado
        $out->id =(int) $userdata["id"];
        
        // Obtenemos el nombre del usuario
        $sql = "SELECT IF(userpersons.fname IS NULL, usercompanies.name, CONCAT(userpersons.fname,' ',userpersons.flastname)) AS name ".
        "       FROM users ".
        "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
        "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
        "       WHERE sessionid = '".$sessionid."'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $userdataaudit = $res->fetch_assoc();
        
        //auditoria
        setAudit($db, "USUARIOS APP", $sessionid, "APP", "El usuario juridico ".$userdataaudit['name']." actualizó sus datos");
    }
    
    //Creacion de carpeta(si no existe) y agrego de imagenes de verificacion
    if(isset($_POST["uploadids"]) && $_POST["uploadids"] != ""){
        //Creamos la direccion del folder
        $urlfolder = "../uploads/users/".$userdata["id"];
        
        //Creamos el directorio en caso de que no exista
        if(!is_dir($urlfolder)){
            mkdir($urlfolder, 0777, true);
        }
        
                
        $filesid = explode("-",$_POST["uploadids"]);
        
        $filesfromdir = glob($urlfolder.'/*');
        
        $arrlenstring = sizeof($filesid);
        
        $arrlendir = sizeof($filesfromdir);
        
        //Si no hay archivos significa que deben ser ingresados por primera vez
        if($arrlendir == 0){
            foreach($filesid as $fileid){
                //Recibimos el valor por el string que se envio en uploadids
                $fileuploaded = $_FILES[strval($fileid)];
                $ext = pathinfo($fileuploaded['name'], PATHINFO_EXTENSION);
                
                //Movemos el FILE del directorio temporal al del sistema para su uso
                if(move_uploaded_file($fileuploaded["tmp_name"], $urlfolder . "/" . $fileid . "." . $ext)){
                    //Guardamos los datos del FILE en la BD para su busqueda
                    $sql = "INSERT INTO useruploads(userid,prefuploadid,filetype,validated)".
                    "       VALUES(".$userdata["id"].",".$fileid.",'".$fileuploaded["type"]."',0)";
                    if (!$rs=$db->query($sql))
                        badEnd("500", array("msg"=>$db->error));
                        
                    reqverifyuser($userdata["id"], $db, true);
                }
            }
        }else{
            //Recorremos todos los files para validar cuales existen en el string y cuales no
            foreach($filesfromdir as $filefromdir){
            
                $extfromdir = pathinfo($filefromdir, PATHINFO_EXTENSION);
                $filename = basename($filefromdir,".".$extfromdir);

                $fileinString = 0;
                for($i = 0; $i < $arrlenstring; $i++){
                    if($filename == $filesid[$i]){
                        $fileinString = 1;
                    }
                }
                
                /*  Si el fileinString es igual a 0 significa que el FILE no se encuentra 
                *   en el archivo y por ende se elimina del fichero y de la BD
                */
                if($fileinString == 0){
                    //Eliminamos registro
                    $sql = "DELETE FROM useruploads WHERE".
                    "       userid=".$userdata["id"]." AND".
                    "       prefuploadid = ".$filename;
                    if (!$db->query($sql))
                        badEnd("500", array("msg"=>$db->error));
                    
                    
                    //Eliminamos fichero
                    unlink($filefromdir);
                
                }
            }
            
            //Recorremos nuevamente el array de string para validar si hay files nuevos para actualizar o ingresar
            foreach($filesid as $fileid){
                
                //Si el file fue enviado debe guardarse/actualizarse
                if(isset($_FILES[strval($fileid)])){
                    
                    //Si el archivo ya existia y quiere ser actualizado se elimina
                    $filewithsamename = glob($urlfolder . "/" . $fileid . ".*");
                    foreach ($filewithsamename as $file) {
                        unlink($file);
                    }
                    
                    $fileuploaded = $_FILES[strval($fileid)];
                    $ext = pathinfo($fileuploaded['name'], PATHINFO_EXTENSION);
                
                    //Movemos el FILE del directorio temporal al del sistema para su uso
                    if(move_uploaded_file($fileuploaded["tmp_name"], $urlfolder . "/" . $fileid . "." . $ext)){
                        
                        //Validamos que el registro en la BD
                        $sql = "SELECT userid, prefuploadid FROM useruploads".
                        "       WHERE userid = ".$userdata["id"]." AND".
                        "       prefuploadid = ".$fileid;
                        if (!$result=$db->query($sql))
                            badEnd("500", array("msg"=>$db->error));
                            
                        $imagedata = $result->fetch_assoc();
                        
                        //Si no existe, se inserta un nuevo registro
                        if($imagedata["userid"] == null){
                            $sql = "INSERT INTO useruploads(userid,prefuploadid,filetype,validated)".
                            "       VALUES(".$userdata["id"].",".$fileid.",'".$fileuploaded["type"]."',0)";
                            if (!$rs=$db->query($sql))
                                badEnd("500", array("msg"=>$db->error));
                            
                            reqverifyuser($userdata["id"], $db, true);
                        }else{
                            /*Si no, actualizamos el ya existente cambiando el type(si es necesario) y 
                            * colocamos el validated 0 para que el nuevo archivo sea validado
                            */
                            $sql = "UPDATE useruploads SET".
                            "       filetype = '".$fileuploaded["type"]."', ".
                            "       validated = 0".
                            "       WHERE".
                            "       userid = ".$userdata["id"]." AND".
                            "       prefuploadid = ".$fileid;
                            if (!$rs=$db->query($sql))
                                badEnd("500", array("msg"=>$db->error));
                            
                            reqverifyuser($userdata["id"], $db, true);
                        }
                    }
                }
            }
        }
    }else if(isset($_POST["uploadids"]) && $_POST["uploadids"] == ""){
        //Creamos la direccion del folder
        $urlfolder = "../uploads/users/".$userdata["id"];
        
        //Creamos el directorio en caso de que no exista
        if(!is_dir($urlfolder)){
            mkdir($urlfolder, 0777, true);
        }
        
        $filesfromdir = glob($urlfolder.'/*');
        
        //Recorremos todos los files para eliminarlo
        foreach($filesfromdir as $filefromdir){
            
            $extfromdir = pathinfo($filefromdir, PATHINFO_EXTENSION);
            $filename = basename($filefromdir,".".$extfromdir);
                
            //Eliminamos registro
            $sql = "DELETE FROM useruploads WHERE".
            "       userid=".$userdata["id"]." AND".
            "       prefuploadid = ".$filename;
            if (!$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
                    
                    
            //Eliminamos fichero
            unlink($filefromdir);
        }
    }
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /* UTILIDAD */
    function createUpdate($rejected, $userid, $db){
        
        //Consultamos los datos del usuario para verificar si cambio el campo
        $sql = "SELECT * FROM usercompanies WHERE usrid = ".$userid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $userdetails = $rs->fetch_assoc();
        $rejectedArr = explode(",",$rejected);
        $strQuery = "";
        $validator = 0;
        
        //Validamos el campo venezuelan
        if(validateUpdate("venezuelan")){
            $strQuery .= " venezuelan = ".$_POST["venezuelan"].",";
            if($userdetails["venezuelan"] != $_POST["venezuelan"]){
                $validator = validateIfExist($rejectedArr, "venezuelan");
                
                if($userdetails["venezuelan"] != $_POST["venezuelan"]){
                    if($validator == 1){
                        foreach($rejectedArr as $index => $fieldRejected){
                            if($fieldRejected == "venezuelan"){
                                reqverifyuser($userid, $db, true);
                                unset($rejectedArr[$index]);
                            }
                        }
                    }
                }
            }
        }
        
        //Validamos el campo ctype
        if(validateUpdate("companytype")){
            $strQuery .= " ctype = ".$_POST["companytype"].",";
            $validator = validateIfExist($rejectedArr, "ctype");
            
            if($userdetails["ctype"] != $_POST["companytype"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "ctype"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }   
            }
        }
        
        //Validamos el campo name
        if(validateUpdate("name")){
            $strQuery .= " name = '".$_POST["name"]."',";
            $validator = validateIfExist($rejectedArr, "name");
            
            if($userdetails["name"] != $_POST["name"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "name"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo comercialname
        if(validateUpdate("comercialname")){
            $strQuery .= " comercialname = '".$_POST["comercialname"]."',";
            $validator = validateIfExist($rejectedArr, "comercialname");
            
            if($userdetails["comercialname"] != $_POST["comercialname"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "comercialname"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo creationdate
        if(validateUpdate("creationdate")){
            $strQuery .= " creationdate = '".$_POST["creationdate"]."',";
            $validator = validateIfExist($rejectedArr, "creationdate");
            
            if(date("d/m/Y", strtotime($userdetails["creationdate"])) != date("d/m/Y", strtotime($_POST["creationdate"]))){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "creationdate"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo doc
        if(validateUpdate("doc")){
            $strQuery .= " doc = '".$_POST["doc"]."',";
            $validator = validateIfExist($rejectedArr, "doc");
            
            if($userdetails["doc"] != $_POST["doc"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "doc"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo doccountryid
        if(validateUpdate("doccountryid")){
            $strQuery .= " doccountryid = ".$_POST["doccountryid"].",";
            $validator = validateIfExist($rejectedArr, "doccountryid");
            
            if($userdetails["doccountryid"] != $_POST["doccountryid"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "doccountryid"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo docregionid
        if(validateUpdate("docregionid")){
            $strQuery .= " docregionid = ".$_POST["docregionid"].",";
            $validator = validateIfExist($rejectedArr, "docregionid");
            
            if($userdetails["docregionid"] != $_POST["docregionid"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "docregionid"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo doccityid
        if(validateUpdate("doccityid")){
            $strQuery .= " doccityid = ".$_POST["doccityid"].",";
            $validator = validateIfExist($rejectedArr, "doccityid");
            
            if($userdetails["doccityid"] != $_POST["doccityid"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "doccityid"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo postalcode
        if(validateUpdate("postalcode")){
            $strQuery .= " postalcode = '".$_POST["postalcode"]."',";
            $validator = validateIfExist($rejectedArr, "postalcode");
            
            if($userdetails["postalcode"] != $_POST["postalcode"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "postalcode"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo website
        if(validateUpdate("website")){
            $strQuery .= " website = '".$_POST["website"]."',";
            $validator = validateIfExist($rejectedArr, "website");
            
            if($userdetails["website"] != $_POST["website"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "website"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo partners
        if(validateUpdate("partners")){
            $strQuery .= " partners = ".$_POST["partners"].",";
            $validator = validateIfExist($rejectedArr, "partners");
            
            if($userdetails["partners"] != $_POST["partners"]){
                
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "partners"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }
                
                if($userdetails["partners"] > $_POST["partners"]){
                    //Eliminamos los socios del ultimo al primero
                    $sql = "DELETE FROM usercompanypartners WHERE companyid = ".$userid.
                    "       ORDER BY id DESC ".
                    "       LIMIT ".($userdetails["partners"] - $_POST["partners"]);
                    if (!$rs=$db->query($sql))
                        badEnd("500", array("msg"=>$db->error));
                }
            }
        }
        
        //Validamos el campo branchoffices
        if(validateUpdate("branchoffices")){
            $strQuery .= " branchoffices = '".$_POST["branchoffices"]."',";
            $validator = validateIfExist($rejectedArr, "branchoffices");
            
            if($userdetails["branchoffices"] != $_POST["branchoffices"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "branchoffices"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo phone
        if(validateUpdate("phone")){
            $strQuery .= " phone = '".$_POST["phone"]."',";
            $validator = validateIfExist($rejectedArr, "phone");
            
            if($userdetails["phone"] != $_POST["phone"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "phone"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo countryid
        if(validateUpdate("countryid")){
            $strQuery .= " countryid = ".$_POST["countryid"].",";
            $validator = validateIfExist($rejectedArr, "countryid");
            
            if($userdetails["countryid"] != $_POST["countryid"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "countryid"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo regionid
        if(validateUpdate("stateid")){
            $strQuery .= " regionid = ".$_POST["stateid"].",";
            $validator = validateIfExist($rejectedArr, "regionid");
            
            if($userdetails["regionid"] != $_POST["stateid"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "regionid"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }
            }
        }
        
        //Validamos el campo cityid
        if(validateUpdate("cityid")){
            $strQuery .= " cityid = ".$_POST["cityid"].",";
            $validator = validateIfExist($rejectedArr, "cityid");
            
            if($userdetails["cityid "] != $_POST["cityid "]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "cityid"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }
            }
        }
        
        //Validamos el campo street
        if(validateUpdate("street")){
            $strQuery .= " street = '".$_POST["street"]."',";
            $validator = validateIfExist($rejectedArr, "street");
            
            if($userdetails["street "] != $_POST["street "]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "street"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }
            }
        }
        
        //Validamos el campo domicile
        if(validateUpdate("domicile")){
            $strQuery .= " domicile = '".$_POST["domicile"]."',";
            $validator = validateIfExist($rejectedArr, "domicile");
            
            if($userdetails["domicile "] != $_POST["domicile "]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "domicile"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }
            }
        }
        
        //Validamos el campo economicactivity
        if(validateUpdate("economicact")){
            $strQuery .= " economicactivity = '".$_POST["economicact"]."',";
            $validator = validateIfExist($rejectedArr, "economicactivity");
            
            if($userdetails["economicactivity"] != $_POST["economicact"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "economicactivity"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }
            }
        }
        
        //Validamos el campo politicallyexposed
        if(validateUpdate("politicalexp")){
            $strQuery .= " politicallyexposed = ".$_POST["politicalexp"].",";
            $validator = validateIfExist($rejectedArr, "politicallyexposed");
            
            if($userdetails["politicallyexposed"] != $_POST["politicalexp"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "politicallyexposed"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
            
        }
        
        //Validamos el campo independentdealer
        if(validateUpdate("indepmerch")){
            $strQuery .= " independentdealer = ".$_POST["indepmerch"].",";
            $validator = validateIfExist($rejectedArr, "independentdealer");
            
            if($userdetails["independentdealer"] != $_POST["indepmerch"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "independentdealer"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }
            }
        }
        
        //Validamos el campo anualincome
        if(validateUpdate("anualincome") && $_POST["anualincome"] != ""){
            $strQuery .= " anualincome = '".$_POST["anualincome"]."',";
            $validator = validateIfExist($rejectedArr, "anualincome");
            
            if($userdetails["anualincome "] != $_POST["anualincome "]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "anualincome"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }
            }
        }
        
        //Validamos el campo patrimony
        if(validateUpdate("patrimony") && $_POST["patrimony"] != ""){
            $strQuery .= " patrimony = '".$_POST["patrimony"]."',";
            $validator = validateIfExist($rejectedArr, "patrimony");
            
            if($userdetails["patrimony"] != $_POST["patrimony"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "patrimony"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo qtymonthlyop
        if(validateUpdate("qtymonthlyop")){
            $strQuery .= " qtymonthlyop = '".$_POST["qtymonthlyop"]."',";
            $validator = validateIfExist($rejectedArr, "qtymonthlyop");
            
            if($userdetails["qtymonthlyop"] != $_POST["qtymonthlyop"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "qtymonthlyop"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }
            }
        }
        
        //Validamos el campo prefertypeop
        if(validateUpdate("prefertypeop")){
            $strQuery .= " prefertypeop = '".$_POST["prefertypeop"]."',";
            $validator = validateIfExist($rejectedArr, "prefertypeop");
            
            if($userdetails["prefertypeop"] != $_POST["prefertypeop"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "prefertypeop"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo amountmontlyop
        if(validateUpdate("amomonthlyop")){
            $strQuery .= " amountmontlyop = '".$_POST["amomonthlyop"]."',";
            $validator = validateIfExist($rejectedArr, "amountmontlyop");
            
            if($userdetails["amountmontlyop"] != $_POST["amomonthlyop"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "amountmontlyop"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo economicrelation
        if(validateUpdate("economicrel") && $_POST["economicrel"] != ""){
            $strQuery .= " economicrelation = ".$_POST["economicrel"].",";
            
            if($userdetails["economicrelation"] != $_POST["economicrel"]){
                $validator = validateIfExist($rejectedArr, "economicrelation");
            
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "economicrelation"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }
            }
            
        }
        
        $strQuery .= validateUpdate("step") ? " step = ".($_POST["step"] + 1)."," : "";
        $strQuery .= " lastupdate = NOW(),";
        
        $strfields = "";
        
        if(sizeof($rejectedArr) > 0){
            foreach($rejectedArr as $rejected){
                $strfields .= $rejected.",";
            }
        
            $strQuery .= " rejected = '".substr($strfields, 0, -1)."',";
        }else{
            $strQuery .= " rejected = NULL,";
        }
        
        return substr($strQuery, 0, -1);
    }
    
    /* Funcion para validar que el parametro fue enviado.
    * Si el parametro existe retorna true y si no retorna false
    */
    function validateUpdate($param){
        $bolValues = false;
        if(isset($_POST[$param])){
            $bolValues = true;
        }
        return $bolValues;
    }
    
    //Asignar campos a guardar
    function ValidValues(){
        $strValues = "";
        $strValues .= " usrid,";
        $strValues .= validateFieldValues("venezuelan","venezuelan");
        $strValues .= validateFieldValues("companytype","ctype");
        $strValues .= validateFieldValues("name","name");
        $strValues .= validateFieldValues("comercialname","comercialname");
        $strValues .= validateFieldValues("creationdate","creationdate");
        $strValues .= validateFieldValues("doc","doc");
        $strValues .= validateFieldValues("doccountryid","doccountryid");
        $strValues .= validateFieldValues("docregionid","docregionid");
        $strValues .= validateFieldValues("doccityid","doccityid");
        $strValues .= validateFieldValues("postalcode","postalcode");
        $strValues .= validateFieldValues("website","website");
        $strValues .= validateFieldValues("partners","partners");
        $strValues .= validateFieldValues("branchoffices","branchoffices");
        $strValues .= validateFieldValues("phone","phone");
        $strValues .= validateFieldValues("countryid","countryid");
        $strValues .= validateFieldValues("stateid","regionid");
        $strValues .= validateFieldValues("cityid","cityid");
        $strValues .= validateFieldValues("street","street");
        $strValues .= validateFieldValues("domicile","domicile");
        $strValues .= validateFieldValues("economicact","economicactivity");
        $strValues .= validateFieldValues("politicalexp","politicallyexposed");
        $strValues .= validateFieldValues("indepmerch","independentdealer");
        $strValues .= validateFieldValues("anualincome","anualincome");
        $strValues .= validateFieldValues("patrimony","patrimony");
        $strValues .= validateFieldValues("qtymonthlyop","qtymonthlyop");
        $strValues .= validateFieldValues("prefertypeop","prefertypeop");
        $strValues .= validateFieldValues("amomonthlyop","amountmontlyop");
        $strValues .= validateFieldValues("economicrel","economicrelation");
        $strValues .= validateFieldValues("step","step");
        $strValues .= " lastupdate,";
        
        return substr($strValues, 0, -1);
    }
    
    /*Funcion valida la existencia del campo para asi ingresarlo en el query, en esta se reciben dos parametros
    * $field == Es el campo que se estara evaluando
    * $param == es el valor que se envia por la url
    */
    function validateFieldValues($param, $field){
        $strValues = "";
        if(isset($_POST[$param]) && $_POST[$param] != ""){
            $strValues .= " ".$field.",";
        }
        return $strValues;
    }
    
    //Funcion para asignar campos al query
    function createInsert($usrid){
        $strQuery = "";
        $strQuery .= " ".$usrid.",";
        $strQuery .= validateFieldInsert("venezuelan","number");
        $strQuery .= validateFieldInsert("companytype","number");
        $strQuery .= validateFieldInsert("name","string");
        $strQuery .= validateFieldInsert("comercialname","string");
        $strQuery .= validateFieldInsert("creationdate","date");
        $strQuery .= validateFieldInsert("doc","string");
        $strQuery .= validateFieldInsert("doccountryid","number");
        $strQuery .= validateFieldInsert("docregionid","number");
        $strQuery .= validateFieldInsert("doccityid","number");
        $strQuery .= validateFieldInsert("postalcode","string");
        $strQuery .= validateFieldInsert("website","string");
        $strQuery .= validateFieldInsert("partners","number");
        $strQuery .= validateFieldInsert("branchoffices","number");
        $strQuery .= validateFieldInsert("phone","number");
        $strQuery .= validateFieldInsert("countryid","number");
        $strQuery .= validateFieldInsert("stateid","number");
        $strQuery .= validateFieldInsert("cityid","number");
        $strQuery .= validateFieldInsert("street","string");
        $strQuery .= validateFieldInsert("domicile","string");
        $strQuery .= validateFieldInsert("economicact","string");
        $strQuery .= validateFieldInsert("politicalexp","number");
        $strQuery .= validateFieldInsert("indepmerch","number");
        $strQuery .= validateFieldInsert("anualincome","string");
        $strQuery .= validateFieldInsert("patrimony","string");
        $strQuery .= validateFieldInsert("qtymonthlyop","string");
        $strQuery .= validateFieldInsert("prefertypeop","string");
        $strQuery .= validateFieldInsert("amomonthlyop","string");
        $strQuery .= validateFieldInsert("economicrel","number");
        $strQuery .= validateFieldInsert("step","number");
        $strQuery .= " NOW(),";
        
        return substr($strQuery, 0, -1);
    }
    
    /*Funcion valida la existencia del campo para asi ingresarlo a la base de datos, en esta se reciben dos parametros
    * $field == Es el campo que se estara evaluando.
    * $type == El tipo de dato que es el campo a evaluar, Estos pueden ser:
    * -string
    * -date
    * -number
    */
    function validateFieldInsert($field,$type){
        $strInsert = "";
        
        if(isset($_POST[$field]) && $_POST[$field] != ""){
            if($type == "string" || $type == "date"){
                $strInsert .= " '".$_POST[$field]."',";
            }else if($type == "number"){
                if($field === "step"){
                    $strInsert .= " ".($_POST[$field] + 1).",";
                }else{
                    $strInsert .= " ".$_POST[$field].",";
                }
            }
        }
        
        return $strInsert;
    }
    
    function delete_directory($dirname) {
         if (is_dir($dirname))
           $dir_handle = opendir($dirname);
     if (!$dir_handle)
          return false;
     while($file = readdir($dir_handle)) {
           if ($file != "." && $file != "..") {
                if (!is_dir($dirname."/".$file))
                     unlink($dirname."/".$file);
                else
                     delete_directory($dirname.'/'.$file);
           }
     }
     closedir($dir_handle);
     rmdir($dirname);
     return true;
    }
    
    /*  Funcion para validar que si el campo se encuentra en un arreglo
    *   $rejected = arreglo con los campos rechazados
    *   $field = campo a validar que se encuentre en cual arreglo
    *   
    *   Retornara 0 cuando no se encuentre en ninguno
    *   Retornara 1 cuando se encuentre en rejected
    */
    function validateIfExist($rejected, $field){
        
        foreach($rejected as $rejectedfield){
            if($field == $rejectedfield){
                return 1;
            }
        }
        
        return 0;
    }
?>
