<?php
// app/api/users/updatecompany
    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 GET
    $out= new stdClass;
    $sessionid = $_POST["sessionid"];
    
    //Validamos la session
    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=2".
        "       WHERE sessionid='".$sessionid."'";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
    }else if($userdata["type"] == 1){
        //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 userpersons 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=2".
        "       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 la empresa
    $sql = "SELECT usrid FROM usercompanies 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 usercompanies ".
            "       WHERE doc = '".$_POST["doc"]."'".
            "       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 usercompanies(".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 usercompanies 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 usercompanies ".
            "       WHERE doc = '".$_POST["doc"]."'".
            "       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("msg"=>determinateMsgFail(array(
                    "esp"=>"Documento de identificacion duplicado",
                    "eng"=>"Duplicate identification document"), $lang, "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"=>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)));

        }
        //Actualizamos que acepto la declaracion si llego al ultimo paso del basic y viene el valor seteado
        if(validateUpdate("step") && $_POST["step"] == 5 && $_POST["declaration"] == 1 ){
            $sql = "UPDATE users SET ".
            "       declaration = NOW() ".
            "       WHERE id = ".$userdata["id"];
            if (!$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
        }
        if(validateUpdate("step") && $_POST["step"] == 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 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
                    /* Samuel: Por que se valida que exista? si el move_uploaded_file funciona retorna TRUE
                    *  Asi que validar que exista por que?
                    */
                    $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[strval($fileid)]["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[strval($fileid)]["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 eliminarlo
        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 usercompanies 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 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 venezuelan
        if(validateUpdate("reppartner")){
            $strQuery .= " reppartner = ".$_POST["reppartner"].",";
            if($userdetails["reppartner"] != $_POST["reppartner"]){
                $validator = validateIfExist($rejectedArr, "reppartner");
                
                if($userdetails["reppartner"] != $_POST["reppartner"]){
                    if($validator == 1){
                        foreach($rejectedArr as $index => $fieldRejected){
                            if($fieldRejected == "reppartner"){
                                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"=>determinateDBError($db)));
                }
            }
        }
        
        //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","string");
        $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;
    }
?>
