<?php

session_start();
if(isset($_SESSION['nomUsuario'])){
  
    $usuario = $_SESSION['nomUsuario'];
    $rol_usuario=$_SESSION['rolUsuario'];
    $id=$_SESSION['cveUsuario'];
    if ($rol_usuario == 'MESERO' || $rol_usuario == 'MESERA') {
      include("path/header.php");
    }else{
      echo "<script> 
            document.location.href='../functions/salir.php';
        </script>";
    }
}else{
echo "<script> 
      document.location.href='/aqua-restaurant/';
  </script>";
}


?>

<div class="row">
  <div class="col-lg-12">
    <div class="row">
      <div class="col-md-12 mb-lg-0">
        <div class="card-header">
          <div class="row">
            <div class="col-lg-6 col-sm-6 mt-2">
              
              <a href="sale_note.php">
                <i class="material-icons  ms-auto text-dark cursor-pointer redondo-b" style="width: 70px; height:70px;" data-bs-toggle="tooltip" data-bs-placement="top" title="Nueva nota de venta"><img style="padding: 20%;" width="70" src="../assets/img/icons/nota.png"></i>
              </a>
              <a href="#" style="margin-left: 15%"><i class="material-icons ms-auto text-dark cursor-pointer redondo-b" style="width: 70px; height:70px;" data-bs-toggle="tooltip" data-bs-placement="top" title="Refrescar" id="btn_refrescar"><img style="padding: 20%;" width="70" src="../assets/img/icons/reload.png"></i></a>
            
              <a href="/aqua-restaurant/functions/salir.php" style="margin-left: 15%"><i class="material-icons ms-auto text-dark cursor-pointer redondo-b" style="width: 70px; height:70px;" data-bs-toggle="tooltip" data-bs-placement="top" title="Cerrar Sesion"><img style="padding: 20%;" width="70" src="../assets/img/icons/sesion.png"></i></a>
            </div>
            <div class="col-lg-3 col-sm-3 mb-2">
              <h6 class="font-weight-bold notes-title text-center"><?php echo $usuario?></h6>
            </div>
            <div class="col-lg-3 col-sm-3 mt-2 text-end ">
              <!-- <img width="210" src="../assets/img/logos/logo.png"> -->
              <div class="row" >
                  <div id="content" class="col-lg-12 col-sm-10">  
                      <div class="date" style="display: none;">
                          <span id="weekDay" class="weekDay"></span>, 
                          <span id="day" class="day"></span> de
                          <span id="month" class="month"></span> del
                          <span id="year" class="year"></span>
                      </div>
                      <div style="position: relative; left: 10px;" class="clock mt-3 ">
                          <span class="hours h2">H: </span>
                          <span id="hours" class="hours h2"></span> :
                          <span id="minutes" class="minutes h2"></span> <!-- :
                          <span id="seconds" class="seconds h2"></span> -->
                      </div>
                  </div>
              </div>
            </div>
            
          </div>
        </div>
        
      </div>
      
      <div class="col-12" id="notas_venta_max">
        <div class="card my-1">
          <div class="card-body px-0">
            <div class="table-responsive" >
              <table class="table compact" id="tabla_notas" style="width:100%;" >
                <thead class="text-3xl d-none" style="background: #052659; color: white" >
                  <tr >
                    <th class="align-middle text-center text-white" >Nota</th>
                    <th class="align-middle text-center text-white" >Fecha</th>
                    <th class="align-middle text-center text-white" >Úl. cambio</th>
                    <th class="align-middle text-center text-white" >E</th>
                    <th class="align-middle text-center text-white" >M</th>
                    <th class="align-middle text-center text-white" >P</th>
                    <th class="align-middle text-center text-white" >Comensal</th>
                    <th class="align-middle text-center text-white" >Ver</th>
                    <th class="align-middle text-center text-white" >Edt</th>
                    <th class="align-middle text-center text-white" >Imp</th>
                  </tr>
                </thead>
                <tbody class="text-2xl" id="notasTableRow" >
                </tbody>
              </table>
            </div>
          </div>

        </div>
      </div>

      <div class="col-12" id="notas_venta_min">
        <div class="card my-1">
          <div class="card-body px-0">
            <div class="table-responsive" >
              <table class="table compact" id="tabla_notas_venta" style="width:100%;">
                <thead class="text-3xl d-none" style="background: #052659; color: white">
                  <tr >
                    <th class="align-middle text-center text-white" >Nota</th>
                    <th class="align-middle text-center text-white" >Úl. cambio</th>
                    <th class="align-middle text-center text-white" >E</th>
                    <th class="align-middle text-center text-white" >M</th>
                    <th class="align-middle text-center text-white" >P</th>
                    <th class="align-middle text-center text-white" >Comensal</th>
                    <th class="align-middle text-center text-white" >Ver</th>
                    <th class="align-middle text-center text-white" >Edt</th>
                    <th class="align-middle text-center text-white" >Imp</th>
                  </tr>
                </thead>
                <tbody class="text-2xl " id="notasTableRow" >
                </tbody>
              </table>
            </div>
          </div>

        </div>
      </div>
    </div>
  </div>

  <!-- Modal Imprimir Nota -->
