<?php
#   SGT - The SGT for Internet - http://sgt.eti.br
#   Copyright (c) 2016-2018, Jean Azevedo. All rights reserved.

#   This file is part of SGT.

#   SGT is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   any later version.

#   SGT is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.

#   You should have received a copy of the GNU General Public License
#   along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

    include("../seguranca_aux_unid.php");
    protegePagina();
    include "../conectar.php";
    include "../log_.php";
    require "../criptografia_sgt.php";
    include "../chave_sgt.php";
    $id = isset($_POST["id"]) ? $_POST["id"]: '';
    $id = ($id);
    $desc = isset($_POST["desc"]) ? $_POST["desc"]: '';
    $user = isset($_POST["user"]) ? $_POST["user"]: '';
    $key = isset($_POST["key"]) ? $_POST["key"]: '';
    $unidade = isset($_POST["unidade"]) ? $_POST["unidade"]: '';
    $nivel = isset($_POST["nivel"]) ? $_POST["nivel"]: '';
    $busca_key=$pdo_sgt->prepare("SELECT * FROM tb_key WHERE unidade=:unidade AND descricao=:desc AND id<>:id");
    $busca_key->bindValue(":unidade",$unidade);
    $busca_key->bindValue(":desc",$desc);
    $busca_key->bindValue(":id",$id);
    $busca_key->execute();
    $dados_key=$busca_key->fetch(PDO::FETCH_ASSOC);
    if($dados_key['usuario'] === $user){
        echo"<script language='javascript' type='text/javascript'>
            alert('Este Usuário para esta Unidade e Descrição já existe!');
            window.history.go(-1)>Volta;
        </script>";
        die();
    }else{
        $sgt_cript = new SGT_KEY();
        $sgt_cript -> chave = $chave_num;
        $sgt_cript -> add_text = md5(sha1($chave_txt));
        $key_crip = $sgt_cript -> bloq($key);
        $atualizar=$pdo_sgt->prepare("UPDATE tb_key SET descricao=:desc,usuario=:usuario,senha=:senha,unidade=:unidade,nivel=:nivel WHERE id=:id");
        $atualizar->bindValue(":desc",$desc);
        $atualizar->bindValue(":usuario",$user);
        $atualizar->bindValue(":senha",$key_crip);
        $atualizar->bindValue(":unidade",$unidade);
        $atualizar->bindValue(":nivel",$nivel);
        $atualizar->bindValue(":id",$id);
        $atualizar->execute();
        $mensagem = "Dados alterados na tabela: tb_key - "
            . "Para os campos: descricao, ususario, senha, nivel, unidade - "
            . "Com os seguintes valores: $desc, $user, $key, $nivel, $unidade - "
            . "Do id: $id.";
        salvaLog($mensagem);
        echo"<script language='javascript' type='text/javascript'>
            window.location.href='list_key.php';
        </script>";
    }
?>