<?php
// app/api/login2fa/deactivate
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    include("../../hooks/google2fa/autoload.php");
    require '../../hooks/PHPMailer5/PHPMailerAutoload.php';
    date_default_timezone_set('Etc/UTC');
    use PragmaRX\Google2FA\Google2FA;
    
    // parametros obligatorios
    $parmsob = array("sessionid", 'secret');
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass();
    $sessionid = $_GET["sessionid"];
    $secret = $_GET['secret'];
    $valid = false;
    
    //Validamos que la session del usuario sea valida para continuar
    $userid = isSessionValid($db, $sessionid);
    
    // Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    //  Obtenemos los datos del usuario 
    $sql = "SELECT * FROM users WHERE id = ".$userid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $userdata = $rs->fetch_assoc();
    
    /* Parametro type
        1: Google
        2: Email
        3: Phone
    */
    if ($userdata['login2fa'] == 1) {
        $google2fa = new Google2FA();
        $valid = $google2fa->verifyKey($userdata['google2fa'], $secret, 0);

    }else if ($userdata['login2fa'] == 2) {
        
    }else if ($userdata['login2fa'] == 3) {
        
    }
    
    if (!$valid){
        badEnd('405', array("msg"=>determinateMsgFail(array(
            "esp"=>"Código de autenticación inválido",
            "eng"=>"Invalid authentication code"), $lang, "Código de autenticación inválido")));
    }
    
    $sql = "UPDATE users SET ".
    "       login2fa = NULL ".
    "       WHERE id = ".$userid;
    if (!$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $out->userid = (int)$userid;
    $out->login2fa = $valid;
    
    $ipaddress = getRealIP();
    //auditoria
    setAudit($db, "USUARIOS APP", $sessionid, "APP", "El usuario ".$userdata['usr']." desactivó 2FA por ".determinateType($userdata['login2fa']), $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 = ".$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 = ".$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 = $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")." ".$userdata['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($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 = $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 = ($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;
    }
?>