<div class="modal fade" id="ModalImprimir" tabindex="-1" aria-labelledby="ModalImprimirLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm-lg ">
    <div class="modal-content">
      <!-- <div class="modal-header">
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div> -->
      <div class="modal-body">
          <div class="card h-50">
            <div class="card-header">
              <!-- <div class="row">
                <div class="col-12 d-flex align-items-center">
                  <h4 class="mb-0">Opciones para imprimir</h4>
                </div>
              </div> -->
            </div>
            <div class="card-body p-3 pb-0">
              <div class="row d-flex">
                <div class="col-6 d-flex align-items-center justify-content-center">
                  <!-- <button type="button" class="btn btn-primary text-white h5" id="btn_chef_1_imp">CUENTA</button> -->
                    <form action="../functions/tablet/ticket/ticket_nota_venta.php" method="POST" target="_blank">
                        <input type="hidden" name="btn_imprimir_id" id="btn_imprimir_id" value="0">
                        <button type="submit" class="btn btn-primary text-white h5" id="btn_chef_1_imp">CUENTA</button>
                    </form>
                </div>
                <!-- <div class="col-3 d-flex align-items-center justify-content-center">
                  <button type="button" class="btn btn-primary text-white h5" id="btn_chef_2_imp">IMP 2</button>
                </div> -->
                <div class="col-6 d-flex align-items-center justify-content-center">
                  <!-- <button type="button" class="btn btn-primary text-white h5" id="btn_todos_imp">TODO</button> -->
                   <form action="../functions/tablet/ticket/ticket_comanda.php" method="POST" target="_blank">
                        <input type="hidden" name="btn_nota_todo_id" id="btn_nota_todo_id" value="0">
                        <button type="submit" class="btn btn-primary text-white h5" id="btn_todos_imp">TODO</button>
                    </form>
                </div>
                <!-- <div class="col-3 d-flex align-items-center justify-content-center">
                  <button type="button" class="btn btn-primary text-white h5" id="btn_ultimos_imp">ULTIM</button>
                </div> -->
              </div>
            </div>
          </div>
          <div class="card h-50">
            <div class="card-header">
              <div class="row">
                <div class="col-12 d-flex align-items-center">
                  <h4 class="mb-0">Datos de la nota:</h4>
                </div>
              </div>
            </div>
            <div class="card-body p-3 pb-0">
              <div class="row d-flex">
                <div class="col-6 d-flex align-items">
                  <h5 >Clave de la nota: </h5><h5 id="clv_nota_venta_im"></h5>
                </div>
                <div class="col-6 d-flex align-items">
                  <h5 for="" >Mesa: </h5> <h5 id="msa_im"></h5>
                </div>
              </div>
              <br>
              <div class="row d-flex">
                <div class="col-6 d-flex align-items">
                  <h5 for=""> Total a pagar: </h5><h5 id="total_im" data-value=''></h5>
                </div>
                <div class="col-6 d-flex align-items">
                  <h5 for="">Mesero: </h5><h5 id="mesero"></h5>
                </div>
              </div>
            </div>
          </div>
          <div class="card h-100">
            <div class="card-header pb-0 p-3">
              <div class="row">
                <div class="col-12 d-flex align-items-center">
                  <h4 class="mb-0">Selecciona el metodo de pago:</h4>
                </div>
              </div>
            </div>
            <div class="card-body p-3 pb-0" id="tipo_pago">
              <div class="form-check pt-1">
                <input class="form-check-input h5" type="radio" name="flexRadioDefault1" id="flexRadioDefault6"  value="1" checked>
                <label class="form-check-label h5" for="flexRadioDefault6">
                  Tarjeta de credito
                </label>
              </div>
              <div class="form-check pt-1">
                <input class="form-check-input h5" type="radio" name="flexRadioDefault1" id="flexRadioDefault5" value="2" >
                <label class="form-check-label h5" for="flexRadioDefault5">
                  Efectivo
                </label>
              </div>
              <div class="form-check pt-1">
                <input class="form-check-input h5" type="radio" name="flexRadioDefault1" id="flexRadioDefault4" value="3" >
                <label class="form-check-label h5" for="flexRadioDefault4">
                  AMBOS
                </label>
              </div>
            </div>
          </div>
          <div id="pago_efec_tarj"></div>
      </div>
      <div class="modal-footer2">
        <div class="row">
          <div class="col-4 d-flex justify-content-center">
            <button type="button" class="btn btn-primary text-white h5" id="btn_finalizar_nota">Finalizar</button>
          </div>
          <div class="col-4">

          </div>
          <div class="col-4 d-flex justify-content-center">
            <button type="button" class="btn btn-secondary h5" id="btn-cerrar2" data-bs-dismiss="modal">Cerrar</button>
          </div>
        </div>
       
        
        <!-- <button type="button" class="btn btn-success text-white h5" id="btn_imprimir">Imprimir</button> -->
      </div>
    </div>
  </div>
