<?php

if($_SESSION["nombre"] == "INVENTARIO"){

  echo '<script>

    window.location = "inicio";

  </script>';

  return;

}

?>

<style>


.select2-container--default .select2-selection--single {
    background-color: #fff;
    border: 1px solid #aaa;
    border-radius: 4px;
    height: calc(2.25rem + 2px);
}
.row1 {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: nowrap;
}
</style>

<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header" style="padding: 2px;">
      <div class="container-fluid">
        <div class="row mb-2">
          
        </div>
      </div><!-- /.container-fluid -->
    </section>

    
    <!-- Main content -->
    <section class="content">

      <!-- Default box -->
      <div class="card">
        <div class="card-header">
          <button class="btn btn-outline-warning float-left btn-sm" data-toggle="modal" data-target="#modalAgregarClientes">
            Agregar Cliente
          </button>
     

          
        </div>


        <div class="card-body">
          <table style="font-size:85%" class="table table-bordered table-hover table-sm dt-responsive cliente">
          <thead>
                <tr>
                  <th style="width: 10px">#</th>
                  <th>ID</th>
                  <th>RUC/DNI</th>
                  <th>Nombre/Razon Social</th>
                  <th>Teléfono</th>
                  <th>Dirección</th>
                  <th>Total compras</th>
                  <th>Ultima compra</th>
                  <th>Acciones</th>
                </tr>
                </thead>
                <tbody>
                <?php 

                
  
                  $item = null;
                  $value = null;

                  $clientes = ControladorClientes:: ctrMostrarClientes($item, $value);

                  foreach($clientes as $key => $value){

                  
                    $telefono = ltrim($value["telefono"], '(+51)' );

                    echo '<tr>
                            <td></td>
                            <td>'.$value["id"].'</td>
                            <td>'.$value["ruc_dni"].'</td>
                            <td>'.$value["razon_social"].'</td>
                            <td>'.$telefono.'</td>
                            <td>'.$value["direccion"].'</td>
                            <td>'.$value["total_compras"].'</td>
                            <td>'.$value["ultima_compra"].'</td>
                            <td>
                              <div class="btn-group">
                                <button class=" btn btn-warning btnEditarCliente" idCliente="'.$value["id"].'" data-toggle="modal" data-target="#modalEditarCliente"><i class="fas fa-pencil-alt"></i></button>';
                                
                                if ($_SESSION["nombre"] == "ADMINISTRADOR") {

                                echo'<button class=" btn btn-danger btnEliminarCliente" idCliente="'.$value["id"].'" ><i class="fa fa-times"></i></button>';
                              
                                }
                              echo '</div>
                            </td>

                          </tr>';
                  }
                  ?>
                </tbody>


          </table>
        </div>

      </div>
      <!-- /.card -->

    </section>
    <!-- /.content -->
  </div>

  <!--=====================================
