<?php
// app/api/login/recover


    header("Content-Type:application/json");
    include_once("../../../settings/dbconn.php");
    include_once("../../../settings/utils.php");
    require '../../hooks/PHPMailer5/PHPMailerAutoload.php';
    date_default_timezone_set('Etc/UTC');
    
    // parametros obligatorios
    $parmsob = array("hash","pwd");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Definimos las variables y guardamos los datos recibidos por GET
    $hash = $_GET["hash"];
    $pwd = $_GET["pwd"];
    
    $lang = updateLang($db,$hash);
    
    $sql = "SELECT id, usr FROM users WHERE sessionid = '".mysqli_real_escape_string($db, $hash)."'";
    if (!$rs=$db->query($sql)){
        badEnd("500", array("msg"=>determinateDBError($db)));
    }
    
    $user = $rs->fetch_assoc();
    
    // Si el usuario es nuevo y tiene transacciones pendientes de las cargamos
    $sql = "SELECT * FROM users WHERE sessionid = '".mysqli_real_escape_string($db, $hash)."'";
    if (!$rs=$db->query($sql)){
        badEnd("500", array("msg"=>determinateDBError($db)));
    }
    
    $row = $rs->fetch_assoc();
    
    // Si es nulo o vacio es un usuario nuevo, validamos si tiene transferencias
    if ($row['pwd'] === '' || $row['pwd'] === null) {
        PAYPendingTransactions($db, $row['id']);
    }
    
    $sql =  "UPDATE users " .
            "SET    pwd = '".mysqli_real_escape_string($db, $pwd)."', ".
            "       sessionid = NULL, ".
            "       pwdexpiration = DATE_ADD(NOW(), INTERVAL 1 YEAR), ".
            "       status = 1 ".
            "WHERE  sessionid='".mysqli_real_escape_string($db, $hash)."'";
    if (!$db->query($sql)){
        badEnd("500", array("msg"=>determinateDBError($db)));
    }
    
    if ($db->affected_rows == 0){
        badEnd("401", array("msg"=>determinateMsgFail(array(
            "esp"=>"Hash incorrecto",
            "eng"=>"Invalid Hash"), $lang, "Hash incorrecto")));
    }

    $out = new stdClass();
    
    // Retornamos mensaje de que todo fue exitoso
    $out->msg = "Contraseña cambiada satisfactoriamente";
    

    
    try {
        
        // incluir auditoria
        $sql = "INSERT INTO audit (application, module, userid, dsc, ipaddress) " .
               "VALUES            ('APP','USUARIOS APP', '" .$user['id']. "', 'Se cambio la contraseña del usuario ".$user['usr']."', NULL)";
        if (!$db->query($sql)){
            badEnd("500", array("msg"=>determinateDBError($db)));
        }
        
    } catch (Exception $e){
        die();
    }
    
    //auditoria
    //setAudit($db, "USUARIOS APP", $sessionid, "APP", "Se cambio la clave del usuario ".$user['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 = ".$user['id'];
    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 = ".$user['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 style='background-color: #F8F8FA;padding: 20px;'>".
        "           <img style='margin: auto; display: block;margin-bottom:10px;' width='110' height='110' src='".$homeurl."./settings/img/logo-email.png'/>".
        "           <div style='margin: auto; display: block;background-color: #FFF;border-radius: 22px;width: 60%;padding:30px;'>".
        "               <h1 class='goodText' style='color:#474C58;text-align:center;font-size: 20px;font-weight: bold;'>".($lang == "esp" ? "Hola" : "Hello")." ".$userdata['name']."</h1>".
        "               <p class='goodText' style='font-size: 18px;color: #474C58;text-align:center;margin-bottom:30px;margin-left:20px;margin-right:20px;'>".($lang == "esp" ? $data['dsc_esp'] : $data['dsc_eng'])."</p>".
        "           </div>".
        "           <p class='copy' style='margin-top:40px; color: #767E93;text-align:center;'>".$footerEmails."</p>".
        "       </div>";
        
        enviarCorreo2($fromeMail, strtolower($user['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 = ".$user['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 = ".$user['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, $user['id'], $email, $sms);
    }
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