</div>

<!-- Mostrar Productos de la Nota -->
<div class="modal fade" id="ModalMostrarProductos" tabindex="-1" aria-labelledby="ModalMostrarProductosLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm-lg ">
    <div class="modal-content">
      <!-- <div class="modal-header">
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div> -->
      <div class="modal-body">
          <div class="card h-50">
            <div class="card-header">
              <div class="row">
                <div class="col-4 d-flex align-items-center">
                  <h4 class="mb-0" id="nota_venta"></h4>
                </div>
                <div class="col-4 d-flex align-items-center">
                  <h4 class="mb-0">H: </h4> <span class="mb-0 h4" id="hora_nt"></span>
                </div>
                
                <div class="col-4 d-flex align-items-center">
                  <span class="mb-0 h4" id="fecha_nt"></span>
                </div>
                <div class="col-4 d-flex align-items-center">
                  <h4 class="mb-0">M: </h4> <span class="mb-0 h4" id="mesa_nt"></span>
                </div>
                <div class="col-4 d-flex align-items-center">
                  <h4 class="mb-0">C: </h4> <span class="mb-0 h4" id="comensal_nt"></span>
                </div>
                <div class="col-4 d-flex align-items-center">
                  <h4 class="mb-0">Total: </h4> <span class="mb-0 h4" id="total_nt"></span>
                </div>
                
                
              </div>
            </div>
            <div class="card-body p-3 pb-0">
              <div class="table-responsive " >
                  <table class="table nowrap " id="ProductsTable" style="width:100%;">       
                      <thead class="text-5xl" style="background: #052659;">
                          <tr>
                          <th class="align-middle text-center text-white" scope="col" style="max-width: 100px; font-size: 2rem !important;">Cant</th>
                          <th class="align-middle text-center text-white" scope="col" style="max-width: 600px; font-size: 2rem !important;">Producto</th>
                          <th class="align-middle text-center text-white" scope="col" style="max-width: 600px; font-size: 2rem !important;">Comentarios</th>
                          <th class="align-middle text-center text-white" scope="col" style="max-width: 300px; font-size: 2rem !important;">Tiemp</th>
                          <th class="align-middle text-center text-white" scope="col" style="max-width: 140px; font-size: 2rem !important;">Precio</th>
                          </tr>
                      </thead>
                      <tbody class="">
                      </tbody>
                    </table>
                </div>
            </div>
          </div>
         
      </div>
      <div class="modal-footer2">
        <div class="row">
          <div class="col-4 d-flex justify-content-center">
            
          </div>
          <div class="col-4">

          </div>
          <div class="col-4 d-flex justify-content-center">
            <button type="button" class="btn btn-secondary h5" id="btn-cerrar" data-bs-dismiss="modal">Cerrar</button>
          </div>
        </div>
       </div>
    </div>
  </div>
</div>

