<div class="row">
  <div class="col-lg-12">
    <div class="card">
      <div class="card-header">
        <div class="card-widgets">
          <button type="button" class="btn btn-danger btn-sm" onclick="location.reload()"><i class="fa fa-redo"></i> Recargar</button>
          <button type="button" class="btn btn-primary btn-sm" onclick="add()"><i class="fa fa-plus"></i> Nuevo</button>
        </div>
        <h3 class="card-title mb-0">Lista de <?= $this->titulo_controlador ?></h3>
      </div>
      <!-- /.box-header -->
      <div class="card-body table-responsive">
        <table id="tabla" class="table table-striped table-bordered dt-responsive nowrap" style="border-collapse: collapse; border-spacing: 0; width: 100%;">
          <thead>
          <tr class="bg-primary text-white">
              <th>#</th>
              <th>Tipo</th>
              <th>RUC</th>
              <th>Razon Social</th>
              <th>Nombre</th>
              <th>Direccion</th>
              <th>Acciones</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
      <!-- /.box -->
    </div>
  </div>
</div>

<!-- Bootstrap modal -->
<div id="modal_form" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form action="#" id="form" class="form-horizontal" autocomplete="off">
          <input type="hidden" class="form-control" id="id" name="id">
          <div class="form-group row">
            <div class="col-md-6">
              <label class="control-label">Tipo</label>
              <select id="tipo" name="tipo" class="form-control">
                <option value="0">NATURAL</option>
                <option value="1">JURIDICA</option>
              </select>
              <span class="help-block"></span>
            </div>
            <div class="col-md-6">
              <label class="control-label">RUC</label>
              <div class="col-md-12 input-group">
                <input class="form-control" id="documento" type="text" name="documento">
                <span class="help-block"></span>
                <span class="input-group-btn">
                  <button type="button" class="btn btn-primary" id="botoncito"><span class="fa fa-search"></span></button>
                </span>
              </div>
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group row">
            <div class="col-md-6">
              <label class="control-label">Razon Social<span class="required">*</span></label>
              <input class="form-control" id="razonsocial" type="text" name="razonsocial">
              <span class="help-block"></span>
            </div>
            <div class="col-md-6">
              <label class="control-label">Nombre Comercial</label>
              <input class="form-control" id="nombre" type="text" name="nombre">
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group row">
            <div class="col-md-6">
              <label class="control-label">Direccion<span class="required">*</span></label>
              <input class="form-control" id="direccion" type="text" name="direccion">
              <span class="help-block"></span>
            </div>
            <div class="col-md-6">
              <label class="control-label">Telefono</label>
              <input class="form-control" id="telefono" type="text" name="telefono">
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group row">
            <div class="col-md-6">
              <label class="control-label">Celular</label>
              <input class="form-control" id="celular" type="text" name="celular">
              <span class="help-block"></span>
            </div>
            <div class="col-md-6">
              <label class="control-label">Serie<span class="required">*</span></label>
              <input class="form-control" id="serie" type="text" name="serie">
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group row">
            <div class="col-md-6">
              <label class="control-label">Ubigeo<span class="required">*</span></label>
              <input class="form-control" id="ubigeo" type="text" name="ubigeo">
              <span class="help-block"></span>
            </div>
            <div class="col-md-6">
              <label class="control-label">Departamento</label>
              <input class="form-control" id="departamento" type="text" name="departamento">
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group row">
            <div class="col-md-6">
              <label class="control-label">Provincia</label>
              <input class="form-control" id="provincia" type="text" name="provincia">
              <span class="help-block"></span>
            </div>
            <div class="col-md-6">
              <label class="control-label">Distrito</label>
              <input class="form-control" id="distrito" type="text" name="distrito">
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group row">
            <div class="col-md-4">
              <label class="control-label">Tipo de Proceso</label>
              <select id="tipoproceso" name="tipoproceso" class="form-control">
                <option value="2">PRODUCCION</option>
                <!-- <option value="1">HOMOLOGACION</option> -->
                <option value="0">BETA</option>
              </select>
              <span class="help-block"></span>
            </div>
            <div class="col-md-4">
              <label class="control-label">Usuario SOL<span class="required">*</span></label>
              <input class="form-control" id="usuariosol" type="text" name="usuariosol">
              <span class="help-block"></span>
            </div>
            <div class="col-md-4">
              <label class="control-label">Clave SOL<span class="required">*</span></label>
              <input class="form-control" id="clavesol" type="text" name="clavesol">
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group row">
            <div class="col-md-6">
              <label class="control-label">Tipo de Impresora<span class="required">*</span></label>
              <select id="tipoimpresora" name="tipoimpresora" class="form-control">
                <option value="0">TERMICA</option>
                <option value="1">TIQUETERA</option>
                <option value="2">DOMINIO</option>
              </select>
              <span class="help-block"></span>
            </div>
            <div class="col-md-6">
              <label class="control-label">Nombre Impresora</label>
              <input class="form-control" id="nombreimpresora" type="text" name="nombreimpresora">
              <span class="help-block"></span>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Guardar</button>
        <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->

