<?php
  $page_title = 'Editar Usuario';
  require_once('../../includes/load.php');
?>
<?php
  $e_user = find_by_id('users',(int)$_GET['id']);
  $groups  = find_all('user_groups');
  if(!$e_user){
    $session->msg("d","Missing user id.");
    redirect('users.php');
  }
?>
<?php
//Update User basic info
  if(isset($_POST['update'])) {
    if(empty($errors)){
        $id = (int)$e_user['id'];
        $name = remove_junk($db->escape($_POST['full-name']));
        $username = remove_junk($db->escape($_POST['username']));
        $level = (int)$db->escape($_POST['level']);
        $status   = remove_junk($db->escape($_POST['status']));
        $last_name = remove_junk($db->escape($_POST['last_name']));
        $sex = remove_junk($db->escape($_POST['sex']));
        $celular = remove_junk($db->escape($_POST['celular']));
        $cargo = remove_junk($db->escape($_POST['cargo']));
        $licencia = remove_junk($db->escape($_POST['licencia']));
        $id_area = remove_junk($db->escape($_POST['id_area']));

         $sql = "UPDATE users SET name ='{$name}', username ='{$username}',user_level='{$level}',status='{$status}',last_name='$last_name',sex='$sex',cargo='$cargo',licencia='$licencia',celular='$celular',id_area='$id_area' WHERE id='{$db->escape($id)}'";
         $result = $db->query($sql);
          if($result && $db->affected_rows() === 1){
            //$session->msg('s',"Account Updated ");
            $session->msg('s',' Cuenta actualizada');
            redirect('users.php', false);
          } else {
            $session->msg('d',' Lo siento no se actualizó los datos.');
            redirect('edit_user.php?id='.(int)$e_user['id'], false);
          }
    } else {
      $session->msg("d", $errors);
      redirect('edit_user.php?id='.(int)$e_user['id'],false);
    }
  }
?>
<?php
// Update user password
if(isset($_POST['update-pass'])) {
  $req_fields = array('password');
  validate_fields($req_fields);
  if(empty($errors)){
           $id = (int)$e_user['id'];
     $password = remove_junk($db->escape($_POST['password']));
     $h_pass   = sha1($password);
          $sql = "UPDATE users SET password='{$h_pass}' WHERE id='{$db->escape($id)}'";
       $result = $db->query($sql);
        if($result && $db->affected_rows() === 1){
          $session->msg('s',"Se ha actualizado la contraseña del usuario. ");
          redirect('users.php', false);
        } else {
          $session->msg('d','No se pudo actualizar la contraseña de usuario..');
          redirect('edit_user.php?id='.(int)$e_user['id'], false);
        }
  } else {
    $session->msg("d", $errors);
    redirect('edit_user.php?id='.(int)$e_user['id'],false);
  }
}

