<style>
  .custom-file-label {
    cursor: pointer;
  }
</style>
<div class="row">
  <div class="col-md-12">
    <div class="card card-outline card-primary">
      <div class="card-header">
        <h3 class="card-title">
          <i class="fas fa-tags text-primary mr-2"></i> Lista de <?= $this->controlador ?>
        </h3>
        <div class="card-tools">
          <a onclick="location.reload()" class="btn btn-default btn-sm" data-toggle="tooltip" title="RECARGAR"><i class="fas fa-sync-alt"></i></a>
          <a onclick="add()" class="btn btn-primary btn-sm" data-toggle="tooltip" title="Nuevo"><i class="fas fa-plus"></i> Nuevo <?= $this->controlador ?></a>
        </div>
      </div>
      <!-- /.card-header -->
      <div class="card-body table-responsive">
        <table id="tabla" class="table table-hover table-bordered table-striped">
          <thead>
            <tr>
              <th width="50">#</th>
              <th width="60">Imagen</th>
              <th>Descripcion</th>
              <th>Codigo</th>
              <th>Opciones</th>
              <th>Estado</th>
              <th width="150">Acción</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
      <!-- /.card-body -->
    </div>
  </div>
</div>

<!-- Modal Principal -->
<div class="modal fade" id="modal_form" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"></h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form action="#" id="form" autocomplete="off" enctype="multipart/form-data">
          <input type="hidden" id="id" name="id">
          <div class="form-group">
            <label>Nombre de la Categoría <span class="text-danger">*</span></label>
            <input type="text" name="nombre" class="form-control" id="nombre">
            <span class="help-block text-danger"></span>
          </div>

          <div class="form-group" style="display: none;">
            <label>Ticketera (Destino de Impresión)</label>
            <select name="clase" class="form-control" id="clase" style="width: 100%;">
              <option value="">Seleccione Destino</option>
              <option value="COCINA">COCINA</option>
              <option value="BAR">BAR</option>
            </select>
          </div>

          <div class="form-group">
            <label>Imagen de Categoría</label>
            <div class="custom-file">
              <input type="file" class="custom-file-input" id="foto" name="foto">
              <label class="custom-file-label" for="foto">Elegir archivo...</label>
            </div>
            <div id="image_preview" class="mt-2 text-center" style="display: none;">
              <img src="" id="current_image" class="img-thumbnail" style="max-height: 150px;">
            </div>
          </div>

          <div class="row mt-2">
            <div class="col-md-6">
              <div class="custom-control custom-switch">
                <input type="checkbox" class="custom-control-input" id="chkCocina" name="chkCocina" value="1">
                <label class="custom-control-label" for="chkCocina">Enviar a Cocina</label>
              </div>
            </div>
            <div class="col-md-6">
              <div class="custom-control custom-switch">
                <input type="checkbox" class="custom-control-input" id="chkExtras" name="chkExtras" value="1">
                <label class="custom-control-label" for="chkExtras">Permitir Extras</label>
              </div>
            </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>
  </div>
</div>

<!-- Modal Opciones -->
<div class="modal fade" id="modal_opcion" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content" style="border-radius: 15px; overflow: hidden;">
      <div class="modal-header bg-gradient-navy text-white">
        <h5 class="modal-title font-weight-bold"><i class="fas fa-list-ul mr-2"></i> AGREGAR OPCIONES</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body p-4">
        <form id="form_opcion" autocomplete="off">
          <input type="hidden" name="idcategoria" id="idcategoria">
          <input type="hidden" name="idopcion" id="idopcion">
          <div class="form-group">
            <label class="font-weight-bold text-muted small">Nombre de la Opción</label>
            <div class="input-group shadow-sm">
              <input type="text" name="opcion" id="opcion" class="form-control border-right-0" placeholder="Ej: Término medio, Sin cebolla...">
              <div class="input-group-append">
                <button type="button" class="btn btn-primary font-weight-bold" id="btnOpcion" onclick="saveopcion()">
                  <i class="fas fa-save mr-1"></i> Guardar
                </button>
              </div>
            </div>
          </div>
        </form>
        
        <div class="table-responsive mt-4">
          <table id="tabla_opcion" class="table table-sm table-hover table-striped" style="width: 100%;">
            <thead class="thead-light">
              <tr>
                <th width="40">#</th>
                <th>Opción</th>
                <th>Estado</th>
                <th width="100">Acción</th>
              </tr>
            </thead>
            <tbody class="small"></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Modal Extras -->