<!-- Modal Eliminar Renglon -->
<div class="modal fade" id="modalAlert" tabindex="-1" aria-labelledby="modalAlert" aria-hidden="true">
  <div class="modal-dialog modal-sm-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header" style="background-color: #ECC950">
          <div class="col-12 d-flex align-items-center justify-content-center">
              <img src="../assets/img/icons/alert-circle.png" alt="" width="250px">
          </div>
        
      </div>
      <div class="modal-body">
      
        <div class="row ">
          <div class="col-12 d-flex align-items-center justify-content-center">
            <h3>Finalizando Nota</h3>
             
          </div>
          <div class="col-12 d-flex align-items-center justify-content-center">
            <h6 class="mb-0">¿Estas seguro de finalizar la nota?</h6> 
          </div>
        </div>
      </div>
      <div class="modal-footer2">
        <div class="row">
          <div class="col-4 d-flex justify-content-center">
            <button type="button" class="btn btn-primary text-white h4" id="finalizar_nota">Finalizar</button>
          </div>
          <div class="col-4">

          </div>
          <div class="col-4 d-flex justify-content-center">
            <button type="button" class="btn btn-secondary h4" data-bs-dismiss="modal" id="cerrar_modal">Cerrar</button>
          </div>
        </div>
        
      </div>
    </div>
  </div>
</div>

<script src="../assets/js/jquery-3.5.1.min.js"></script>
<script src="../assets/lib/dataTable/datatables.min.js"></script>
<script src="../assets/js/funciones.js"></script>