?>
<?php include_once('../../layouts/header.php'); ?>
<?php echo display_msg($msg); ?>
  <div class="row col-md-16">
    <div class="panel panel-default">
          <form method="post" action="edit_user.php?id=<?php echo (int)$e_user['id'];?>" class="clearfix">
             <div class="container pt-1 mt-1 animated fadeIn">
              <div class="row pt-4">
                <div class="col-12 mb-3">
                  <p class="h1 text-center text-primary font-weight-bold"> Registrar Usuario <i class="fas fa-user-alt"></i></p>
                </div>
              </div> 
              
              <div class="row"> 
                <div class="col-12">
                  <p class="h3 text-primary">Datos Generales <i class="fas fa-user-circle"></i></p>
                </div>
                <div class="col-12 col-lg-6"> 
                  <p class="text-primary mb-1">DNI</p>
                  <div class="input-group mb-3"> 
                    <div class="input-group-prepend">
                      <span class="input-group-text"><i class="fas fa-id-card"></i></span>
                    </div>
                    <input maxlength="8"  placeholder="DNI" aria-label="DNI"  type="text" autocomplete="off" name="username" id="username" class="form-control is-requerido" value="<?php echo remove_junk(ucwords($e_user['username'])); ?>" required>
                       
                  </div>
                </div>         
              </div> 
              <div class="row">
                <div class="col-12 col-lg-6">
                  <p class="text-primary mb-1">Nombres</p>
                  <div class="input-group mb-3">
                    <div class="input-group-prepend">
                      <span class="input-group-text"><i class="fas fa-user"></i></span>
                    </div>
                    <input  maxlength="50" type="text" class="form-control is-requerido " placeholder="Nombres" autocomplete="off" name="full-name" id="full-name" aria-label="Nombres" value="<?php echo remove_junk(ucwords($e_user['name'])); ?>" required>
                  </div>
                  
                </div>
                <div class="col-12 col-lg-6">
                  <p class="text-primary mb-1">Apellidos</p>
                  <div class="input-group mb-3">
                    <div class="input-group-prepend">
                      <span class="input-group-text"><i class="fas fa-user"></i></span>
                    </div>
                    <input  maxlength="50" type="text" class="form-control is-requerido " placeholder="Apellidos" name="last_name" id="last_name" value="<?php echo remove_junk(ucwords($e_user['last_name'])); ?>" required>
                  </div>
                </div>
                <div class="col-12 col-lg-6"> 
                  <p class="text-primary mb-1">Sexo</p>
                  <div class="input-group mb-3">
                    <div class="input-group-prepend">
                      <label class="input-group-text" for="sex"><i class="fas fa-user-cog"></i></label>
                    </div> 
                    <select class="custom-select is-requerido" id="sex" name="sex" required>
                      <option value="" selected disabled>SELECCIONE</option>
                      <option <?php if($e_user['sex'] === '1') echo 'selected="selected"';?>value="1">FEMENINO</option>
                      <option <?php if($e_user['sex'] === '2') echo 'selected="selected"';?> value="2">MASCULINO</option>
                    </select>
                  </div>
                </div>
                <div class="col-12 col-lg-6">
                  <p class="text-primary mb-1">Celular</p>
                  <div class="input-group mb-3">
                    <div class="input-group-prepend">
                      <span class="input-group-text"><i class="fas fa-phone"></i></span>
                    </div>
                    <input maxlength="9" type="text" class="form-control is-requerido" placeholder="N° de Celular" name="celular" id="celular" value="<?php echo remove_junk(ucwords($e_user['celular'])); ?>" required>
                  </div>
                </div>
                <div class="col-12 col-lg-6">
                  <p class="text-primary mb-1">Licencia</p>
                  <div class="input-group mb-3">
                    <div class="input-group-prepend">
                      <span class="input-group-text"><i class="fas fa-id-card"></i></span>
                    </div>
                    <input maxlength="9" type="text" class="form-control is-requerido" placeholder="N° de Licencia" name="licencia" id="licencia" value="<?php echo remove_junk(ucwords($e_user['licencia'])); ?>" required>
                  </div>
                </div>
                <div class="col-12 col-lg-6"> 
                  <p class="text-primary mb-1">Estado</p>
                  <div class="input-group mb-3">
                    <div class="input-group-prepend">
                      <label class="input-group-text" for="status"><i class="fas fa-user-cog"></i></label>
                    </div> 
                    <select class="custom-select is-requerido" id="status" name="status" required>
                      <option value="" selected disabled>SELECCIONE</option>
                      <option <?php if($e_user['status'] === '1') echo 'selected="selected"';?>value="1">ACTIVO</option>
                      <option <?php if($e_user['status'] === '0') echo 'selected="selected"';?> value="0">NO ACTIVO</option>
                    </select>
                  </div>
                </div>
                <div class="col-12 col-lg-6">
                  <p class="text-primary mb-1">Cargo</p>
                  <div class="input-group mb-3">
                    <div class="input-group-prepend">
                      <span class="input-group-text"><i class="fas fa-user"></i></span>
                    </div>
                    <input maxlength="30" type="text" class="form-control is-requerido " placeholder="Nombre de cargo" name="cargo" id="cargo" value="<?php echo remove_junk(ucwords($e_user['cargo'])); ?>" required>
                  </div>
                </div>
                <div class="col-12 col-lg-6">
                  <p class="text-primary mb-1">Gerencia</p>
                  <div class="input-group mb-3">
                    <div class="input-group-prepend">
                      <span class="input-group-text"><i class="fas fa-user"></i></span>
                    </div>
                   
                    <select class="custom-select is-requerido" name="id_gerencia" id="id_gerencia" required> 

                        <?php
                                $id_A=$e_user['id_area'];
                                $consultaA = $db->query("SELECT * FROM area WHERE id='$id_A'");
                                $DatosA = $db->fetch_array($consultaA);
                                $consultaG = $db->query("SELECT * FROM gerencia");
                                $gerencia =$DatosA['ID_GER'];
                                while ($CGerencia = $db->fetch_array($consultaG)) {
                                $def='';
                                if($CGerencia['id']==$gerencia){
                                    $def='selected';
                                }
                        ?>
                              <option value="<?php echo $CGerencia['id']?>" <?php echo $def?> ><?php echo $CGerencia['NOMB_GER'] ?></option>
                        <?php
                                }
                        ?>         
                    </select>
                  </div>
                </div>
                <div class="col-12 col-lg-6">
                  <p class="text-primary mb-1">Área</p>
                  <div class="input-group mb-3">
                    <div class="input-group-prepend">
                      <span class="input-group-text"><i class="fas fa-user"></i></span>
                    </div>
                    <select class="custom-select is-requerido" required name="id_area" id="id_area" required>

                    </select>
                  </div>
                </div>
                <div class="col-12 col-lg-6"> 
                  <p class="text-primary mb-1">Tipo de Usuario</p>
                  <div class="input-group mb-3">
                    <div class="input-group-prepend">
                      <label class="input-group-text" for="level"><i class="fas fa-user-cog"></i></label>
                    </div> 
                      <select class="custom-select is-requerido" name="level" id="level" required>
                           <option value="" selected disabled>SELECCIONE</option>
                          <?php foreach ($groups as $group ):?>
                             <option <?php if($group['group_level'] === $e_user['user_level']) echo 'selected="selected"';?> value="<?php echo $group['group_level'];?>"><?php echo ucwords($group['group_name']);?></option>
                          <?php endforeach;?>
                      </select>
                  </div>
                </div>
              </div>    
              <div class="row mb-4">
                <div class="col-12">
                  <button class="btn btn-block btn-primary" type="submit" name="update">Actualizar Usuario</button>
                </div>
              </div>
            </div>
          </form>

  <!-- Change password form -->

        <form action="edit_user.php?id=<?php echo (int)$e_user['id'];?>" method="post" class="clearfix">
          <div class="container pt-1 mt-1 animated fadeIn">
            <div class="col-12">
                  <p class="h3 text-primary">Autentificación <i class="fas fa-id-card"></i></p>
            </div>
                 
              <div class="col-12">
                <p class="text-primary mb-1">Contraseña</p>
                <div class="input-group mb-3">
                  <div class="input-group-prepend">
                    <span class="input-group-text"><i class="fas fa-unlock-alt"></i></span>
                  </div>
                  <input type="password" class="form-control" placeholder="Contraseña" autocomplete="new-password" name ="password" id="password" required>
                </div>
              </div>
            <div class="form-group clearfix">
                    <button type="submit" name="update-pass" class="btn btn-block btn-primary">Cambiar Contraseña</button>
            </div>
          </div>
        </form>
       </div>
      </div>