<div class="modal fade" id="modal_extras" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content" style="border-radius: 15px; overflow: hidden;">
      <div class="modal-header bg-gradient-success text-white">
        <h5 class="modal-title font-weight-bold"><i class="fas fa-plus-circle mr-2"></i> ADMINISTRAR EXTRAS DE LA CATEGORÍA</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body p-4">
        <form id="form_extras" autocomplete="off">
          <input type="hidden" name="idcategoria" id="idcategoriaextras">
          <input type="hidden" name="idextras" id="idextras">
          <div class="row align-items-end">
            <div class="col-md-6 form-group">
              <label class="font-weight-bold text-muted small">Nombre del Adicional / Extra</label>
              <input type="text" name="nombreextra" id="nombreextra" class="form-control shadow-sm" placeholder="Ej: Extra Papas, Queso derretido...">
            </div>
            <div class="col-md-3 form-group">
              <label class="font-weight-bold text-muted small">Precio Adicional (S/.)</label>
              <input type="number" step="0.10" name="precioextra" id="precioextra" class="form-control shadow-sm" placeholder="0.00">
            </div>
            <div class="col-md-3 form-group">
              <button type="button" class="btn btn-success btn-block font-weight-bold shadow-sm" id="btnExtras" onclick="saveextras()">
                <i class="fas fa-save mr-1"></i> Guardar
              </button>
            </div>
          </div>
        </form>
        
        <div class="table-responsive mt-4">
          <table id="tabla_extras" class="table table-sm table-hover table-striped" style="width: 100%;">
            <thead class="thead-light">
              <tr>
                <th width="40">#</th>
                <th width="60">Imagen</th>
                <th>Extra</th>
                <th>Precio (S/.)</th>
                <th>Estado</th>
                <th width="120">Acción</th>
              </tr>
            </thead>
            <tbody class="small"></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
  var save_method;
  var table;
  var table_opcion;
  var table_extras;

  $(document).ready(function() {
    table = $('#tabla').DataTable({
      language: dtlanguage,
      "ajax": {
        "url": "<?= $this->url ?>/ajax_list",
        "type": "POST"
      },
      "columnDefs": [{ "targets": [-1], "orderable": false }]
    });

    $("input, select").change(function() {
      $(this).removeClass('is-invalid');
      $(this).nextAll('.help-block').empty();
    });

    $(".custom-file-input").on("change", function() {
      var fileName = $(this).val().split("\\").pop();
      $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
    });
  });

  function add() {
    save_method = 'add';
    $('#form')[0].reset();
    $('.custom-file-label').html('Elegir archivo...');
    $('#image_preview').hide();
    $('.form-control').removeClass('is-invalid');
    $('.help-block').empty();
    $('#modal_form').modal('show');
    $('.modal-title').text('Crear Categoria');
    $("#chkCocina").prop("checked", true);
  }

  function save() {
    $('#btnSave').text('guardando...').attr('disabled', true);
    var url = save_method == 'add' ? "<?= $this->url ?>/ajax_add" : "<?= $this->url ?>/ajax_update";
    
    $.ajax({
      url: url,
      type: "POST",
      data: new FormData($("#form")[0]),
      dataType: "JSON",
      contentType: false,
      processData: false,
      success: function(data) {
        if (data.status) {
          $('#modal_form').modal('hide');
          reload_table();
          
          if (data.upload_error) {
            Swal.fire({
              icon: 'warning',
              title: 'Guardado con aviso',
              text: data.upload_error,
              timer: 3000,
              showConfirmButton: false,
              toast: true,
              position: 'bottom-end'
            });
          } else {
            Swal.fire({
              icon: 'success',
              title: '¡Éxito!',
              text: 'Operación realizada correctamente',
              timer: 2000,
              showConfirmButton: false,
              toast: true,
              position: 'bottom-end'
            });
          }
        } else {
          for (var i = 0; i < data.inputerror.length; i++) {
            $('[name="' + data.inputerror[i] + '"]').addClass('is-invalid');
            $('[name="' + data.inputerror[i] + '"]').nextAll('.help-block').text(data.error_string[i]);
          }
        }
        $('#btnSave').text('Guardar').attr('disabled', false);
      },
      error: function() {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'Ocurrió un problema al procesar la solicitud',
          toast: true,
          position: 'bottom-end',
          timer: 3000,
          showConfirmButton: false
        });
        $('#btnSave').text('Guardar').attr('disabled', false);
      }
    });
  }

  function edit(id) {
    save_method = 'update';
    $('#form')[0].reset();
    $('.custom-file-label').html('Elegir archivo...');
    $('.form-control').removeClass('is-invalid');
    $('.help-block').empty();
    $.ajax({
      url: "<?= $this->url ?>/ajax_edit/" + id,
      type: "GET",
      dataType: "JSON",
      success: function(data) {
        $('[name="id"]').val(data.id);
        $('[name="nombre"]').val(data.nombre);
        $('[name="clase"]').val(data.clase);
        if (data.photo) {
          $('#current_image').attr('src', "<?= base_url() ?>files/productocategoria/" + data.photo);
          $('#image_preview').show();
        } else {
          $('#image_preview').hide();
        }
        $("#chkCocina").prop("checked", data.estadococina == '1');
        $("#chkExtras").prop("checked", data.estadoextras == '1');
        $('#modal_form').modal('show');
        $('.modal-title').text('Modificar Categoria');
      }
    });
  }

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

  function borrar(id) {
    Swal.fire({
      title: '¿Estás seguro?',
      text: "Esta acción eliminará la categoría permanentemente",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Sí, eliminar',
      cancelButtonText: 'Cancelar'
    }).then((result) => {
      if (result.isConfirmed) {
        $.ajax({
          url: "<?= $this->url ?>/ajax_delete/" + id,
          type: "POST",
          dataType: "JSON",
          success: function() { 
            reload_table(); 
            Swal.fire({
              icon: 'success',
              title: 'Eliminado',
              toast: true,
              position: 'bottom-end',
              timer: 2000,
              showConfirmButton: false
            });
          }
        });
      }
    });
  }

  function editopcion(id) {
    $.ajax({
      url: "<?= $this->url ?>/ajax_editopcion/" + id,
      type: "GET",
      dataType: "JSON",
      success: function(data) {
        $('#idopcion').val(data.id);
        $('#opcion').val(data.nombre);
        $('#btnOpcion').html('<i class="fas fa-sync-alt mr-1"></i> Actualizar');
      }
    });
  }

  function borraropcion(id) {
    Swal.fire({
      title: '¿Eliminar opción?',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      confirmButtonText: 'Eliminar'
    }).then((result) => {
      if (result.isConfirmed) {
        $.ajax({
          url: "<?= $this->url ?>/ajax_deleteopcion/" + id,
          type: "POST",
          dataType: "JSON",
          success: function() { 
            table_opcion.ajax.reload(null, false); 
            reload_table(); 
            Swal.fire({ icon: 'success', title: 'Eliminado', toast: true, position: 'bottom-end', timer: 2000, showConfirmButton: false }); 
          }
        });
      }
    });
  }

  function activaropcion(id) {
    $.ajax({ url: "<?= $this->url ?>/ajax_activaropcion/" + id, type: "POST", success: function() { table_opcion.ajax.reload(null, false); } });
  }

  function desactivaropcion(id) {
    $.ajax({ url: "<?= $this->url ?>/ajax_desactivaropcion/" + id, type: "POST", success: function() { table_opcion.ajax.reload(null, false); } });
  }

  function opciones(categoria) {
    $('#idcategoria').val(categoria);
    $('#idopcion').val(0);
    $('#opcion').val("");
    $('#btnOpcion').html('<i class="fas fa-save mr-1"></i> Guardar');
    table_opcion = $('#tabla_opcion').DataTable({
      language: dtlanguage,
      destroy: true,
      "ajax": {
        "url": "<?= $this->url ?>/ajax_listopcion",
        "type": "POST",
        "data": { categoria: categoria }
      }
    });
    $('#modal_opcion').modal('show');
  }

  function saveopcion() {
    $('#btnOpcion').attr('disabled', true);
    var url = $('#idopcion').val() == 0 ? "<?= $this->url ?>/ajax_addopcion" : "<?= $this->url ?>/ajax_updateopcion";
    $.ajax({
      url: url,
      type: "POST",
      data: new FormData($("#form_opcion")[0]),
      dataType: "JSON",
      contentType: false,
      processData: false,
      success: function(data) {
        if (data.status) {
          $('#idopcion').val(0); $('#opcion').val("");
          $('#btnOpcion').html('<i class="fas fa-save mr-1"></i> Guardar');
          table_opcion.ajax.reload(null, false);
          reload_table();
          Swal.fire({ icon: 'success', title: 'Guardado', toast: true, position: 'bottom-end', timer: 2000, showConfirmButton: false });
        }
        $('#btnOpcion').attr('disabled', false);
      }
    });
  }

  function activar(id) {
    $.ajax({ url: "<?= $this->url ?>/ajax_activar/" + id, type: "POST", success: function() { reload_table(); } });
  }

  function desactivar(id) {
    $.ajax({ url: "<?= $this->url ?>/ajax_desactivar/" + id, type: "POST", success: function() { reload_table(); } });
  }

  function extrascategoria(categoria) {
    $('#idcategoriaextras').val(categoria);
    $('#idextras').val(0);
    $('#nombreextra').val("");
    $('#precioextra').val("");
    $('#btnExtras').html('<i class="fas fa-save mr-1"></i> Guardar');
    
    table_extras = $('#tabla_extras').DataTable({
      language: dtlanguage,
      destroy: true,
      "ajax": {
        "url": "<?= $this->url ?>/ajax_list_extras/" + categoria,
        "type": "POST"
      }
    });
    $('#modal_extras').modal('show');
  }

  function saveextras() {
    $('#btnExtras').attr('disabled', true);
    var url = $('#idextras').val() == 0 ? "<?= $this->url ?>/ajax_saveextras" : "<?= $this->url ?>/ajax_update_saveextras";
    $.ajax({
      url: url,
      type: "POST",
      data: new FormData($("#form_extras")[0]),
      dataType: "JSON",
      contentType: false,
      processData: false,
      success: function(data) {
        if (data.status) {
          $('#idextras').val(0); 
          $('#nombreextra').val("");
          $('#precioextra').val("");
          $('#btnExtras').html('<i class="fas fa-save mr-1"></i> Guardar');
          table_extras.ajax.reload(null, false);
          reload_table();
          Swal.fire({ icon: 'success', title: 'Guardado', toast: true, position: 'bottom-end', timer: 2000, showConfirmButton: false });
        } else {
          for (var i = 0; i < data.inputerror.length; i++) {
            $('[name="' + data.inputerror[i] + '"]').addClass('is-invalid');
          }
          Swal.fire({ icon: 'error', title: 'Error de validación', text: 'Completa los campos obligatorios', toast: true, position: 'bottom-end', timer: 3000, showConfirmButton: false });
        }
        $('#btnExtras').attr('disabled', false);
      },
      error: function() {
        Swal.fire({ icon: 'error', title: 'Error', text: 'Ocurrió un problema en la solicitud', toast: true, position: 'bottom-end', timer: 3000, showConfirmButton: false });
        $('#btnExtras').attr('disabled', false);
      }
    });
  }

  function editExtras(id) {
    $.ajax({
      url: "<?= $this->url ?>/ajax_editvariante/" + id,
      type: "GET",
      dataType: "JSON",
      success: function(data) {
        $('#idextras').val(data.id);
        $('#nombreextra').val(data.nombre);
        $('#precioextra').val(data.precio);
        $('#btnExtras').html('<i class="fas fa-sync-alt mr-1"></i> Actualizar');
      }
    });
  }

  function borrarExtras(id) {
    Swal.fire({
      title: '¿Eliminar extra?',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      confirmButtonText: 'Eliminar',
      cancelButtonText: 'Cancelar'
    }).then((result) => {
      if (result.isConfirmed) {
        $.ajax({
          url: "<?= $this->url ?>/ajax_eliminar_extras/" + id,
          type: "POST",
          dataType: "JSON",
          success: function() { 
            table_extras.ajax.reload(null, false); 
            reload_table(); 
            Swal.fire({ icon: 'success', title: 'Eliminado', toast: true, position: 'bottom-end', timer: 2000, showConfirmButton: false }); 
          }
        });
      }
    });
  }

  function activarExtras(id) {
    $.ajax({ url: "<?= $this->url ?>/ajax_activar_extras/" + id, type: "POST", success: function() { table_extras.ajax.reload(null, false); } });
  }

  function desactivarExtras(id) {
    $.ajax({ url: "<?= $this->url ?>/ajax_desactivar_extras/" + id, type: "POST", success: function() { table_extras.ajax.reload(null, false); } });
  }
</script>