<?php $page = 'familia';
include('header.php'); ?>

<body class="hold-transition layout-top-nav">
  <div class="wrapper">
    <div class="preloader flex-column justify-content-center align-items-center">
    </div>
    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
      <!-- Content Header (Page header) -->
      <div class="content-header">
        <div class="container-fluid">
        </div><!-- /.container-fluid -->
      </div>
      <!-- /.content-header -->

      <!-- Main content -->
      <section class="content">
        <div class="container-fluid">
          <div class="row">
            <div class="col-md-3">
              <!-- Profile Image -->
              <div class="card card-primary card-outline" style="border-top: 3px solid #560085;">
                <div class="card-body box-profile">
                  <div class="text-center">
                    <div class="profile-user-img img-fluid img-circle image-info-profile" style="display: flex; justify-content: center; align-items: center;" alt="User profile picture">
                      <i class="fas fa-user fa-3x" style="color: #560085;"></i>
                    </div>
                  </div>

                  <h3 class="profile-username text-center" id="nomeUsuarioPerfil"></h3>

                  <p class="text-muted text-center">Usuário</p>

                  <input type="file" id="file" name="file" accept="image/*" hidden>
                  <div id="div-botao-foto">
                    <a href="#" class="btn btn-primary btn-block" id="update-foto"><b>Alterar Foto de Perfil</b></a>
                  </div>
                </div>
                <!-- /.card-body -->
              </div>
              <!-- /.card -->

              <!-- About Me Box -->
              <div class="card card-primary">
                <div class="card-header">
                  <h3 class="card-title">Sobre Mim</h3>
                </div>
                <!-- /.card-header -->
                <div class="card-body">
                  <strong><i class="fas fa-id-card-clip mr-1"></i> Bilhete de Identidade</strong>

                  <p class="text-muted" id="aboutBi">
                  </p>

                  <hr>

                  <strong><i class="fas fa-venus-mars mr-1"></i> Genero</strong>

                  <p class="text-muted" id="aboutGenero"></p>

                  <hr>

                  <strong><i class="fas fa-envelope mr-1"></i> E-mail</strong>

                  <p class="text-muted" id="aboutEmail"></p>

                  <hr>

                  <strong><i class="far fa-user mr-1"></i> Tipo de Usuário</strong>

                  <p class="text-muted" id="aboutTipoUsuario"></p>
                </div>
                <!-- /.card-body -->
              </div>
              <!-- /.card -->
            </div>
            <!-- /.col -->
            <div class="col-md-9">
              <div class="card">
                <div class="card-header p-2">
                  <ul class="nav nav-pills">
                    <li class="nav-item"><a class="nav-link active" href="#informacao" data-toggle="tab">Informações</a></li>
                    <li class="nav-item"><a class="nav-link" href="#password" data-toggle="tab">Palavra-Passe</a></li>
                  </ul>
                </div><!-- /.card-header -->
                <div class="card-body">
                  <div class="tab-content">
                    <div class="active tab-pane" id="informacao">
                      <div class="row">
                        <div class="col-md-12">
                          <div class="alert alert-info alert-dismissible" style="background-color: #56008521; border-color: #56008557; color: #560085;">
                            <i class="icon fas fa-info"></i> Campos com asterisco (*) são campos de preenchimento obrigatório.
                          </div>
                        </div>
                      </div>
                      <div class="row">
                        <div class="col-md-4">
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="required">Nome Completo</small>
                            <input type="text" class="form-control" id="nome" name="nome" placeholder="Nome Completo" title="Nome Completo" required>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="required">Nome de Usuário</small>
                            <input type="text" class="form-control" id="nomeUsuario" name="nomeUsuario" placeholder="Nome de Usuário" title="Nome de Usuário" required>
                            <small>Mensagem de erro</small>
                          </div>
                        </div>
                        <div class="col-md-4">
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="required">E-mail</small>
                            <input type="text" class="form-control" id="email" name="email" placeholder="E-mail" title="E-mail" required>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="required">Bilhete de Identidade</small>
                            <input type="text" class="form-control" id="bi" name="bi" placeholder="Bilhete de Identidade" title="Nº Bilhete de Indentidade" required>
                            <small>Mensagem de erro</small>
                          </div>
                        </div>
                        <div class="col-md-4">
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="required">Tipo de Usuário</small>
                            <select class="form-control select2" style="width: 100%;" id="idTipoUsuario" name="idTipoUsuario">
                              <option value="0">Selecione um Tipo de Usuário</option>
                            </select>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="required">Género</small>
                            <select class="form-control select2" style="width: 100%;" id="genero" name="genero">
                              <option value="0">Selecione um género</option>
                              <option value="Masculino">Masculino</option>
                              <option value="Feminino">Feminino</option>
                            </select>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group" style="margin-bottom: 0;">
                            <button class="btn btn-block btn-primary" id="btn-submit" name="btn-submit">Actualizar Usuário</button>
                          </div>
                        </div>
                        <!-- /.col -->
                      </div>
                    </div>

                    <div class="tab-pane" id="password">
                      <div class="row">
                        <div class="col-md-4">
                          <div class="form-group margem" style="margin-bottom: 0;">
                            <small class="required">Palavra-passe Actual</small>
                            <div class="input-group mb-3 field" style="margin-bottom: 0 !important;">
                              <input type="password" class="form-control" placeholder="Digite a Sua Palavra-passe Actual" name="oldPassword" id="oldPassword">
                              <div class="input-group-append">
                                <div class="input-group-text">
                                  <span class="fas fa-key"></span>
                                </div>
                              </div>
                            </div>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group margem" style="margin-bottom: 0;">
                            <small class="required">Nova Palavra-passe</small>
                            <div class="input-group mb-3 field" style="margin-bottom: 0 !important;">
                              <input type="password" class="form-control" placeholder="Digite a Sua Nova Palavra-passe" name="newPassword" id="newPassword">
                              <div class="input-group-append">
                                <div class="input-group-text">
                                  <span class="fas fa-lock"></span>
                                </div>
                              </div>
                            </div>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group margem" style="margin-bottom: 0;">
                            <small class="required">Nova Palavra-passe</small>
                            <div class="input-group mb-3 field" style="margin-bottom: 0 !important;">
                              <input type="password" class="form-control" placeholder="Re-Introduza a Sua Nova Palavra-passe" name="cNewPassword" id="cNewPassword">
                              <div class="input-group-append">
                                <div class="input-group-text">
                                  <span class="fas fa-lock"></span>
                                </div>
                              </div>
                            </div>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group">
                            <button type="submit" name="btn-submit" id="btn-password" class="btn btn-block btn-primary">Alterar Palavra-passe</button>
                          </div>
                        </div>
                      </div>
                    </div>
                    <!-- /.tab-pane -->
                  </div>
                  <!-- /.tab-content -->
                </div><!-- /.card-body -->
              </div>
              <!-- /.card -->
            </div>
            <!-- /.col -->
          </div>
          <!-- /.row -->
        </div><!-- /.container-fluid -->
      </section>
      <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php include('footer.php'); ?>
    <script>
      let resizedImage;
      $('[data-mask]').inputmask();

      $(function() {
        //Initialize Select2 Elements
        $('.select2').select2()

        //Initialize Select2 Elements
        $('.select2bs4').select2({
          theme: 'bootstrap4'
        });
      });

      $(function() {
        $('.toastrDefaultSuccess').click(function() {
          toastr.success('Lorem ipsum dolor sit amet, consetetur sadipscing elitr.')
        });
        $('.toastrDefaultInfo').click(function() {
          toastr.info('Lorem ipsum dolor sit amet, consetetur sadipscing elitr.')
        });
        $('.toastrDefaultError').click(function() {
          toastr.error('Lorem ipsum dolor sit amet, consetetur sadipscing elitr.')
        });
        $('.toastrDefaultWarning').click(function() {
          toastr.warning('Lorem ipsum dolor sit amet, consetetur sadipscing elitr.')
        });
      });

      $(document).ready(function() {
        console.log("Estou aqui: ");
        funcaoSelect("../pos/includes/select.inc.php", "post", "json", "tipoUsuario", success = (data) => {
          let select = "";
            select += "<option value='0'>Selecione um Tipo de Usuário</option>";
            for (var key in data) {
              select += "<option value=" + data[key]['idTipoUsuario'] + ">" + data[key]['nome'] + "</option>";
            }
            $("#idTipoUsuario").html(select);
        }, error = (data) => {

        }, done = (data) => {

        });
        /*$.ajax({
          url: "includes/read/tipoUsuario.inc.php",
          type: "post",
          dataType: "json",
          success: function(data) {
            let select = "";
            select += "<option value='0'>Selecione um Tipo de Usuário</option>";
            for (var key in data) {
              select += "<option value=" + data[key]['idTipoUsuario'] + ">" + data[key]['nome'] + "</option>";
            }
            $("#idTipoUsuario").html(select);
          }
        });*/
      });

      let urlToFile = (url) => {
        let arr = url.split(",");
        let mime = arr[0].match(/:(.*?);/)[1];
        let data = arr[1];

        let dataString = atob(data);
        let n = dataString.length;
        let dataArr = new Uint8Array(n);
        while (n--) {
          dataArr[n] = dataString.charCodeAt(n);
        }
        let file = new File([dataArr], 'File.jpg', {
          type: mime
        });
        return file;
      }

      $(document).ready(function() {
        const img_input = document.querySelector("#file");
        img_input.addEventListener("change", function() {
          const reader = new FileReader();
          reader.addEventListener("load", () => {
            const imgElement = document.createElement("img");
            imgElement.src = reader.result;
            imgElement.onload = function(e) {
              const canvas = document.createElement("canvas");
              const MAX_WIDTH = 400;
              const scaleSize = MAX_WIDTH / e.target.width;
              canvas.width = MAX_WIDTH;
              canvas.height = e.target.height * scaleSize;
              const ctx = canvas.getContext("2d");
              ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height);

              const srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");
              resizedImage = urlToFile(srcEncoded);
            }

            const uploaded_image = reader.result;
            document.querySelector(".image-info-profile").style.backgroundImage = `url(${uploaded_image})`;

            let botao = document.getElementById("div-botao-foto");
            botao.innerHTML = `<div class="row"><div class="col-md-6"><a href="#" class="btn btn-primary btn-block" style="background-color: #560085; border-color: #560085;" id="add-foto"><b>Gravar</b></a></div>
          <div class="col-md-6"><a href="#" class="btn btn-primary btn-block" style="background-color: #560085; border-color: #560085;" id="cancelar-foto"><b>Cancelar</b></a></div></div>`
          });
          reader.readAsDataURL(this.files[0]);
          document.querySelector(".image-info-profile").querySelector("i").style.display = "none";
        });
      });

      $(document).on("click", "#cancelar-foto", function(e) {
        e.preventDefault();
        document.querySelector(".image-info-profile").style.backgroundImage = "none";
        document.querySelector(".image-info-profile").querySelector("i").style.display = "block";
        let botao = document.getElementById("div-botao-foto");
        botao.innerHTML = `<a href="#" class="btn btn-primary btn-block" style="background-color: #560085; border-color: #560085;" id="update-foto"><b>Alterar Foto de Perfil</b></a>`;
      });

      $(document).on("click", "#add-foto", function(e) {
        e.preventDefault();
        let identificador = <?php echo $_SESSION["usuarioId"]; ?>;
        let img = $("#file")[0].files;
        let form_data = new FormData();
        form_data.append('id', identificador);
        form_data.append('parametro', "idUsuario");
        form_data.append('campo', "imagem");
        form_data.append('tabela', "usuario");
        form_data.append('imagem', resizedImage);
        form_data.append('caminho', '../../gestao/images/usuario/');

        funcaoImagem("../pos/includes/imagem.inc.php", "post", form_data, false, false, false, success = (data) => {
          console.log("É isso que veio: ", data);
          /*Swal.fire({
              title: 'Fotografia Alterada com Sucesso!',
              text: 'Usuário:' + nome.value,
              allowOutsideClick: false,
              confirmButtonText: 'Confirmar',
              confirmButtonColor: "#560085",
              icon: 'success'
            });*/
        }, error = (data) => {
          Swal.fire({
                  title: 'Erro ao Alterar foto de perfil!',
                  text: 'Usuário:' + nome.value,
                  confirmButtonText: 'Confirmar',
                  confirmButtonColor: "#560085",
                  icon: 'error'
                });
        }, done = (data) => {
          let botao = document.getElementById("div-botao-foto");
          botao.innerHTML = `<a href="#" class="btn btn-primary btn-block" style="background-color: #560085; border-color: #560085;" id="update-foto"><b>Alterar Foto de Perfil</b></a>`;
        });
        /*$.ajax({
          url: "includes/create/fotoUsuario.inc.php",
          type: "post",
          data: form_data,
          cache: false,
          contentType: false,
          processData: false,
          success: function(data) {
            console.log(data);
            Swal.fire({
              title: 'Fotografia Alterada com Sucesso!',
              text: 'Usuário:' + nome.value,
              allowOutsideClick: false,
              confirmButtonText: 'Confirmar',
              confirmButtonColor: "#560085",
              icon: 'success'
            })
          }
        }).done(function() {
          let botao = document.getElementById("div-botao-foto");
          botao.innerHTML = `<a href="#" class="btn btn-primary btn-block" style="background-color: #560085; border-color: #560085;" id="update-foto"><b>Alterar Foto de Perfil</b></a>`;
        });*/
      });

      $(document).on("click", "#update-foto", function(e) {
        e.preventDefault();
        let elemento = document.getElementById("file");
        elemento.click();
      });

      $(document).on("click", "#checkBoxAgree", function(e) {
        let btn = document.getElementById("btn-agree");
        if (this.checked) {
          btn.removeAttribute('disabled');
        } else {
          btn.setAttribute('disabled', 'disabled');
        }
      });

      $(document).on("click", "#btn-agree", function(e) {
        e.preventDefault();
        let btn = document.getElementById("checkBoxAgree");
        if (btn.checked) {
          $('#modal-lg').modal('hide');
          submeter();
        } else {
          this.setAttribute('disabled', 'disabled');
        }
      });

      $(document).on("click", "#btn-submit", function(e) {
        if (nomeUsuario.value != '' && genero.value != 0 && idTipoUsuario.value != 0) {
          swal.fire({
            title: "Deseja actualizar os dados?",
            text: "Usuário: " + nome.value,
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: 'Confirmar',
            confirmButtonColor: '#560085',
            cancelButtonText: 'Cancelar',
            cancelButtonColor: '#560085',
          }).then((result) => {
            if (result.isConfirmed) {
              let dados = {
                nome: nome.value,
                nomeUsuario: nomeUsuario.value,
                genero: genero.value,
                email: email.value,
                bi: bi.value,
                idTipoUsuario: idTipoUsuario.value
              };
              funcaoUpdate("../pos/includes/update.inc.php", "post", "json", "usuario", dados, {"idUsuario": <?php echo $_SESSION["usuarioId"]; ?>}, success = (data) => {
                Swal.fire({
                  title: 'Informações Alteradas com Sucesso!',
                  text: 'Usuário:' + nome.value,
                  allowOutsideClick: false,
                  confirmButtonText: 'Confirmar',
                  confirmButtonColor: "#560085",
                  icon: 'success'
                }).then(() => {
                  nomeUsuarioPerfil.innerText = nome.value;
                  aboutBi.innerText = bi.value;
                  aboutGenero.innerText = genero.value;
                  aboutEmail.innerText = email.value;
                  aboutTipoUsuario.innerText = $('#idTipoUsuario').select2('data')[0].text;

                  nome.className = "form-control";
                  nomeUsuario.className = "form-control";
                  email.className = "form-control";
                  bi.className = "form-control";
                });
              }, error = (data) => {
                console.log("Erro: ", data);
                Swal.fire({
                  title: 'Erro ao Editar Informações do Usuário!',
                  text: 'Usuário:' + nome.value,
                  confirmButtonText: 'Confirmar',
                  confirmButtonColor: "#560085",
                  icon: 'error'
                });
              }, done = (data) => {
                console.log("Terminado: ", data);
              });
            }
          });
        }
      });

      $(document).ready(function() {
        $.ajax({
          url: "includes/read/queryUser.inc.php",
          type: "post",
          dataType: "json",
          data: {
            idUsuario: <?php echo $_SESSION["usuarioId"]; ?>,
          },
          success: function(data) {
            console.log("Dados: ", data);
            if (data[0]["imagem"] != null) {
              document.querySelector(".image-info-profile").style.backgroundImage = `url(${"images/usuario/" + data[0]["imagem"]})`;
              document.querySelector(".image-info-profile").querySelector("i").style.display = "none";
            }
            if (data[0]["nome"] != null) {
              nomeUsuarioPerfil.innerText = data[0]["nome"];
              nome.value = data[0]["nome"];
            }
            if (data[0]["nomeUsuario"] != null) {
              nomeUsuario.value = data[0]["nomeUsuario"];
            }
            if (data[0]["bi"] != null) {
              bi.value = data[0]["bi"];
              aboutBi.innerText = data[0]["bi"];
            }
            if (data[0]["email"] != null) {
              aboutEmail.innerText = data[0]["email"];
              email.value = data[0]["email"];
            }
            if (data[0]["idTipoUsuario"] != null) {
              aboutTipoUsuario.innerText = data[0]["tipoUsuario"];
              $('#idTipoUsuario').val(data[0]['idTipoUsuario']);
              $('#idTipoUsuario').select2().trigger('change');
            }
            if (data[0]["genero"] != null) {
              aboutGenero.innerText = data[0]['genero'];
              $('#genero').val(data[0]['genero']);
              $('#genero').select2().trigger('change');
            }
          }
        }).done(function(data) {})
      });

      function passwords() {
        let btn = document.getElementById("btn-password");
        let smallNew = newPassword.parentElement.parentElement.querySelectorAll("small")[1];
        let smallCnew = cNewPassword.parentElement.parentElement.querySelectorAll("small")[1];
        if (newPassword.value != cNewPassword.value) {
          newPassword.className = "form-control is-invalid";
          smallNew.style.visibility = "visible";
          smallNew.style.color = "#dc3545";
          smallNew.innerText = "Senhas não coinscidem!";

          cNewPassword.className = "form-control is-invalid";
          smallCnew.style.visibility = "visible";
          smallCnew.style.color = "#dc3545";
          smallCnew.innerText = "Senhas não coinscidem!";
          btn.setAttribute('disabled', 'disabled');
        } else if (newPassword.value == "") {
          newPassword.className = "form-control is-warning";
          smallNew.innerText = "Campo obrigatório!";
          smallNew.style.color = "#ffc107";
          smallNew.style.visibility = "visible";
          btn.setAttribute('disabled', 'disabled');
        } else if (cNewPassword.value == "") {
          cNewPassword.className = "form-control is-warning";
          smallCnew.innerText = "Campo obrigatório!";
          smallCnew.style.color = "#ffc107";
          smallCnew.style.visibility = "visible";
          btn.setAttribute('disabled', 'disabled');
        } else {
          newPassword.className = "form-control is-valid";
          cNewPassword.className = "form-control is-valid";
          smallNew.style.visibility = "hidden";
          smallCnew.style.visibility = "hidden";
          btn.removeAttribute('disabled');
        }
      }

      $(document).on("keyup", "#oldPassword", function(e) {
        let smallOld = oldPassword.parentElement.parentElement.querySelectorAll("small")[1];
        if (oldPassword.value != "") {
          smallOld.style.visibility = "hidden";
          oldPassword.className = "form-control is-valid";
        } else {
          oldPassword.className = "form-control is-warning";
          smallOld.style.visibility = "visible";
          smallOld.style.color = "#ffc107";
          smallOld.innerText = "Campo obrigatório!";
        }
      });

      $(document).on("keyup", "#newPassword", function(e) {
        passwords();
      });

      $(document).on("keyup", "#cNewPassword", function(e) {
        passwords();
      });

      $(document).on("click", "#btn-password", function(e) {
        e.preventDefault();
        console.log("cliquei");
        $.ajax({
          url: "includes/read/verifyPassword.inc.php",
          type: "post",
          dataType: "json",
          data: {
            idUsuario: <?php echo $_SESSION["usuarioId"]; ?>,
            oldPassword: oldPassword.value
          },
          success: function(data) {
            let smallOld = oldPassword.parentElement.parentElement.querySelectorAll("small")[1];
            let smallNew = newPassword.parentElement.parentElement.querySelectorAll("small")[1];
            let smallCnew = cNewPassword.parentElement.parentElement.querySelectorAll("small")[1];
            if (oldPassword.value == '') {
              oldPassword.className = "form-control is-warning";
              smallOld.style.visibility = "visible";
              smallOld.style.color = "#ffc107";
              smallOld.innerText = "Campo obrigatório!";
            } else if (newPassword.value == '') {
              newPassword.className = "form-control is-warning";
              smallNew.style.visibility = "visible";
              smallNew.style.color = "#ffc107";
              smallNew.innerText = "Campo obrigatório!";
            } else if (cNewPassword.value == '') {
              cNewPassword.className = "form-control is-warning";
              smallCnew.style.visibility = "visible";
              smallCnew.style.color = "#ffc107";
              smallCnew.innerText = "Campo obrigatório!";
            } else {
              if (data == true || data == oldPassword.value) {
                oldPassword.className = "form-control is-valid";
                smallOld.style.visibility = "hidden";
                $.ajax({
                  url: "includes/update/senhaUser.inc.php",
                  type: "post",
                  data: {
                    idUsuario: <?php echo $_SESSION["usuarioId"]; ?>,
                    senha: newPassword.value
                  },
                  success: function(data) {
                    swal.fire({
                      title: "Palavra-passe alterada com sucesso!",
                      text: "Palavra-passe alterada!",
                      confirmButtonText: 'Confirmar',
                      confirmButtonColor: "#560085",
                      icon: "success",
                    });
                    oldPassword.className = "form-control";
                    oldPassword.value = "";
                    newPassword.className = "form-control";
                    newPassword.value = "";
                    cNewPassword.className = "form-control";
                    cNewPassword.value = "";
                  }
                });
              } else {
                smallOld.style.visibility = "visible";
                smallOld.style.color = "#dc3545";
                smallOld.innerText = "Palavra-passe Incorrecta!";
                oldPassword.classList.add("is-invalid");
              }
            }
          }
        });
      });
    </script>
</body>

</html>