<?php include_once('../../layouts/footer.php'); ?>
<script type="text/javascript" src="js/edit_user.js"></script>
<!-- script para rellenar el select de area dependiendo al id del area que esta en la tabla de usuario-->
<script type="text/javascript">
$(document).ready(function () {
    // Llenar el select de "Área" al cargar la página
    llenarSelectArea();

});
function llenarSelectArea() {
    var gerenciaId = $("#id_gerencia").val();
    var areaIdUsuario = <?php echo $e_user['id_area']; ?>;
    
    // Realizar una solicitud AJAX para obtener las áreas según la gerencia seleccionada
    $.ajax({
        url: "data/data_edit.php", // Ruta al archivo PHP que manejará la solicitud AJAX
        method: "POST",
        data: { gerencia: gerenciaId }, // Enviar el ID de la gerencia seleccionada
        dataType: "json",
        success: function (data) {
            // Limpiar el select de áreas
            $("#id_area").empty();

            // Agregar las opciones de área al select
            $.each(data, function (key, value) {
              var option = $('<option>', {
                  value: value.id,
                  text: value.NOMB_AREA
              });

              if (value.id == areaIdUsuario) {
                  option.attr('selected', 'selected');
              }

              $("#id_area").append(option);
          });
        }
    });
}
</script>