<script src="../assets/js/clock.js"></script>
<script>
  $(document).ready(function () {
      
    $('#notas_venta_min').hide();
    $('#notas_venta_max').hide();
    
    var mq = window.matchMedia( "(max-width: 800px)" );
      if (mq.matches) {
        // console.log('table 800')
        $('#tabla_notas_venta thead').removeClass('d-none');
        $('#notas_venta_min').css('display','block');
        $('#tabla_notas_venta').DataTable({
            //order: [[4, 'Desc']],
            ordering: false,
            dom: 'Blfrtip',
            searching: false,  
            lengthChange: false,
            buttons: [],
            pagingType: 'simple_numbers',
            language: {
                url: '../assets/lib/dataTable/spanish.json',
            },
            paging: false,
            scrollY: 'calc(107vh - 300px)',
            scrollX: true,
            fixedHeader: true,
            bFilter: false, 
            bInfo: false,
            columns: [
                {data: 'nota', class: 'text-col-table text-center'},
                {data: 'cambio', class: 'text-col-table text-center'},
                {data: 'estatus', class: 'text-col-table text-center'},
                {data: 'mesa', class: 'text-col-table text-center'},
                {data: 'personas', class: 'text-col-table text-center'},
                {data: 'comensal', class: 'text-col-table text-center'},
                {data: 'ver', class: 'text-col-table text-center'},
                {data: 'editar', class: 'text-col-table text-center'},
                {data: 'imprimir', class: 'text-col-table text-center'},
              ],
          });
      }else{
        $('#tabla_notas thead').removeClass('d-none');
        $('#notas_venta_max').css('display','block');
        $('#tabla_notas').DataTable({
            //order: [[4, 'Desc']],
            ordering: false,
            dom: 'Blfrtip',
            searching: false,  
            lengthChange: false,
            buttons: [],
            pagingType: 'simple_numbers',
            language: {
                url: '../assets/lib/dataTable/spanish.json',
            },
            paging: false,
            scrollY: 'calc(107vh - 300px)',
            scrollX: true,
            fixedHeader: true,
            bFilter: false, 
            bInfo: false,
            columns: [
                {data: 'nota', class: 'text-col-table text-center'},
                {data: 'fecha', class: 'text-col-table text-center'},
                {data: 'cambio', class: 'text-col-table text-center'},
                {data: 'estatus', class: 'text-col-table text-center'},
                {data: 'mesa', class: 'text-col-table text-center'},
                {data: 'personas', class: 'text-col-table text-center'},
                {data: 'comensal', class: 'text-col-table text-center'},
                {data: 'ver', class: 'text-col-table text-center'},
                {data: 'editar', class: 'text-col-table text-center',},
                {data: 'imprimir', class: 'text-col-table text-center',},
              ],
          });
      }
      $.ajax({
      type: 'POST',
      dataType: 'JSON',
      data: { idProducto: 0 },
      url: '../functions/tablet/notas/notas.php',
      success: function (respuesta) {
        putNotas(respuesta);
        //seleccionarFila();
      }, error(e) {
        console.log(e);
      }
    });

    $('#ProductsTable').DataTable({
        ordering: false,
        dom: 'Blfrtip',
        searching: false,  
        lengthChange: false,
        buttons: [],
        pagingType: 'simple_numbers',
        language: {
            url: '../assets/lib/dataTable/spanish.json',
        },
        paging: false,
        scrollY: 'calc(72vh - 300px)',
        scrollX: true,
        fixedHeader: true,
        bFilter: false, 
        bInfo: false,
        columns: [
            {data: 'Cantidad', class: 'text-col-table text-center border-bottom-tb col_table_prd'},
            {data: 'Nombre', class: 'text-col-table col-table text-center border-bottom-tb col_table_prd'},
            {data: 'Comentarios', class: 'text-col-table col-table text-center border-bottom-tb col_table_prd'},
            {data: 'Tiempo', class: 'text-col-table text-center border-bottom-tb col_table_prd'},
            {data: 'Precio', class: 'text-col-table text-center border-bottom-tb col_table_prd'},
        ],
    });
    
    $('#btn_refrescar').on('click', function(){
      location.href ="/aqua-restaurant/usuario_mesero/sale_notes.php";
    })

    $('#btn-cerrar').on('click', function(){
      $('#ModalMostrarProductos').modal("toggle");
    });
    $('#btn-cerrar2').on('click', function(){
      $('#ModalImprimir').modal("toggle");
    });
    $("#cerrar_modal").on('click', function(){
      $('#modalAlert').modal("toggle");
    });
    $("#btn_chef_1_imp").unbind("click").on("click", function(){
      setTimeout(function() {
                        location.href ="/aqua-restaurant/usuario_mesero/sale_notes.php";
        }, 3000)
    })
  });
  
  function mostrarProductos(id){
    let pagina = "../functions/tablet/notas/list_note_products.php"; 
    let datos = { id_nota: id }; 
    let dtipo = "JSON"; 
    let tipo = "POST"; 
    let selector = putNoteProducts;
    ajax_function(pagina, datos, dtipo, tipo, selector);
  }
  function putNoteProducts(dt){
    // console.log(dt);
    
    let tabla = $('#ProductsTable').DataTable();
    let bg_color = '';
    let status = 0;
    tabla.rows().remove().draw();
    if (dt[0].id > 0) {
      $.each(dt, function (v, u) {
        if (u.pdn_estatus == 'terminado') {
          bg_color = 'bg-color-green';
          status = 1;
        }else{
          bg_color = '';
          status = 0;
        }
        tabla.row
          .add({
            Cantidad: u.pdn_cantidad,
            Nombre: `<div class="producto" id="pdn${u.id}"> ${u.pro_nombre}</div>` ,
            Comentarios: u.pdn_comentario,
            Tiempo: u.pdn_tiempo,
            Precio: u.pro_precio_venta,
            
          })
        .draw();
        $('#pdn' + u.id).parents('tr').attr('id', u.id).attr('data-tiempo', u.pdn_tiempo).attr('data-total', u.total).attr('data-idProd', u.id_producto).attr('data-new', 0).attr('data-status', status).addClass(bg_color);
      });
    }
  }
  function putNotas(dt){
    
    var mq = window.matchMedia( "(max-width: 800px)" );
    
    if (mq.matches) {
      console.log('800');
      let tabla = $('#tabla_notas_venta').DataTable();
      if (dt[0]['id'] > 0) {
        $.each(dt, function (v, u) {
            //console.log(u.ntv_no_nota);
            icon1 = "../assets/img/icons/iconos-13.png";
            icon2 = "../assets/img/icons/impresion.png";
            icon3="../assets/img/icons/eye-outline.png"
            backbround1='bg-gradient-info';
            backbround2='bg-gradient-success';
            backbround3='btn-primary';
            color = u.activar_color;
            w_color = '';
            if(color == 1){
              w_color = 'change_color_imp2';
            }

            tabla.row
                  .add({
                    nota: u.ntv_no_nota,
                    cambio: u.ntv_hora_edt,
                    estatus:  u.ntv_estatus,
                    mesa: u.ntv_no_mesa,
                    personas: u.ntv_no_personas,
                    comensal: u.pdn_comensal,
                    ver: `<button class="badge badge-sm btn ${backbround3} see_note" type="submit" name="nota_ver"
              id="${u.id}" value="${u.id}" data-complement="${u.ntv_no_nota}|${u.ntv_fecha_creacion}|${u.ntv_hora_edt}|${u.ntv_no_mesa}|${u.pdn_comensal}|${u.ntv_total_nota}"><img width="35"
              src="${icon3}">`,
                    editar: `<form action="sale_note.php" method="post" id="formularioEditarNota">
                        <button class="badge badge-sm btn ${backbround1}" type="submit" name="nota_edt"
              id="nota_edt_${u.id}" value="${u.id}"><img width="35"
              src="${icon1}">
              </form>`,
                    imprimir: `<button class="badge badge-sm btn ${backbround2} print" type="button" name="imprimir_nota"
              id="imprimir_nota" data-id="${u.id}" data-complement="${u.cant_productos}"><img width="35"
              src="${icon2}">`,
                  })
                  .draw();
              $("#nota_edt_"+u.id).parents('tr').addClass(w_color);
          });
      } 
    }else{
      let tabla = $('#tabla_notas').DataTable();
      if (dt[0]['id'] > 0) {
      $.each(dt, function (v, u) {
          //console.log(u.ntv_no_nota);
          icon1 = "../assets/img/icons/iconos-13.png";
          icon2 = "../assets/img/icons/impresion.png";
          icon3="../assets/img/icons/eye-outline.png"
          backbround1='bg-gradient-info';
          backbround2='bg-gradient-success';
          backbround3='btn-primary';
          color = u.activar_color;
          w_color = '';
          if(color == 1){
            w_color = 'change_color_imp2';
          }

          tabla.row
                .add({
                  nota: u.ntv_no_nota,
                  fecha:  u.ntv_fecha_creacion,
                  cambio: u.ntv_hora_edt,
                  estatus:  u.ntv_estatus,
                  mesa: u.ntv_no_mesa,
                  personas: u.ntv_no_personas,
                  comensal: u.pdn_comensal,
                  ver: `<button class="badge badge-sm btn ${backbround3} see_note" type="submit" name="nota_ver"
              id="${u.id}" value="${u.id}" data-complement="${u.ntv_no_nota}|${u.ntv_fecha_creacion}|${u.ntv_hora_edt}|${u.ntv_no_mesa}|${u.pdn_comensal}|${u.ntv_total_nota}"><img width="40"
              src="${icon3}">`,
                  editar: `<form action="sale_note.php" method="post" id="formularioEditarNota">
                        <button class="badge badge-sm btn ${backbround1} " type="submit" name="nota_edt"
              id="nota_edt_${u.id}" value="${u.id}"><img width="40"
              src="${icon1}">
              </form>`,
                  imprimir: `<button class="badge badge-sm btn ${backbround2}  print" type="button" name="boton_imprimir"
            id="boton_imprimir" data-id="${u.id}" data-complement="${u.cant_productos}"><img width="40"
            src="${icon2}">`,
                })
                .draw();
                
          $("#nota_edt_"+u.id).parents('tr').addClass(w_color);
        });
      } 
    }

    $('#tabla_notas tbody tr td button.print').unbind('click').on('click',function(){
        //console.log($(this).attr('data-id'));
        let note_id = $(this).attr('data-id');
        let cantidad_productos = $(this).attr('data-complement')

        getNota(note_id)
        $('#ModalImprimir').modal('show');
        $('#btn_imprimir').attr('data-ntvid', note_id);
        
        /* $("#btn_chef_2_imp").attr('data-ntvid', note_id); */
        /* $('#btn_ultimos_imp').attr('data-ntvid', note_id); */
        $('#btn_imprimir_id').val(note_id);
        $('#btn_nota_todo_id').val(note_id);
        
        if(cantidad_productos>0){
          $('#btn_finalizar_nota').css('display','block')
          $('#btn_chef_1_imp').css('display','block')
          $('#btn_todos_imp').css('display','block')
          $('#btn_finalizar_nota').attr('data-ntvid', note_id);
        }else{
          $('#btn_finalizar_nota').css('display','none')
          $('#btn_chef_1_imp').css('display','none')
          $('#btn_todos_imp').css('display','none')
        }
        $('#flexRadioDefault4').on('change', function(){
          $('#pago_efec_tarj').load('../functions/tablet/notas/pagos_efec_tarj.php');
        });
        $('#flexRadioDefault5').on('change', function(){
          $('#pago_efec_tarj').empty();
        });
        $('#flexRadioDefault6').on('change', function(){
          $('#pago_efec_tarj').empty();
        });

    })

    $('#tabla_notas tbody tr td button.see_note').unbind('click').on('click',function(){
        let note_id = $(this).attr('id');
        $('#ModalMostrarProductos').modal('show');
        let nota = $(this).attr('data-complement').split('|')[0]
        let fecha = $(this).attr('data-complement').split('|')[1]
        let hora = $(this).attr('data-complement').split('|')[2]
        let mesa = $(this).attr('data-complement').split('|')[3]
        let comensal = $(this).attr('data-complement').split('|')[4]
        let total = $(this).attr('data-complement').split('|')[5]
        datosNota(nota, fecha, hora, mesa, comensal,total);
        mostrarProductos(note_id)

    })

    $('#tabla_notas_venta tbody tr td button.print').unbind('click').on('click',function(){
        //console.log($(this).attr('data-id'));
        let note_id = $(this).attr('data-id');
        let cantidad_productos = $(this).attr('data-complement')
        getNota(note_id)
        $('#ModalImprimir').modal('show');
        $('#btn_imprimir').attr('data-ntvid', note_id);
        console.log("im",note_id)
        $('#btn_imprimir_id').val(note_id);
        /* $("#btn_chef_2_imp").attr('data-ntvid', note_id); */
        $('#btn_nota_todo_id').val(note_id);
        /* $('#btn_ultimos_imp').attr('data-ntvid', note_id); */

        if(cantidad_productos>0){
          $('#btn_finalizar_nota').css('display','block')
          $('#btn_chef_1_imp').css('display','block')
          $('#btn_todos_imp').css('display','block')
          $('#btn_finalizar_nota').attr('data-ntvid', note_id);
        }else{
          $('#btn_chef_1_imp').css('display','none')
          $('#btn_todos_imp').css('display','none')
          $('#btn_nota_todo_id').css('display','none')
        }

        $('#flexRadioDefault4').on('change', function(){
          $('#pago_efec_tarj').load('../functions/tablet/notas/pagos_efec_tarj.php');
        });
        $('#flexRadioDefault5').on('change', function(){
          $('#pago_efec_tarj').empty();
        });
        $('#flexRadioDefault6').on('change', function(){
          $('#pago_efec_tarj').empty();
        });

    })

    $('#tabla_notas_venta tbody tr td button.see_note').unbind('click').on('click',function(){
        let note_id = $(this).attr('id');
        $('#ModalMostrarProductos').modal('show');
        let nota = $(this).attr('data-complement').split('|')[0]
        let fecha = $(this).attr('data-complement').split('|')[1]
        let hora = $(this).attr('data-complement').split('|')[2]
        let mesa = $(this).attr('data-complement').split('|')[3]
        let comensal = $(this).attr('data-complement').split('|')[4]
        let total = $(this).attr('data-complement').split('|')[5]
        datosNota(nota, fecha, hora, mesa, comensal,total);
        mostrarProductos(note_id)

    })

    /* $('#btn_imprimir').unbind('click').on('click', function(){
      let nt_id = $(this).attr('data-ntvid')
       imprimirCuenta(nt_id)
      //imprimir(nt_id, "smb://mi_cabanita_2:1234@MI-CABANITA2/BIXOLON-SRP-350plusIII")
    }) */

    /* $('#btn_chef_1_imp').on('click', function(){
      let nt_id = $(this).attr('data-ntvid')
      imprimirCuenta(nt_id)
      //imprimir(nt_id, "smb://mi_cabanita_2:1234@MI-CABANITA2/BIXOLON-SRP-350plusIII");
      $("#nota_edt_"+nt_id).parents('tr').addClass('change_color_imp2')
    }) */
   /*  $("#btn_chef_2_imp").on('click', function(){
      let nt_id = $(this).attr('data-ntvid')
      imprimir(nt_id, "smb://mi_cabanita_3:1234@Micabanita3/bixolon-srp-350iii");
      $("#nota_edt_"+nt_id).parents('tr').addClass('change_color_imp2')
    }) */
   /*  $('#btn_todos_imp').on('click', function(){
      let nt_id = $(this).attr('data-ntvid')
      //imprimirTodos(nt_id);
    }) */
    /* $('#btn_ultimos_imp').on('click', function(){
      let nt_id = $(this).attr('data-ntvid')
      imprimirUltimos(nt_id);
    }) */

    $('#btn_finalizar_nota').unbind('click').on('click', function(){
      let id = $(this).attr('data-ntvid')
      let tipo = $('input[type="radio"]:checked').val();
      let pago_tjt = $('#pago_total_tarjeta').val();
      let pago_efc = $('#pago_total_efectivo').val();

      
      $("#finalizar_nota").attr('data-nota',id).attr('data-tipo',tipo).attr('data-pago-tjt',pago_tjt).attr('data-pago-efc',pago_efc)
      
      $("#ModalImprimir").modal('toggle')
      $("#modalAlert").modal('show')
      
      
    })

    $("#finalizar_nota").on('click', function(){
      let id = $(this).attr('data-nota')
      let tipo = $(this).attr('data-tipo')
      let pago_tjt = $(this).attr('data-pago-tjt')
      let pago_efc = $(this).attr('data-pago-efc')
      
      if (tipo == 1) {
        pago_tjt = $('#total_im').attr('data-value');
        pago_efc = 0;
      }else if(tipo == 2){
        pago_efc =$('#total_im').attr('data-value');
        pago_tjt = 0;
      }
      
      if (parseFloat(pago_tjt)+parseFloat(pago_efc) >= parseFloat($('#total_im').attr('data-value'))) {

        finalizarNota(id, tipo, pago_tjt, pago_efc)
      }
    })
    
    //tabla.rows().remove().draw();
  }

  function datosNota(nota, fecha, hora, mesa, comensal,total){
    console.log(total)
    $('#nota_venta').text(nota)
    $('#hora_nt').text(hora)
    $('#fecha_nt').text(fecha)
    $('#mesa_nt').text(mesa)
    $('#comensal_nt').text(comensal)
    $('#total_nt').text('$ '+total)
  }
  function getNota(id){
    let pagina = "../functions/tablet/notas/get_nota.php"; 
    let datos = {id: id }; 
    let dtipo = "JSON"; 
    let tipo = "POST"; 
    let selector = putNota;
    ajax_function(pagina, datos, dtipo, tipo, selector);

  }
  function putNota(dt){
    $('#clv_nota_im').text(dt[0].ntv_no_nota);
    $('#clv_nota_venta_im').text(dt[0].ntv_no_nota);
    $('#msa_im').text(dt[0].ntv_no_mesa);
    $('#total_im').text(dt[0].ntv_total_nota);
    $('#mesero').text(dt[0].uss_nombre);
    $('#total_im').attr('data-value',(dt[0].ntv_total_nota));
  }
  /* function imprimir(id, impresora){
    let pagina = "../functions/tablet/ticket/ticket_nota_venta_red.php"; 
    let datos = {id: id, opcionImprComanda: impresora}; 
    let dtipo = "JSON"; 
    let tipo = "POST"; 
    let selector = impreso;
    ajax_function(pagina, datos, dtipo, tipo, selector);
  } */

  function impreso(dt){
    console.log(dt);
  }

  function finalizarNota(id, tipo_p, tarjt, efect){
    console.log(id, tipo_p,tarjt, efect);
    let pagina = "../functions/tablet/notas/terminar.php"; 
    let datos = {id: id, tipo_pago: tipo_p, tarjt: tarjt, efect: efect}; 
    let dtipo = "JSON"; 
    let tipo = "POST"; 
    let selector = notaTerminada;
    ajax_function(pagina, datos, dtipo, tipo, selector);

  }
  function notaTerminada(dt){
    location.href ="/aqua-restaurant/usuario_mesero/sale_notes.php";
  }
  function terminar_nota(datos2){
  
    $.ajax({
          data: datos2,
          url: '../functions/terminar_nota_1.php',
          type: 'post',
          success:  function (response) {
            console.log(response);
            if(response==1){
              
            }else{
              
              $('#ModalImprimir').modal('toggle');
              $('#modalFalloProductosNota').modal('show');
            }
            
          },
          error: function (error) {
              console.log(error); 
          }
        });
  }