MODAL AGREGAR CLIENTE
======================================-->

 <div class="modal fade" id="modalAgregarClientes">
        <div class="modal-dialog">
          <div class="modal-content">
    <form role="form" method="post" >

            <div class="modal-header" style="background: #EAA354; color: white">
              <h4 class="modal-title">Agregar Cliente</h4>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>

            <div class="modal-body">
              <div class="box-body">

              <div class="form-group">
                <div class="input-group mb-3">
                <div class="input-group-append">
                  <div class="input-group-text">
                    <span class="fas fa-key"></span>
                  </div>
                  </div>
                  <select class="form-control input-lg " name="clientedoc" style ="width: 10px;" id="clientedoc" required>
                                        <option value="">Seleccionar Documento</option>
                                        <option value="RUC">RUC</option>
                                        <option value="DNI">DNI</option>
                  </select>
                  </div>
                </div>

                <div class="form-group clientes">
                
                </div>
                <div class="form-group">
                <div class="input-group mb-3">
                <div class="input-group-append">
                  <div class="input-group-text">
                    <span class="fas fa-user"></span>
                  </div>
                  </div>
                    <input type="text" class="form-control input-lg focusNext razon_social" onkeypress="return permite(event, 'car')" tabindex="2"  name="nuevoNombre" id="nuevoNombre" placeholder="Ingresar Nombre o Razón social" required>
                  </div>
                </div>

                <div class="form-group">
                <div class="input-group mb-3">
                <div class="input-group-append">
                  <div class="input-group-text">
                    <span class="fas fa-envelope"></span>
                  </div>
                  </div>
                    <input type="email" class="form-control input-lg focusNext" tabindex="3"  name="nuevoCorreo" id="nuevoCorreo" placeholder="Ingresar Correo">
                  </div>
                </div>

                <div class="form-group">
                <div class="input-group mb-3">
                <div class="input-group-append">
                  <div class="input-group-text">
                    <span class="fas fa-phone"></span>
                  </div>
                  </div>
                    <input type="text" class="form-control input-lg focusNext" tabindex="4"  name="nuevoTelefono" id="nuevoTelefono" placeholder="Ingresar Telefono" data-inputmask="'mask':'(+51) 999-999-999'" data-mask>
                  </div>
                </div>

                        <div class="form-group">
                          <div class="input-group mb-3">
                            <div class="input-group-append">
                              <div class="input-group-text">
                                <span class="fas fa-map-marker"></span>
                              </div>
                            </div>
                            <input type="text" class="form-control input-lg focusNext direccion" onkeypress="return permite(event, 'num_car')"  tabindex="8"  name="nuevoDireccion" id="nuevoDireccion" placeholder="Ingresar Direccion" required>
                          </div>
                        </div>
                 

  
              </div>
            </div>


            <div class="modal-footer justify-content-between">
              <button type="button" class="btn btn-default" data-dismiss="modal">Salir</button>
              <button type="submit" tabindex="10" class="btn btn-warning">Guardar</button>
            </div>
            <?php 
            
            $crearCliente = new ControladorClientes();
            $crearCliente -> ctrCrearCliente();
            
            ?>
        </form>
          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
      </div>
      <!-- /.modal -->
      
  <!--=====================================
MODAL EDITAR CLIENTE
======================================-->

<div class="modal fade" id="modalEditarCliente">
        <div class="modal-dialog">
          <div class="modal-content">
    <form role="form" method="post" >

            <div class="modal-header" style="background: #EAA354; color: white">
              <h4 class="modal-title">Editar Cliente</h4>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>

            <div class="modal-body">
              <div class="box-body">

              <div class="form-group">
                <div class="input-group mb-3">
                <div class="input-group-append">
                  <div class="input-group-text">
                    <span class="fas fa-key"></span>
                  </div>
                  </div>
                    <input type="number" class="form-control input-lg focusNext" tabindex="1" name="editarRuc" id="editarRuc" required>
                    <input type="hidden"  name="idcliente" id="idcliente">
                    <input type="hidden"  name="fecha" id="fecha">
                  </div>
                </div>

                <div class="form-group">
                <div class="input-group mb-3">
                <div class="input-group-append">
                  <div class="input-group-text">
                    <span class="fas fa-user"></span>
                  </div>
                  </div>
                    <input type="text" class="form-control input-lg focusNext razon_social" onkeypress="return permite(event, 'car')"  tabindex="2" name="editarNombre" id="editarNombre"  required>
                  </div>
                </div>

                <div class="form-group">
                <div class="input-group mb-3">
                <div class="input-group-append">
                  <div class="input-group-text">
                    <span class="fas fa-envelope"></span>
                  </div>
                  </div>
                    <input type="email" class="form-control input-lg focusNext" tabindex="3" name="editarCorreo" id="editarCorreo" >
                  </div>
                </div>

                <div class="form-group">
                <div class="input-group mb-3">
                <div class="input-group-append">
                  <div class="input-group-text">
                    <span class="fas fa-phone"></span>
                  </div>
                  </div>
                    <input type="text" class="form-control input-lg focusNext" tabindex="4" name="editarTelefono" id="editarTelefono"  data-inputmask="'mask':'(+51) 999-999-999'" data-mask >
                  </div>
                </div>

                <div class="row">
                  <div class="col-12">
                    <div class="form-group">
                      <div class="input-group mb-3">
                        <div class="input-group-append">
                          <div class="input-group-text">
                            <span class="fas fa-map-marker"></span>
                          </div>
                        </div>
                        <input type="text" class="form-control input-lg focusNext direccion" onkeypress="return permite(event, 'num_car')"  name="editarDireccion" tabindex="8" id="editarDireccion" required>
                      </div>
                    </div>
                  </div>
                  

                </div>

  
              </div>
            </div>


            <div class="modal-footer justify-content-between">
              <button type="button" class="btn btn-default" data-dismiss="modal">Salir</button>
              <button type="submit" class="btn btn-warning">Guardar</button>
            </div>
            <?php 
            
          $editarCliente = new ControladorClientes();
          $editarCliente -> ctrEditarCliente();
            
            ?>
        </form>
          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
      </div>
      <!-- /.modal -->
      <?php 
      