<script type="text/javascript">
  //for save method string
  var save_method;
  var table;
  $(document).ready(function() {
    $("#razonsocial").mayusculassintildes();
    $("#nombre").mayusculassintildes();
    $("#direccion").mayusculassintildes();
    $("#departamento").mayusculassintildes();
    $("#distrito").mayusculassintildes();
    $("#provincia").mayusculassintildes();
    $('#documento').attr('minLength', 11);
    $('#documento').attr('maxlength', 11);
    $("#documento").numeric();
    $("#serie").numeric();
    $("#ubigeo").numeric();
    //datatables
    table = $('#tabla').DataTable({
      language: {
        "decimal": "",
        "emptyTable": "No hay información",
        "info": "Mostrando _START_ a _END_ de _TOTAL_ Entradas",
        "infoEmpty": "Mostrando 0 to 0 of 0 Entradas",
        "infoFiltered": "(Filtrado de _MAX_ total entradas)",
        "infoPostFix": "",
        "thousands": ",",
        "lengthMenu": "Mostrar _MENU_ Entradas",
        "loadingRecords": "Cargando...",
        "processing": "Procesando...",
        "search": "Buscar:",
        "zeroRecords": "Sin resultados encontrados",
        "paginate": {
          "first": "Primero",
          "last": "Ultimo",
          "next": "Siguiente",
          "previous": "Anterior"
        }
      },
      // Load data for the table's content from an Ajax source
      "ajax": {
        "url": "<?= $this->url ?>/ajax_list",
        "type": "POST"
      },
    });
    //set input/textarea/select event when change value, remove class error and remove text help block
    $("input").change(function() {
      $(this).parent().parent().removeClass('has-error');
      $(this).next().empty();
    });
    $("textarea").change(function() {
      $(this).parent().parent().removeClass('has-error');
      $(this).next().empty();
    });
    $("select").change(function() {
      $(this).parent().parent().removeClass('has-error');
      $(this).next().empty();
    });
    //datatables
    $('#botoncito').on('click', function() {
      $(this).empty();
      $(this).append('<i class="fa fa-spinner fa-spin"></i>');
      $(this).attr('disabled', true);
      $.ajax({
        url: "<?= $this->url ?>/consulta_reniec/" + $('#documento').val(),
        method: "POST",
        dataType: "json",
        beforeSend: function() {
          $('[name="razonsocial"]').val("");
          $('[name="direccion"]').val("");
          $('[name="nombre"]').val("");
          $('[name="departamento"]').val("");
          $('[name="provincia"]').val("");
          $('[name="distrito"]').val("");
        },
        success: function(data) {
          $("#botoncito").empty();
          $('#botoncito').append('<i class="fa fa-search"></i>');
          $('#botoncito').attr('disabled', false);
          $('[name="razonsocial"]').val(data.razonSocial);
          $('[name="direccion"]').val(data.direccion);
          $('[name="nombre"]').val(data.nombreComercial);
          $('[name="departamento"]').val(data.departamento);
          $('[name="provincia"]').val(data.provincia);
          $('[name="distrito"]').val(data.distrito);
        },
        error: function(data) {
          $("#botoncito").empty();
          $('#botoncito').append('<i class="fa fa-search"></i>');
          $('#botoncito').attr('disabled', false);
          Lobibox.notify('error', {
            size: 'mini',
            msg: 'Error al obtener datos de ajax.'
          });
        }
      });
    });
  });

  function add() {
    save_method = 'add';
    $('#form')[0].reset(); // reset form on modals
    $('.form-group').removeClass('has-error'); // clear error class
    $('.help-block').empty(); // clear error string
    $('#modal_form').modal('show'); // show bootstrap modal
    $('.modal-title').text('Crear <?= $this->controlador ?>'); // Set Title to Bootstrap modal title
  };

  function save() {
    $('#btnSave').text('guardando...'); //change button text
    $('#btnSave').attr('disabled', true); //set button disable
    var url;
    if (save_method == 'add') {
      url = "<?= $this->url ?>/ajax_add";
      msgsuccess = "El registro fue creado exitosamente.";
      msgerror = "El registro no se pudo crear verifique las validaciones.";
    } else {
      url = "<?= $this->url ?>/ajax_update";
      msgsuccess = "El registro fue actualizado exitosamente.";
      msgerror = "El registro no se pudo actualizar. Verifique la operación";
    }
    // ajax adding data to database
    $.ajax({
      url: url,
      type: "POST",
      data: $('#form').serialize(),
      dataType: "JSON",
      success: function(data) {
        //if success close modal and reload ajax table
        if (data.status) {
          $('#modal_form').modal('hide');
          reload_table();
          Lobibox.notify('success', {
            size: 'mini',
            msg: msgsuccess
          });
        } else {
          for (var i = 0; i < data.inputerror.length; i++) {
            $('[name="' + data.inputerror[i] + '"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
            $('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[i]); //select span help-block class set text error string
          }
        }
        $('#btnSave').text('Guardar'); //change button text
        $('#btnSave').attr('disabled', false); //set button enable
      },
      error: function(jqXHR, textStatus, errorThrown) {
        Lobibox.notify('error', {
          size: 'mini',
          msg: msgerror
        });
        $('#btnSave').text('Guardar'); //change button text
        $('#btnSave').attr('disabled', false); //set button enable
      }
    });
  };

  function reload_table() {
    table.ajax.reload(null, false); //reload datatable ajax
  };

  function edit(id) {
    save_method = 'update';
    $('#form')[0].reset(); // reset form on modals
    $('.form-group').removeClass('has-error'); // clear error class
    $('.help-block').empty(); // clear error string
    //Ajax Load data from ajax
    $.ajax({
      url: "<?= $this->url ?>/ajax_edit/" + id,
      type: "GET",
      dataType: "JSON",
      success: function(data) {
        $('[name="id"]').val(data.id);
        $('[name="tipo"]').val(data.tipo);
        $('[name="documento"]').val(data.ruc);
        $('[name="razonsocial"]').val(data.razonsocial);
        $('[name="nombre"]').val(data.nombre);
        $('[name="serie"]').val(data.serie);
        $('[name="direccion"]').val(data.direccion);
        $('[name="telefono"]').val(data.telefono);
        $('[name="celular"]').val(data.celular);
        $('[name="departamento"]').val(data.departamento);
        $('[name="provincia"]').val(data.provincia);
        $('[name="distrito"]').val(data.distrito);
        $('[name="ubigeo"]').val(data.ubigeo);
        $('[name="usuariosol"]').val(data.usuariosol);
        $('[name="clavesol"]').val(data.clavesol);
        $('[name="tipoproceso"]').val(data.tipoproceso);
        $('[name="tipoimpresora"]').val(data.tipoimpresora);
        $('[name="nombreimpresora"]').val(data.nombreimpresora);
        $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
        $('.modal-title').text('Modificar <?= $this->titulo_controlador ?>'); // Set title to Bootstrap modal title
      },
      error: function(jqXHR, textStatus, errorThrown) {
        Lobibox.notify('error', {
          size: 'mini',
          msg: 'Error al obtener datos de ajax.'
        });
      }
    });
  };

  function borrar(id) {
    bootbox.confirm("Seguro desea Eliminar este registro?", function(result) {
      if (result === true) {
        $.ajax({
          url: "<?= $this->url ?>/ajax_delete/" + id,
          type: "POST",
          dataType: "JSON",
          success: function(data) {
            //if success reload ajax table
            $('#modal_form').modal('hide');
            reload_table();
            Lobibox.notify('success', {
              size: 'mini',
              msg: 'El registro fue eliminado exitosamente.'
            });
          },
          error: function(jqXHR, textStatus, errorThrown) {
            Lobibox.notify('error', {
              size: 'mini',
              msg: 'No se puede eliminar este registro por seguridad de su base de datos, Contacte al Administrador del Sistema'
            });
          }
        });
      }
    });
  };
</script>
