<?php
// cms/api/login2fa/deactivate
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    require '../../hooks/PHPMailer5/PHPMailerAutoload.php';
    date_default_timezone_set('Etc/UTC');
    use PragmaRX\Google2FA\Google2FA;
    
    // parametros obligatorios
    $parmsob = array("sessionid", 'usrid');
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass();
    $sessionid = $_GET["sessionid"];
    $userid = $_GET['usrid'];
    $valid = false;
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 78))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    //  Obtenemos los datos del usuario 
    $sql = "SELECT * FROM users WHERE id = ".mysqli_real_escape_string($db, $userid);
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $userdata = $rs->fetch_assoc();
    
    if ($userdata['login2fa'] == null) {
        badEnd("402", array("msg"=>"Usuario no posee 2FA activado"));
    }
    
    $sql = "UPDATE users SET ".
    "       login2fa = NULL, ".
    "       google2fa = NULL ".
    "       WHERE id = ".mysqli_real_escape_string($db, $userid);
    if (!$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $out->userid = (int)$userid;
    $out->login2fa = true;
    
    $ipaddress = getRealIP();
    //auditoria
    setAudit($db, "USUARIOS APP", $sessionid, "CMS", "Se desactivó 2FA por ".determinateType($userdata['login2fa'])." para el usuario ".$userdata['usr'] , $ipaddress);
    
    // 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.usr AS usr, ".
    "       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 = ".mysqli_real_escape_string($db, $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 = 16";
    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 = ".mysqli_real_escape_string($db, $data['category']).
    "       AND usrid = ".mysqli_real_escape_string($db, $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'] ? $data['name_esp'] : $data['name_eng'];
        $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
        $body = "<div class='emailBox'>".
            "           <img class='afxLogo' src='".$homeurlCMS."./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['usr']), $subject, $body);
    }

    // Se valida la preferenca del mensaje y se envía según 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 = ".mysqli_real_escape_string($db, $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 = ".mysqli_real_escape_string($db, $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();
    
    function determinateType($typeId){
        $str = '';
        
        switch($typeId){
            case 1:
                $str = 'Google';
                break;
            case 2:
                $str = 'email';
                break;
            case 3:
                $str = 'teléfono';
                break;
        }
        return $str;
    }
?>