$borrarCliente = new ControladorClientes();
$borrarCliente -> ctrBorrarCliente();

?>
  <script src="./vistas/js/clientes.js"></script>
  <script>
  $(function () {
    //Initialize Select2 Elements
    $('.select2bs4').select2({
      theme: 'bootstrap4'
    })

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


  })

</script>
<script>
    document.addEventListener('keypress', function(evt) {

// Si el evento NO es una tecla Enter
if (evt.key !== 'Enter') {
  return;
}

let element = evt.target;

// Si el evento NO fue lanzado por un elemento con class "focusNext"
if (!element.classList.contains('focusNext')) {
  return;
}

// AQUI logica para encontrar el siguiente
let tabIndex = element.tabIndex + 1;
var next = document.querySelector('[tabindex="'+tabIndex+'"]');

// Si encontramos un elemento
if (next) {
  next.focus();
  event.preventDefault();
}
});
  </script>

<script>
        var elemento = document.getElementById("venta");
      elemento.className += " active";

      var elemento = document.getElementById("ven");
      elemento.className += " menu-open";
      
      var elemento = document.getElementById("cliente");
      elemento.className += " active";



  function permite(elEvento, permitidos) {
  // Variables que definen los caracteres permitidos
  var numeros = "0123456789";
  var caracteres = " aábcdeéfghiíjklmnñoópqrstuvwxyzAÁBCDEÉFGHIÍJKLMNÑOÓPQRSTUVWXYZ";
  var numeros_caracteres = numeros + caracteres;
  var teclas_especiales = [8, 37, 39, 46];
  // 8 = BackSpace, 46 = Supr, 37 = flecha izquierda, 39 = flecha derecha
 
 
  // Seleccionar los caracteres a partir del parámetro de la función
  switch(permitidos) {
    case 'num':
      permitidos = numeros;
      break;
    case 'car':
      permitidos = caracteres;
      break;
    case 'num_car':
      permitidos = numeros_caracteres;
      break;
  }
 
  // Obtener la tecla pulsada 
  var evento = elEvento || window.event;
  var codigoCaracter = evento.charCode || evento.keyCode;
  var caracter = String.fromCharCode(codigoCaracter);
 
  // Comprobar si la tecla pulsada es alguna de las teclas especiales
  // (teclas de borrado y flechas horizontales)
  var tecla_especial = false;
  for(var i in teclas_especiales) {
    if(codigoCaracter == teclas_especiales[i]) {
      tecla_especial = true;
      break;
    }
  }
 
  // Comprobar si la tecla pulsada se encuentra en los caracteres permitidos
  // o si es una tecla especial
  return permitidos.indexOf(caracter) != -1 || tecla_especial;
}


</script>
