<?php
// app/api/users/update

    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","pwd","newpwd");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Definicion de variables y almacenamiento de valores enviados por GET
    $out= new stdClass();
    $sessionid = $_GET["sessionid"];
    $pwd = $_GET["pwd"];
    $newpwd = $_GET["newpwd"];
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    // Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    //Validamos que la clave actual sea igual a $pwd
    $sql = "SELECT id,usr, pwd FROM users WHERE sessionid = '".$sessionid."'";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
            
    $userdata = $rs->fetch_assoc();
    
    //Si la pwd no coincide retornamos error
    if($userdata["pwd"] != $pwd){
        badEnd("400", array("msg"=>determinateMsgFail(array(
            "esp"=>"La contraseña no coincide con la actual",
            "eng"=>"The new password is the same as the current"), $lang, "La contraseña no coincide con la actual")));
    }
    
    //Si la pwd es igual a la actualretornamos error
    if($userdata["pwd"] == $newpwd){
        badEnd("409", array("msg"=>determinateMsgFail(array(
            "esp"=>"La nueva contraseña es igual a la actual",
            "eng"=>"The new password is the same as the current"), $lang, "La nueva contraseña es igual a la actual")));
    }
    
    //Actualizamos la pwd del usuario por su ssid y su clave vieja
    $sql = "UPDATE users SET".
    "       pwd = '".$newpwd."'".
    "       WHERE sessionid = '".$sessionid."'".
    "       AND pwd = '".$pwd."'";
    if (!$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Retornamos 304 si no se actualizo ningun registro
    if ($db->affected_rows == 0)
        badEnd("304", array("msg"=>determinateMsgFail(array(
            "esp"=>"No se pudo modificar",
            "eng"=>"Cannot modify"), $lang, "No se pudo modificar")));
    
    
    $out->id = (int)$userdata["id"];
    
    //auditoria
    setAudit($db, "USUARIOS APP", $sessionid, "APP", "Se cambio la clave del usuario ".$userdata['usr']);
    
    // 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 = ".$userid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
            
    $userdata = $rs->fetch_assoc();
    
    // Consultamos los datos del mensaje
    $sql = "SELECT * FROM cmsmessages WHERE id = 11";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $data = $rs->fetch_assoc();
    
    // Validamos que el usuario tenga las notificaciones activas
    $sql = "SELECT * FROM usermessages ".
    "       WHERE categoryid = ".$data['category'].
    "       AND usrid = ".$userid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $userPref = $rs->fetch_assoc();
    
    if($userPref['email'] == null || $userPref['email'] == 1){
        $subject = $userdata['lang'] == "esp" ? $data['name_esp'] : $data['name_eng'];
        $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
        $body = "<div class='emailBox'>".
            "           <img class='afxLogo' src='".$homeurl."./settings/img/logo-email.png'/>".
            "           <div class='mainBox'>".
            "               <h1 class='titleEmail'>".
            "                   ".($userdata['lang'] == "esp" ? "Hola" : "Hello")." ".$userdata['name'].
            "               </h1>".
            "               <p class='msgEmail'>".
            "                   ".($userdata['lang'] == "esp" ? $data['dsc_esp'] : $data['dsc_eng']).
            "               </p>".
            "           </div>".
            "           <p class='copy'>".$footerEmails."</p>".
            "       </div>";
            
        $body = templateEmail($body, $STANDAR_STYLE_EMAIL);
        
        enviarCorreo2($fromeMail, strtolower($userdata['email']), $subject, $body);
        
        // Se valida la preferenca del mensaje y se envia segun el idioma
        if($userPref['sms'] == null || $userPref['sms'] == 1){
            $msg = ($userdata['lang'] == "esp" ? $data['sms_esp'] : $data['sms_eng']);
            enviarSMS($userdata['phone'], $msg);
        }
        
        if($userPref['system'] == null || $userPref['system'] == 1){
            
            $email = '';
            $sms = '';
            
            // Si se envia por correo obtenemos el correo del usuario
            if($userPref['email'] == null || $userPref['email'] == 1){
                $sql = "SELECT usr ".
                "       FROM users ".
                "       WHERE id = ".$userid;
                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 = ".$userid;
                if (!$resPref=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $rowPrefCom = $resPref->fetch_assoc();
                
                $sms = $rowPrefCom['phone'];
                
            }
                            
            // Enviamos el mensaje por la mensajeria interna
            $msg = ($userdata['lang'] == "esp" ? $data['dsc_esp'] : $data['dsc_eng']);
            saveInternalMsg($db, $msg, $userid, $email, $sms);
        }
    }
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