function imprimirTodos(id){
    let impresora = 'smb://mi_cabanita_2:1234@MI-CABANITA2/BIXOLON-SRP-350plusIII'; // Nombre de la impresora
    //let pagina = "../functions/tablet/ticket/ticket_chef_red.php"; 
    let pagina = "../functions/tablet/ticket/ticket_meseros_red.php"; 
    let datos = {id: id, opcionImprComanda: impresora}; 
    let dtipo = "JSON"; 
    let tipo = "POST"; 
    let selector = impreso;
    ajax_function(pagina, datos, dtipo, tipo, selector);
}
function imprimirUltimos(id){
    let impresora = 'smb://mi_cabanita_2:1234@MI-CABANITA2/BIXOLON-SRP-350plusIII'; // Nombre de la impresora
    let pagina = "../functions/tablet/ticket/ticket_meseros_ultimos_red.php"; 
    let datos = {id: id, opcionImprComanda: impresora}; 
    let dtipo = "JSON"; 
    let tipo = "POST"; 
    let selector = impreso;
    ajax_function(pagina, datos, dtipo, tipo, selector);
}
/** FUNCION AJAX */
function ajax_function(pagina, datos, dtipo, tipo, selector){
    $.ajax({
      type: tipo,
      dataType: dtipo,
      data: datos,
      url: pagina,
      success: function (respuesta) {
        selector(respuesta)
      }, error(e) {
        console.log(e);
      }
    });
  }
</script>