<?php
// app/api/users/updateperson
    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");
    if (!parametrosValidos($_POST, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    //Definicion de variables y almacenamiento de valores enviados por POST
    $out= new stdClass();
    $sessionid = $_POST["sessionid"];   
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    // Obtenemos el lenguaje del usuario
    $lang = updateLang($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"=>determinateDBError($db)));
            
    $userdata = $rs->fetch_assoc();
    
    //Validamos que sea null para actualizar
    if($userdata["type"] == null){
        $sql = "UPDATE users".
        "       SET type=1".
        "       WHERE sessionid='".$sessionid."'";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
    }else if($userdata["type"] == 2){
        //Cambio de tipo
        
        // Validamos que no tenga imagenes validadas
        $sql = "SELECT COUNT(userid) AS qty FROM useruploads ".
        "       WHERE userid = ".$userdata['id'].
        "       AND validated = 1";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $rowQty = $rs->fetch_assoc();
        
        if(intval($rowQty['qty']) > 0){
            badEnd("402", array("msg"=>"No puede cambiar de tipo"));
        }
        
        //Se elimina el de la otra tabla
        $sql = "DELETE FROM usercompanies WHERE usrid='".$userdata["id"]."'";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        //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 validar cuales existen en el string y cuales no
        foreach($filesfromdir as $filefromdir){
        
            $extfromdir = pathinfo($filefromdir, PATHINFO_EXTENSION);
            $filename = basename($filefromdir,".".$extfromdir);
            
            /*  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($filename !== 'avatar'){
                //Eliminamos registro
                $sql = "DELETE FROM useruploads WHERE".
                "       userid=".$userdata["id"]." AND".
                "       prefuploadid = ".$filename;
                if (!$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                
                
                //Eliminamos fichero
                unlink($filefromdir);
            }
        }
            
        //Se eliminan los uploads
        $sql = "DELETE FROM useruploads WHERE userid='".$userdata["id"]."'";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        //Se modifica el tipo de la tabla principal
        $sql = "UPDATE users".
        "       SET type=1".
        "       WHERE sessionid='".$sessionid."'";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        //badEnd("304", array("msg"=>"No se pudo modificar"));
    }
    
    //Consultamos para saber si existe ya un perfil para el usuario
    $sql = "SELECT usrid FROM userpersons WHERE usrid=".$userdata["id"];
    if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
    $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 userpersons ".
            "       WHERE doc = '".$_POST["doc"]."'".
            "       AND doctype = ".$_POST["doctype"].
            "       AND usrid != ".$userdata["id"];
            if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
            $row = $rs->fetch_assoc();
        
            // Retornamos 409 cuando doc esta duplicado
            if($row["usrid"] != null){
                badEnd("409", array("msg"=>determinateMsgFail(array(
                    "esp"=>"Documento de identificacion duplicado",
                    "eng"=>"Duplicate identification document"), $lang, "Documento de identificacion duplicado")));
            }
        }
        
        //Insertamos el usuario debido a que no cuenta con registro
        $sql = "INSERT INTO userpersons(".validValues().")".
        "       VALUES (".createInsert($userdata["id"]).")";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        // 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 userpersons WHERE usrid=".$userdata["id"];
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $uservalid = $rs->fetch_assoc();
        
        // Retornamos 204 cuando la busqueda no obtiene resutados
        if($uservalid["usrid"] == null){
            badEnd("204", array("msg"=>determinateMsgFail(array(
            "esp"=>"No se encuentra el registro",
            "eng"=>"Cannot find the record"), $lang, "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 userpersons ".
            "       WHERE doc = '".$_POST["doc"]."'".
            "       AND doctype = ".$_POST["doctype"].
            "       AND usrid != ".$userdata["id"];
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $row = $rs->fetch_assoc();
        
            // Retornamos 409 cuando doc esta duplicado
            if($row["qty"] > 0){
                badEnd("409", array("sql"=>$sql,"msg"=>determinateMsgFail(array(
                    "esp"=>"Documento de identificacion duplicado",
                    "eng"=>"Duplicate identification document"), $lang, "Documento de identificacion duplicado")));
            }
        }
        
        //Actualizamos el usuario
        $sql = "UPDATE userpersons".
        "       SET".
        "       ".createUpdate($uservalid["rejected"], $userdata["id"], $db).
        "       WHERE usrid =".$userdata["id"];
        if (!$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        if ($db->affected_rows == 0){
            badEnd("304", array("msg"=>determinateMsgFail(array(
                    "esp"=>"No se pudo modificar",
                    "eng"=>"Cannot modify"), $lang, "No se pudo modificar")));
        }
        //#NEW
        //Validamos el campo view SOLO SE INSERTA AL UPDATE
        if(validateUpdate("step") && $_POST["step"] + 1 == 2 && validateUpdate("view")){
            $sql = "UPDATE users SET ".
            "       view = ".mysqli_real_escape_string($db, $_POST["view"]).
            "       WHERE id = ".$userdata["id"];
            if (!$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));

        }
        /**SEPARADA ESTA SECCIÓN EN 2 IFS para actualizar declaración y para envío de mails**/
        //Actualizamos que acepto la declaracion si pasa del primer nivel y viene aceptada la declaración
        if(validateUpdate("step") && $_POST["step"] + 1 == 2 && $_POST["declaration"] == 1 ){
            $sql = "UPDATE users SET ".
            "       declaration = NOW() ".
            "       WHERE id = ".$userdata["id"];
            if (!$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            // 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 = ".$userdata["id"];
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $userdatatmp = $res->fetch_assoc();
            
            // Consultamos los datos del mensaje
            $sql = "SELECT * FROM cmsmessages WHERE id = 13";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $data = $res->fetch_assoc();
            
            // Validamos que el usuario tenga las notificaciones activas
            $sql = "SELECT * FROM usermessages ".
            "       WHERE categoryid = ".$data['category'].
            "       AND usrid = ".$userdata["id"];
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $userPref = $rs->fetch_assoc();
        
            $subject = $lang == "esp" ? $data['name_esp'] : $data['name_eng'];
                $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
                $body = "<div class='emailBox'>".
                "           <img class='afxLogo' src='".$homeurl."./settings/img/logo-email.png'/>".
                "           <div class='mainBox'>".
                "               <h1 class='titleEmail'>".
                "                   ".($lang == "esp" ? "Hola" : "Hello")." ".$userdatatmp['name'].
                "               </h1>".
                "               <p class='msgEmail'>".
                "                   ".($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($userdatatmp['email']), $subject, $body);
            
            enviarCorreo2($fromeMail, strtolower($userdatatmp['email']), $subject, $body);
                
            // Se valida la preferenca del mensaje y se envia seggun el idioma
            $msg = $lang == 'esp' ? $data['sms_esp'] : $data['sms_eng'];
            enviarSMS($userdatatmp['phone'], $msg);
    
            // Enviamos el mensaje por la mensajeria interna
            saveInternalMsg($db, $msg, $userdata["id"], $userdatatmp['email'], $userdatatmp['phone']);

        }
         //Actualizamos que acepto la declaracion si pasa del primer nivel y viene aceptada la declaración
        /* if(validateUpdate("step") && $_POST["step"] + 1 == 5){
            // 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 = ".$userdata["id"];
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $userdatatmp = $res->fetch_assoc();
            
            // Consultamos los datos del mensaje
            $sql = "SELECT * FROM cmsmessages WHERE id = 13";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $data = $res->fetch_assoc();
            
            // Validamos que el usuario tenga las notificaciones activas
            $sql = "SELECT * FROM usermessages ".
            "       WHERE categoryid = ".$data['category'].
            "       AND usrid = ".$userdata["id"];
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $userPref = $rs->fetch_assoc();
            
            if($userPref['email'] == null || $userPref['email'] == 1){
                $subject = $lang == "esp" ? $data['name_esp'] : $data['name_eng'];
                $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
                $body = "<div class='emailBox'>".
                "           <img class='afxLogo' src='".$homeurl."./settings/img/logo-email.png'/>".
                "           <div class='mainBox'>".
                "               <h1 class='titleEmail'>".
                "                   ".($lang == "esp" ? "Hola" : "Hello")." ".$userdatatmp['name'].
                "               </h1>".
                "               <p class='msgEmail'>".
                "                   ".($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($userdatatmp['email']), $subject, $body);
            }
            // Se valida la preferenca del mensaje y se envia seggun el idioma
            if($userPref['sms'] == null || $userPref['sms'] == 1){
                $msg = $lang == 'esp' ? $data['sms_esp'] : $data['sms_eng'];
                enviarSMS($userdatatmp['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 = ".$userdata["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 = ".$userdata["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 = ($lang == "esp" ? $data['dsc_esp'] : $data['dsc_eng']);
                saveInternalMsg($db, $msg, $userdata["id"], $email, $sms);
            }
        }*/
            
        // 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"=>determinateDBError($db)));
            
        $userdataaudit = $res->fetch_assoc();
        
        //auditoria
        setAudit($db, "USUARIOS APP", $sessionid, "APP", "El usuario natural ".$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"=>determinateDBError($db)));
                        
                    reqverifyuser($userdata["id"], $db, true);
                }else{
                    badEnd("411", array($msg=>"Error subida de archivos ".$_FILES["file"]["error"]));
                }
            }
        }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 && $filename !== 'avatar'){
                    //Eliminamos registro
                    $sql = "DELETE FROM useruploads WHERE".
                    "       userid=".$userdata["id"]." AND".
                    "       prefuploadid = ".$filename;
                    if (!$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                    
                    
                    //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"=>determinateDBError($db)));
                            
                        $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"=>determinateDBError($db)));
                                
                            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"=>determinateDBError($db)));
                                
                            reqverifyuser($userdata["id"], $db, true);
                        }
                    }else{
                        badEnd("411", array($msg=>"Error subida de archivos ".$_FILES["file"]["error"]));
                    }
                }
            }
        }
    
    }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 Eliminarlos
        foreach($filesfromdir as $filefromdir){
            
            $extfromdir = pathinfo($filefromdir, PATHINFO_EXTENSION);
            $filename = basename($filefromdir,".".$extfromdir);
                if($filename !== 'avatar'){
                    //Eliminamos registro
                    $sql = "DELETE FROM useruploads WHERE".
                    "       userid=".$userdata["id"]." AND".
                    "       prefuploadid = ".$filename;
                    if (!$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                            
                            
                    //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 userpersons WHERE usrid = ".$userid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userdetails = $rs->fetch_assoc();
        $rejectedArr = explode(",",$rejected);
        $strQuery = "";
        $validator = 0;
        
        //Validamos el campo affiliationbody
        if(validateUpdate("affiliationbody")){
            $strQuery .= " affiliationbody = '".$_POST["affiliationbody"]."',";
            $validator = validateIfExist($rejectedArr, "affiliationbody");
            
            if($userdetails["affiliationbody"] != $_POST["affiliationbody"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "affiliationbody"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }
            }
        }
        
        //Validamos el campo positionheld
        if(validateUpdate("positionheld")){
            $strQuery .= " positionheld = '".$_POST["positionheld"]."',";
            $validator = validateIfExist($rejectedArr, "positionheld");
            
            if($userdetails["positionheld"] != $_POST["positionheld"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "positionheld"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo pepcountryid
        if(validateUpdate("pepcountryid")){
            $strQuery .= " pepcountryid = ".$_POST["pepcountryid"].",";
            $validator = validateIfExist($rejectedArr, "pepcountryid");
            
            if($userdetails["pepcountryid"] != $_POST["pepcountryid"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "pepcountryid"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo peprelatedid
        if(validateUpdate("peprelatedid")){
            $strQuery .= " peprelatedid = '".$_POST["peprelatedid"]."',";
            $validator = validateIfExist($rejectedArr, "peprelatedid");
            
            if($userdetails["peprelatedid"] != $_POST["peprelatedid"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "peprelatedid"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo venezuelan
        if(validateUpdate("venezuelan")){
            $strQuery .= " 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 fname
        if(validateUpdate("fname")){
            $strQuery .= " fname = '".$_POST["fname"]."',";
            $validator = validateIfExist($rejectedArr, "fname");
            
            if($userdetails["fname"] != $_POST["fname"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "fname"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo sname
        if(validateUpdate("sname")){
            $strQuery .= " sname = '".$_POST["sname"]."',";
            $validator = validateIfExist($rejectedArr, "sname");
            
            if($userdetails["sname"] != $_POST["sname"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "sname"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo flastname
        if(validateUpdate("flastname")){
            $strQuery .= " flastname = '".$_POST["flastname"]."',";
            $validator = validateIfExist($rejectedArr, "flastname");
            
            if($userdetails["flastname"] != $_POST["flastname"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "flastname"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo slastname
        if(validateUpdate("slastname")){
            $strQuery .= " slastname = '".$_POST["slastname"]."',";
            $validator = validateIfExist($rejectedArr, "slastname");
            
            if($userdetails["slastname"] != $_POST["slastname"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "slastname"){
                            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 doctype
        if(validateUpdate("doctype")){
            $strQuery .= " doctype = ".$_POST["doctype"].",";
            $validator = validateIfExist($rejectedArr, "doctype");
            
            if($userdetails["doctype"] != $_POST["doctype"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "doctype"){
                            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 docissue
        if(validateUpdate("docissue")){
            $strQuery .= " docissue = '".$_POST["docissue"]."',";
            $validator = validateIfExist($rejectedArr, "docissue");
            
            if(date("d/m/Y", strtotime($userdetails["docissue"])) != date("d/m/Y", strtotime($_POST["docissue"]))){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "docissue"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }

        //Validamos el campo docexpiry
        if(validateUpdate("docexpiry")){
            $strQuery .= " docexpiry = '".$_POST["docexpiry"]."',";
            $validator = validateIfExist($rejectedArr, "docexpiry");
            
            if(date("d/m/Y", strtotime($userdetails["docexpiry"])) != date("d/m/Y", strtotime($_POST["docexpiry"]))){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "docexpiry"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo
        if(validateUpdate("gender")){
            $strQuery .= " gender = '".$_POST["gender"]."',";
            $validator = validateIfExist($rejectedArr, "gender");
            
            if($userdetails["gender"] != $_POST["gender"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "gender"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo maritalstatus
        if(validateUpdate("maritalstatus")){
            $strQuery .= " maritalstatus = ".$_POST["maritalstatus"].",";
            $validator = validateIfExist($rejectedArr, "maritalstatus");
            
            if($userdetails["maritalstatus"] != $_POST["maritalstatus"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "maritalstatus"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo birthdate
        if(validateUpdate("birthdate")){
            $strQuery .= " birthdate = '".$_POST["birthdate"]."',";
            $validator = validateIfExist($rejectedArr, "birthdate");
            
            if(date("d/m/Y", strtotime($userdetails["birthdate"])) != date("d/m/Y", strtotime($_POST["birthdate"]))){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "birthdate"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo birthcountryid
        if(validateUpdate("birthcountryid")){
            $strQuery .= " birthcountryid = ".$_POST["birthcountryid"].",";
            $validator = validateIfExist($rejectedArr, "birthcountryid");
            
            if($userdetails["birthcountryid"] != $_POST["birthcountryid"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "birthcountryid"){
                            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 stateid
        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 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 profession
        if(validateUpdate("profession")){
            $strQuery .= " profession = '".$_POST["profession"]."',";
            $validator = validateIfExist($rejectedArr, "profession");
            
            if($userdetails["profession"] != $_POST["profession"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "profession"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo ocupation
        if(validateUpdate("ocupation")){
            $strQuery .= " ocupation = '".$_POST["ocupation"]."',";
            $validator = validateIfExist($rejectedArr, "ocupation");
            
            if($userdetails["ocupation"] != $_POST["ocupation"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "ocupation"){
                            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 company
        if(validateUpdate("company")){
            $strQuery .= " company = '".$_POST["company"]."',";
            $validator = validateIfExist($rejectedArr, "company");
            
            if($userdetails["company"] != $_POST["company"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "company"){
                            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 amountmonthlyop
        if(validateUpdate("amomonthlyop")){
            $strQuery .= " amountmonthlyop = '".$_POST["amomonthlyop"]."',";
            $validator = validateIfExist($rejectedArr, "amountmonthlyop");
            
            if($userdetails["amountmonthlyop"] != $_POST["amomonthlyop"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "amountmonthlyop"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo economicrelation
        if(validateUpdate("economicrel") && $_POST["economicrel"] != ""){
            $strQuery .= " economicrelation = ".$_POST["economicrel"].",";
            $validator = validateIfExist($rejectedArr, "economicrelation");
            
            if($userdetails["economicrelation"] != $_POST["economicrel"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "economicrelation"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        
        //Validamos el campo fname
        if(validateUpdate("fname")){
            $strQuery .= " fname = '".$_POST["fname"]."',";
            $validator = validateIfExist($rejectedArr, "fname");
            
            if($userdetails["fname"] != $_POST["fname"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "fname"){
                            reqverifyuser($userid, $db, true);
                            unset($rejectedArr[$index]);
                        }
                    }
                }    
            }
        }
        //Validamos el campo american
        if(validateUpdate("american")){
            $strQuery .= " american = ".$_POST["american"].",";
            $validator = validateIfExist($rejectedArr, "american");
            
            if($userdetails["american"] != $_POST["american"]){
                if($validator == 1){
                    foreach($rejectedArr as $index => $fieldRejected){
                        if($fieldRejected == "american"){
                            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])){//Ajustado esta validación puede recibir vacío
            $bolValues = true;
        }
        return $bolValues;
    }
    
    //Asignar campos a guardar
    function ValidValues(){
        $strValues = "";
        $strValues .= " usrid,";
        $strValues .= validateFieldValues("affiliationbody","affiliationbody");
        $strValues .= validateFieldValues("positionheld","positionheld");
        $strValues .= validateFieldValues("pepcountryid","pepcountryid");
        $strValues .= validateFieldValues("peprelatedid","peprelatedid");
        $strValues .= validateFieldValues("venezuelan","venezuelan");
        $strValues .= validateFieldValues("fname","fname");
        $strValues .= validateFieldValues("sname","sname");
        $strValues .= validateFieldValues("flastname","flastname");
        $strValues .= validateFieldValues("slastname","slastname");
        $strValues .= validateFieldValues("doc","doc");
        $strValues .= validateFieldValues("doctype","doctype");
        $strValues .= validateFieldValues("doccountryid","doccountryid");
        $strValues .= validateFieldValues("docissue","docissue");
        $strValues .= validateFieldValues("docexpiry","docexpiry");
        $strValues .= validateFieldValues("gender","gender");
        $strValues .= validateFieldValues("maritalstatus","maritalstatus");
        $strValues .= validateFieldValues("birthdate","birthdate");
        $strValues .= validateFieldValues("birthcountryid","birthcountryid");
        $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("postalcode","postalcode");
        $strValues .= validateFieldValues("profession","profession");
        $strValues .= validateFieldValues("ocupation","ocupation");
        $strValues .= validateFieldValues("economicact","economicactivity");
        $strValues .= validateFieldValues("politicalexp","politicallyexposed");
        $strValues .= validateFieldValues("indepmerch","independentdealer");
        $strValues .= validateFieldValues("company","company");
        $strValues .= validateFieldValues("anualincome","anualincome");
        $strValues .= validateFieldValues("patrimony","patrimony");
        $strValues .= validateFieldValues("qtymonthlyop","qtymonthlyop");
        $strValues .= validateFieldValues("prefertypeop","prefertypeop");
        $strValues .= validateFieldValues("amomonthlyop","amountmonthlyop");
        $strValues .= validateFieldValues("economicrel","economicrelation");
        $strValues .= validateFieldValues("american","american");
        $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("affiliationbody","string");
        $strQuery .= validateFieldInsert("positionheld","string");
        $strQuery .= validateFieldInsert("pepcountryid","number");
        $strQuery .= validateFieldInsert("peprelatedid","string");
        $strQuery .= validateFieldInsert("venezuelan","number");
        $strQuery .= validateFieldInsert("fname","string");
        $strQuery .= validateFieldInsert("sname","string");
        $strQuery .= validateFieldInsert("flastname","string");
        $strQuery .= validateFieldInsert("slastname","string");
        $strQuery .= validateFieldInsert("doc","string");
        $strQuery .= validateFieldInsert("doctype","number");
        $strQuery .= validateFieldInsert("doccountryid","number");
        $strQuery .= validateFieldInsert("docissue","date");
        $strQuery .= validateFieldInsert("docexpiry","date");
        $strQuery .= validateFieldInsert("gender","string");
        $strQuery .= validateFieldInsert("maritalstatus","number");
        $strQuery .= validateFieldInsert("birthdate","date");
        $strQuery .= validateFieldInsert("birthcountryid","number");
        $strQuery .= validateFieldInsert("phone","string");
        $strQuery .= validateFieldInsert("countryid","number");
        $strQuery .= validateFieldInsert("stateid","number");
        $strQuery .= validateFieldInsert("cityid","number");
        $strQuery .= validateFieldInsert("street","string");
        $strQuery .= validateFieldInsert("domicile","string");
        $strQuery .= validateFieldInsert("postalcode","string");
        $strQuery .= validateFieldInsert("profession","string");
        $strQuery .= validateFieldInsert("ocupation","string");
        $strQuery .= validateFieldInsert("economicact","string");
        $strQuery .= validateFieldInsert("politicalexp","number");
        $strQuery .= validateFieldInsert("indepmerch","number");
        $strQuery .= validateFieldInsert("company","string");
        $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("american","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;
    }
?>


